i don't get the right answer, why? - java

I'm quite new to java, and I've just started the course for a few days. I wrote the following code to make a simple phone book. It gets names and phone numbers first, then it gets a name and passes the phone number. Except the first name, if I enter any name it will print the last line (the name is not in the list) then the related number!!! Why?
import java.util.Scanner;
class MyPhoneBook {
public static void main(String[] args) {
Scanner myScan = new Scanner(System.in);
String[] name = new String[200];
String[] number = new String[200];
System.out.println("when finished all contacts, just type : finish");
for (int a = 0; a < 200; a++) {
System.out.print("\nenter name:");
name[a] = myScan.nextLine();
if (name[a].equals("finish")) {
break;
} else {
}
System.out.print("enter number:");
number[a] = myScan.nextLine();
}
for (int a = 1; a > 0; a++) {
System.out.println("\nenter name to find number:\n");
String name2 = myScan.nextLine();
for (int b = 0; b < 200; b++) {
if (name2.equals(name[b])) {
System.out.println("number is " + number[b]);
break;
}
}
System.out.println("----THE NAME IS NOT IN THE LIST----\n");
}
}
}

Add a flag for when you find a name that matches user's input and dont print out last line when you find match, for that you could change your code like this:
for (int a = 1; a > 0; a++) {
System.out.println("\nenter name to find number:\n");
String name2 = myScan.nextLine();
boolean isNameFound = false;
for (int b = 0; b < 200; b++) {
if (name2.equals(name[b])) {
System.out.println("number is " + number[b]);
isNameFound = true;
break;
}
}
if (!isNameFound)
System.out.println("----THE NAME IS NOT IN THE LIST----\n");
}

Using a map will simplify this
Map<> contactBook = new Hashmap<>()
//then load the map using the phone number and name
You can also use data structure which will not allow dup names

Related

How do I access the String value inside a for loop?

Here I am not able to access the value of the name outside of the string even if I use other string the value is not initializing.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("\n\tWelcome to the Store");
System.out.print("\nPls enter the number of items you want to bill ");
int n = sc.nextInt();
String name;
for(int i = 1;i<=100;i++) {
System.out.print("Enter the name of the item no "+i+" ");
name = sc.next();
if (i == n) {
break;
}
}
System.out.println();
for(int m=1;m<=n;m++) {
//System.out.println(name);
}
}
You need to change name to be an array since it should contain several values.
String[] names = new String[n];
I also think you should use a while loop instead. Something like
Scanner sc = new Scanner(System.in);
System.out.println("\n\tWelcome to the Store");
System.out.print("\nPls enter the number of items you want to bill ");
int n = sc.nextInt();
String[] names = new String[n];
int i = 0;
while (i < n) {
System.out.print("Enter the name of the item no " + i + " ");
names[i] = sc.next();
i++;
}
System.out.println();
for (int m = 0; m < n; m++) {
System.out.println(names[m]);
}
Your question is not clear. But I hope this will fix it. Be sure to initialize variable n with a value that you want.
import java.util.*;
class example{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
String[] name = new String[100];
int n=3; // make sure to change this one
for(int i = 1;i<=3;i++){
System.out.print("Enter the name of the item no "+i+" ");
name[i] = sc.next();
}
for(int i = 1;i<=n;i++){
System.out.print(name[i]+"\n");
}
}
}

Why is the println() method being executed twice instead of once?

public class HashMapTest2 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter total player");
Integer p = s.nextInt();
System.out.println("Enter total Team");
Integer t = s.nextInt();
List<String> listp = new ArrayList<>();
for (int i = 1; i<p; i++){
System.out.println("Enter Player name "+i);
listp.add(s.nextLine());
}
List<String> listt = new ArrayList<>();
for (int i = 1; i<t; i++){
System.out.println("Enter Team name "+i);
listt.add(s.nextLine());
}
}
}
I am getting some strange outputs, like the ones below:
Enter total player
3
Enter total Team
2
Enter Player name 1
Enter Player name 2
pari
Enter Team name 1
Why is the program asking me to enter the player's name twice? For the first time it is asking for player's name twice and I don't know why. Any way to solve this?
When you are using nextInt() then the integer value is read but not the end-of-line character (Return/Enter) change your code to use nextLine() as below for correct handling.
public static void main(String... obj) {
Scanner s = new Scanner(System.in);
System.out.println("Enter number of Players");
Integer p = Integer.valueOf(s.nextLine());
System.out.println("Enter number of Teams");
Integer t = Integer.valueOf(s.nextLine());
List<String> listp = new ArrayList<>();
for (int i = 0; i < p; i++){
System.out.println("Enter Player name " + i);
listp.add(s.nextLine());
}
List<String> listt = new ArrayList<>();
for (int i = 1; i < t; i++){
System.out.println("Enter Team name " + i);
listt.add(s.nextLine());
}
}

There's an error in my Java Program about entering name and gender. Number of Male and Female is counted and printed and it repeats process

The procedure of this code must be looping until 1000 applicants enter their name and gender but it stopped at the first applicant. Please help me find out what's going on. I tried different ways but it didn't work.
Here's the code:
import java.util.Scanner;
public class Problem5 {
public static void main (String [] args)
{
Scanner myVar = new Scanner (System.in);
int b = 1000;
String [] name = new String [b];
/*enter name and gender of applicants*/
for (int i=0; i<name.length; i++)
{
int index = i;
System.out.println("Enter name of applicant and gender:");
System.out.println("M for male and F for female");
name[index] = myVar.nextLine();
for (String name1:name)
{
int maleCount = 0;
int femaleCount = 0;
if (name1.contains("M"))
{
maleCount++;
}
if (name1.contains("F"))
{
femaleCount++;
}
System.out.println("NUMBER OF MALE: "+maleCount);
System.out.println("NUMBER OF FEMALE: "+femaleCount);
}
}
}
}
The result must look like this.
For example, I type my name Isabella Cruz and my gender F.
Enter name of applicant and gender:
M for male and F for female
Isabella Cruz F
NUMBER OF MALE: 0
NUMBER OF FEMALE: 1
But, it stops there and an error came:
Exception in thread "main" java.lang.NullPointerException
at Problem5.main(Problem5.java:30)
I need solutions for this, please.
name has "Isabella Cruz F" in index 0 and the rest of the array is nulls, so name1 is null in the second iteration. Take the second loop out of the first one.
for (int i = 0; i < name.length; i++) {
//...
}
for (String name1 : name) {
//...
}
You can also use only one loop and get the data there
int maleCount = 0;
int femaleCount = 0;
for (int i = 0; i < name.length; i++)
{
int index = i;
System.out.println("Enter name of applicant and gender:");
System.out.println("M for male and F for female");
name[index] = myVar.nextLine();
if (name[index].contains("M")) {
maleCount++;
}
else if (name[index].contains("F")) {
femaleCount++;
}
}
System.out.println("NUMBER OF MALE: " + maleCount);
System.out.println("NUMBER OF FEMALE: " + femaleCount);
There is couple issues. First is there is a nested for loop. I see that you are populating the String array first then iterating over it to check for the count. You really only need one loop. Second is that you are checking if the String contains "M" or "F" which may be problematic if the persons name contains that String(Ex Joanna M Smith F). You only need to check the last character.
import java.util.Scanner;
public class Problem5 {
public static void main (String [] args)
{
Scanner myVar = new Scanner (System.in);
int b = 1000;
String [] names = new String [b];
int maleCount = 0;
int femaleCount = 0;
/*enter name and gender of applicants*/
for (int i=0; i<name.length; i++)
{
System.out.println("Enter name of applicant and gender:");
System.out.println("M for male and F for female");
String line = myVar.nextLine();
names[i] = line;
// check if the line passed in is a M or F
if (line.substring(line.length()-1).equals("M"))
{
maleCount++;
}
if (line.substring(line.length()-1).equals("F"))
{
femaleCount++;
}
System.out.println("NUMBER OF MALE: "+maleCount);
System.out.println("NUMBER OF FEMALE: "+femaleCount);
}
}
}

Java: How do I replace a string element from an array

Im a newbie in java programming and I'm trying to create a program wherein the user will be asked to input words into an array depending on the number specified by the user. Afterwards, the program will be displaying the entered words in Alphabetical order. The user will also be prompted "Which word to replace from the list?" This is the part I'm having problems. I dont know how the user can enter the new word (a string element) and replace it from the list. What I was able to come up, is to input an integer representing the position of that word from the array and replace it from the list. Dont know how can I make it as string?
import java.util.Scanner;
import java.util.Arrays;
public class EnterArrays {
public static void main ( String args[] ){
int length;
Scanner sc = new Scanner(System.in);
Scanner an = new Scanner(System.in);
System.out.print("How many words are you going to enter? ");
length = sc.nextInt();
String[] sEnterWord = new String[length];
for(int nCtr = 0; nCtr < length; nCtr++){
System.out.print("Enter word " + (nCtr+1) + ":");
sEnterWord[nCtr] = sc.next();
}
System.out.println("Your words are: ");
Arrays.sort(sEnterWord);
for(int nCtr = 0; nCtr < length; nCtr++){
System.out.println(sEnterWord[nCtr]);
}
System.out.println("Which word would you like to change?");
int sWordToChange = sc.nextInt();
System.out.println("You have chosen to change the word : " + sWordToChange);
System.out.println("Enter the new word: ");
String sNewWord = an.nextLine();
sEnterWord[sWordToChange-1] = sNewWord;
System.out.println("Your words are: ");
for(int nCtr = 0; nCtr < length; nCtr++){
System.out.println(sEnterWord[nCtr]);
}
}
}
Break your code up into smaller methods. See the (working) example below. All you need to do to change the word (string, not numeric index) with another is loop through and check for equality with the equals method. The break statement after that will stop iteration (after you've found the correct index, no point looking further).
import java.util.Scanner;
import java.util.Arrays;
public class Test {
public static void main ( String args[] ){
String[] sEnterWord = getSortedWordArr();
showWordlist(sEnterWord);
String sWordToChange = getInputFromKeyboard("Which word would you like to change? ");
System.out.println("You have chosen to change the word : " + sWordToChange);
changeWordInArray(sWordToChange, sEnterWord);
Arrays.sort(sEnterWord);
showWordlist(sEnterWord);
}
private static String[] getSortedWordArr(){
String line = getInputFromKeyboard("How many words are you going to enter? ");
int length = Integer.valueOf(line);
String[] sEnterWord = new String[length];
for(int nCtr = 0; nCtr < length; nCtr++){
sEnterWord[nCtr] = getInputFromKeyboard("Enter word " + (nCtr+1) + ":");
}
Arrays.sort(sEnterWord);
return sEnterWord;
}
private static String getInputFromKeyboard(String prompt){
System.out.print(prompt);
Scanner s = new Scanner(System.in);
String input = s.nextLine();
return input;
}
private static void showWordlist(String[] words){
System.out.println("Your words are: ");
for (String w : words){
System.out.println(w);
}
}
private static void changeWordInArray(String word, String[] array){
String newWord = getInputFromKeyboard("Enter the new word: ");
for (int i = 0; i < array.length; i++){
if (array[i].equals(word)){
array[i] = newWord;
break;
}
}
Arrays.sort(array);
}
}
Sample output:
How many words are you going to enter? 5
Enter word 1:apple
Enter word 2:banana
Enter word 3:orange
Enter word 4:pear
Enter word 5:lemon
Your words are:
apple
banana
lemon
orange
pear
Which word would you like to change? banana
You have chosen to change the word : banana
Enter the new word: strawberry
Your words are:
apple
lemon
orange
pear
strawberry
Replace the code between
System.out.println("Which word would you like to change?");
and
System.out.println("You have chosen to change the word : " +
sWordToChange);
with this:
sc.nextLine();
String sWordToChange = sc.nextLine();
int index=-1;
for (int i = 0; i < sEnterWord.length; i++) {
if(sEnterWord[i].equals(sWordToChange))
index=i;
}
Explanation:
The first line is just to avoid the scanner skipping the assignation to sWordToChange. The for loop iterates over the array and looks for a match, if it finds one it saves the index of the word on the previously declared variable index. It is initalized as -1 in case the word is not found. Maybe you want to add an if block right after the substitution to make sure you modify the array only when there is a match
Changed the Scanner class to BufferedReader Class.
public class ArrayTest {
public static void main(String args[]) throws IOException {
int length;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("How many words are you going to enter? ");
length=Integer.parseInt(br.readLine());
String[] sEnterWord = new String[length];
for (int nCtr = 0; nCtr < length; nCtr++) {
System.out.println("Enter word " + (nCtr + 1) + ":");
sEnterWord[nCtr]=br.readLine();
}
System.out.println("Your words are: ");
Arrays.sort(sEnterWord);
for (int nCtr = 0; nCtr < length; nCtr++) {
System.out.println(sEnterWord[nCtr]);
}
System.out.println("Which word would you like to change?");
String sWordToChange = br.readLine();
System.out.print("Enter the new word: ");
String sNewWord = br.readLine();
for (int i = 0; i < sEnterWord.length; i++) {
if (sEnterWord[i].equals(sWordToChange)) {
sEnterWord[i] = sNewWord;
}
}
System.out.println("Your words are: ");
for (int nCtr = 0; nCtr < length; nCtr++) {
System.out.println(sEnterWord[nCtr]);
}
}}
you can also make some changes in the code like:
System.out.println("Which word would you like to change?");
String sWordToChange = br.readLine();
int position = Arrays.binarySearch(sEnterWord, sWordToChange);
if (position < 0) {
System.out.println("Word not found ");
} else {
System.out.print("Enter the new word: ");
String sNewWord = br.readLine();
sEnterWord[position] = sNewWord;
}
In this program you need add sc.nextLine() before taking new word to update in String array.nextLine() method of Scanner class takes empty string from buffer.
The whole program with change of code.
package expertwebindia;
import java.util.Arrays;
import java.util.Scanner;
public class Test {
public static void main(String args[]){
int length;
Scanner sc = new Scanner(System.in);
//Scanner an = new Scanner(System.in);
System.out.print("How many words are you going to enter? ");
length = sc.nextInt();
String[] sEnterWord = new String[length];
for(int nCtr = 0; nCtr < length; nCtr++){
System.out.print("Enter word " + (nCtr+1) + ":");
sEnterWord[nCtr] = sc.next();
}
System.out.println("Your words are: ");
Arrays.sort(sEnterWord);
for(int nCtr = 0; nCtr < length; nCtr++){
System.out.println(sEnterWord[nCtr]);
}
System.out.println("Which word would you like to change?");
int sWordToChange = sc.nextInt();
sc.nextLine();
System.out.println("You have chosen to change the word : " + sWordToChange);
System.out.println("Enter the new word: ");
String sNewWord = sc.nextLine();
sEnterWord[sWordToChange-1] = sNewWord;
System.out.println("Your words are: ");
for(int nCtr = 0; nCtr < length; nCtr++){
System.out.println(sEnterWord[nCtr]);
}
}
}

String Formatting & NullPointerException's

Whenever I don't give a value to one of my phone numbers (null) and print it to the screen with this current code block, it gives me a NullPointerException. I don't want to have to fill every spot in my 'phone book' with contacts before reading them because it would just be way too much to type.
This is the code where the exception is being thrown:
for (int i = 0; i< array1.length; i++) {
num++;
System.err.println("Contact: " + num);
System.out.print(array1[counterB2][counterB]);
counterB++;
System.out.print(" " + array1[counterB2][counterB]);
counterB++;
String[] phoneNumArr= {
array1[counterB2][2].substring(0, 3),
array1[counterB2][2].substring(3,6),
array1[counterB2][2].substring(6)};
System.out.println(" ");
if (!array1[counterB2][2].equals(null)) {
System.out.println(phoneMsgFmt.format(phoneNumArr));
counterB = 0;
counterB2++;
}
}
Any help improving this so that it would work properly would be appreciated.
Here's the rest of the code:
import java.util.Scanner;
import java.awt.*;
import java.math.*;
import java.text.DecimalFormat;
public class testMattWalker {
//
public static void main (String[] args){
Scanner input = new Scanner(System.in);
Scanner input2 = new Scanner(System.in);
Scanner input3 = new Scanner(System.in);
Scanner input4 = new Scanner(System.in);
Scanner input5 = new Scanner(System.in);
Scanner input6 = new Scanner(System.in);
Scanner input7 = new Scanner(System.in);
Scanner input8 = new Scanner(System.in);
int counter = 0;
int counter2 = 0;
int counterB = 0;
int counterB2 = 0;
int counterC = 0;
int counterD = 0;
int counterE = 0;
String yn = "";
String searchLast = "";
String searchFirst = "";
String searchNumber = "";
int maxNumberOfPeople = 5;
boolean go = true;
DecimalFormat phoneDecimalFmt = new DecimalFormat("0000000000");
java.text.MessageFormat phoneMsgFmt=new java.text.MessageFormat("({0})-{1}-{2}");
//Temp VAriables for entry
String firstNameOfEntry = "";
String lastNameOfEntry = "";
String personPhoneNumber = "";
//
//create array
String [][] array1 = new String[5][3];
while (go = true) {
String choice = "";
System.err.println("\n\n\n\n\n\n\n\n\nDIDGITAL PHONE BOOK 2013");
System.out.println("1- Create phone book\n2- Display phone book\n3- Find person(s) by last name\n4- Find person(s) by first name\n5- Find person(s) by phone number\n6- Exit application");
choice = input.nextLine();
if (choice.equals("1") && counter2 != maxNumberOfPeople) {
System.err.println("\n\n\n\n\nPHONE BOOK ENTRY CREATOR:");
System.out.println("Please enter the first name of the person you wish to enter: ");
array1[counter2][counter] = input2.nextLine();
counter++;
System.out.println("Please enter the last name of the person you wish to enter: ");
array1[counter2][counter] = input3.nextLine();
counter++;
System.out.println("Please enter the phone number of this person: example:9057773344");
array1[counter2][counter] = input4.nextLine();
counter = 0;
counter2++;
}else if (choice.equals("2")) {
int num = 0;
System.out.println("SEE I CAN FORMAT NUMBERS... I just didn't have time to put it on every one.");
for (int i = 0; i< array1.length; i++) {
num++;
System.err.println("Contact: " + num);
System.out.print(array1[counterB2][counterB]);
counterB++;
System.out.print(" " + array1[counterB2][counterB]);
counterB++;
String[] phoneNumArr= {
array1[counterB2][2].substring(0, 3),
array1[counterB2][2].substring(3,6),
array1[counterB2][2].substring(6)};
System.out.println(" ");
if (!array1[counterB2][2].equals(null)) {
System.out.println(phoneMsgFmt.format(phoneNumArr));
counterB = 0;
counterB2++;
}
}
}else if (choice.equals("3")) {
System.out.println("\n\n\n\n\n\nPlease enter the last name of the person you are searching for: ");
searchLast = input6.nextLine();
counterC = 0;
for (int i = 0; i < array1.length; i++) {
if (searchLast.equals(array1[counterC][1])) {
System.out.println(array1[counterC][0] + " " + array1[counterC][1] + " " + array1[counterC][2]);
}
counterC++;
}
}else if (choice.equals("4")) {
System.out.println("\n\n\n\n\n\nPlease enter the first name of the person you are searching for: ");
searchFirst = input7.nextLine();
counterD = 0;
for (int i = 0; i < array1.length; i++) {
if (searchFirst.equals(array1[counterD][0])) {
System.out.println(array1[counterC][0] + " " + array1[counterC][1] + " " + array1[counterC][2]);
}
counterD++;
}
}else if (choice.equals("5")) {
System.out.println("\n\n\n\n\n\nPlease enter the phone number of the person you are searching for: ");
searchNumber = input8.nextLine();
counterE = 0;
for (int i = 0; i < array1.length; i++) {
if (searchNumber.equals(array1[counterE][2])) {
System.out.println(array1[counterC][0] + " " + array1[counterC][1] + " " + array1[counterC][2]);
}
counterE++;
}
}else if (choice.equals("6")) {
System.err.println("Are you sure? [y/n]");
yn = input5.nextLine();
if (yn.equals("y")) {
System.err.println("CLOSING...");
System.exit(0);
}else if (yn.equals("n")){
System.out.println("Resuming...");
}else {System.err.println("ERROR"); System.exit(0);}
}
}
}// end of main
}// end of class
EDIT: What I've been trying to do is create a way to only display the phone number if the element in the array is not empty but It just doesn't seem to want to work for me ;--;
You're getting a NullPointerException probably because you're referencing a method of (String) array1[counterB2][2] before checking that value for null here: if (!array1[counterB2][2].equals(null)).
This happens when you initialize phoneNumArr, which contains calls to substring on array1[counterB2][2].
If array1[counterB2][2] is null, calling substring on it will throw the NullPointerException.
Just enclose your substring statements within the check for null and you should be all right.
Finally, dont't use if (!array1[counterB2][2].equals(null)), use if (array1[counterB2][2] != null).
Otherwise, you might end up calling Object.equals on a null Object, which again, will throw NullPointerException.
Just check whenever you do nextLine() if the User really entered something via
if(string != null)...
check
Comparing the strings using '.equals(null)' will throw a NullPointerException if the first object is null. Instead, compare using:
string == null
or obviously
string != null
for what you want to do.
You are right to prefer the .equals() method for String comparison but not when you're checking if something is null.
I also noticed that the condition for your while loop won't work as expected, you are assigning 'true' to the 'go' boolean every time when you use '(go = true)'. Instead, either use:
while (go == true)
or simply
while (go)
you shoudl employ null check before working with Strings here. Thats the standard way to do these.

Categories