Mr. Kaiser's Coding Website

Creating a Simple Phone Book with Java

For the last two years almost all of my projects are written in JavaScript. I am familiar with other languages, I have taken a few courses at the community college, one in Python and the other in Java. This summer I decided to take another course, Advanced Java. We are using Java – An Introduction to Problem Solving and Programming for our textbook.

I just completed a simple phone book assignment from chapter 7, the chapter focuses on arrays. The assignment gives you much of the code, it asks you to take two seperate arrays, the names of people and their phone numbers, and combine them into a single multidimensional array. Then you must write the method lookupName, the user enters a name and the method should return that person’s phone number. Below is what I just turned in. Again, I am rusty with Java, but thought I’d share regardless.

 

[code]</pre>
<pre>// Kurt Kaiser
// 7.13.2018

import java.util.Scanner;

public class PhoneBook
{
/* Creates multidimensional array of numbers and
asking for users input, calls lookup and outputs
the returned result
*/
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
String[][] listings = {
{"Michael Myers", "333-8000"},
{"Ash Williams", "333-2323"},
{"Jack Torrance", "333-6150"},
{"Freddy Krueger", "339-7970"}

};
System.out.println("Enter name to look up.");
String targetName = kbd.nextLine();
String targetPhone = lookupName(targetName, listings);
System.out.println("The phone number is " + targetPhone);

}

/* Loops through the multidimensional array of names to return
the associated number
*/
public static String lookupName(String targetName, String listings[][]){
for (int i = 0; i < 4; i++){
if (targetName.equals(listings[i][0])){
//System.out.println("Number: " + listings[i][1]);
return listings[i][1];
}
}
return "";
}

}
[/code]

No Comments Yet

Leave a Reply