String Formatting & NullPointerException's - java

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.

Related

Want to print my stored names in array by JoptionPane, JAVA

public static void main(String[] args) {
i got to enter the amount of names i want, then input them by scanner in console, and after print the longest one, it's mostly done, but i want to print it by JoptionPane aswell
Scanner wczytanie = new Scanner(System.in);
System.out.println("ENTER THE AMOUNT OF NAMES");
int size = wczytanie.nextInt();
String[] array = new String[size];
System.out.println("ENTER THE NAMES");
String name = wczytanie.nextLine();
for (int i = 0; i < array.length; i++) {
array[i] = wczytanie.nextLine();
if (name.length() < array[i].length()) {
name = array[i];
}
}
// System.out.println("LONGEST NAME: " + name);
String name1 = new String();
if(name == name1) {
JOptionPane.showMessageDialog(null, " THE LONGEST NAME IS " + name1);
}
}
You have a lot of problems here: you're reading from the scanner before the loop when reading names and you're doing a raw object equality on a new string for some reason that will never work. You want something more like this:
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
System.out.println("How many names? ");
int num = scanner.nextInt();
List<String> names = new ArrayList<>(num);
System.out.println("Enter names: ");
for (int i = 0; i < num; i++) {
names.add(scanner.next());
}
String longest = names.stream().reduce((a, b) -> a.length() > b.length() ? a : b).get();
System.out.println("The longest name is: " + longest);
JOptionPane.showMessageDialog(null, "The longest name is: " + longest);
}
}

while loop with store value for next while loop in java

I'm a beginner in Java. I have an assignment that require me to take 3 input from user, then output the 3 at the same time.
here is my code. i have only get 1 output.
suppose look like this:
anyone could help, thx!
here is my code
Scanner sc = new Scanner(System.in);
int i = 0;
String classname = " ";
String rating = " ";
int plus = 0;
while(i < 3){
System.out.print("What class are you rating? ");
classname = sc.nextLine();
System.out.print("How many plus signs does " + classname +" get? ");
rating = sc.nextLine();
plus = Integer.parseInt(rating);
i++;
}
System.out.print(classname + ": ");
while (plus > 0){
System.out.print("+");
plus --;
}
System.out.println();
The very first thing I would do is create a Course POJO (Plain Old Java Object). It should have two fields, name and rating. And I would implement the display logic with a toString in that Course POJO. Like,
public class Course {
private String name;
private int rating;
public Course(String name, int rating) {
this.name = name;
this.rating = rating;
}
public String toString() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < rating; i++) {
sb.append("+");
}
return String.format("%s: %s", name, sb);
}
}
Then your main method simply involves filling a single array of three Course instances in one loop, and displaying them in a second loop. Like,
Scanner sc = new Scanner(System.in);
Course[] courses = new Course[3];
int i = 0;
while (i < courses.length) {
System.out.print("What class are you rating? ");
String className = sc.nextLine();
System.out.printf("How many plus signs does %s get? ", className);
int classRating = Integer.parseInt(sc.nextLine());
courses[i] = new Course(className, classRating);
i++;
}
i = 0;
while (i < courses.length) {
System.out.println(courses[i]);
i++;
}
You overwrite your variables classname and rating in each loop. You need to store each iteration in a field of an array.
Scanner sc = new Scanner(System.in);
int i = 0;
String[] classname = new String[3]; //create array
String rating = " "; //rating can be overwritten, it is not needed after the loop
int[] plus = new int[3];
while(i < 3){
System.out.print("What class are you rating? ");
classname[i] = sc.nextLine(); //name[index] to read/write fields of an array
//index starts at 0
System.out.print("How many plus signs does " + classname +" get? ");
rating = sc.nextLine();
plus[i] = Integer.parseInt(rating);
i++;
}
for(i = 0;i<3;i++){ //iterate over all elements in the array
System.out.print(classname[i] + ": ");
while (plus[i] > 0){
System.out.print("+");
plus[i] --;
}
System.out.println();
}

Check if user entered both a first and last name

I'm making a program that gives random lottery numbers to inputted names. The problem though is that I have to make sure the user entered both a first and last name. I'm using a method of finding the space in the users input, then creating substrings from that data, but I keep on getting the error "incompatible type" right under my for loop. Any help would be greatly appreciated!
enter code here
import java.util.Scanner; //Import scanner class
import java.util.Random; //Import random number generator
import java.io.*; //Import PrintWriter
public class Lab4ZinkovskyFl //Program that lets user enter a name and generates random lottery numbers for that name
{
public static void main (String[] args) throws IOException
{
Scanner keyboard = new Scanner (System.in);
Random randomNumbers = new Random();
String again = "y"; //Control the loop
int r1 = randomNumbers.nextInt(100)+ 1; //*******************
int r2 = randomNumbers.nextInt(100)+ 1; //* Random lottery
int r3 = randomNumbers.nextInt(100)+ 1; //* numbers for
int r4 = randomNumbers.nextInt(100)+ 1; //* program
int r5 = randomNumbers.nextInt(100)+ 1; //*******************
while (again.equalsIgnoreCase ("y")) // Allows the user to continue the loop
{
System.out.println ("Please enter first and last name to enter the lottery.");
String fullName = keyboard.nextLine();
boolean space = false; // Checks for first and last name
for (int i = 0; i < fullName.length(); i++)
{
if (fullName.indexOf(i) == " ")
{
space = true;
spaceIndex = i;
}
else
{
System.out.println ("Error, please enter both first and last name to continue.");
}
}
String firstName = fullName.substring (0, spaceIndex);
String lastName = fullName.substring (spaceIndex, fullName.length());
System.out.println (lastName + ", " + firstName + ": " + r1 + ", " + r2 + ", " + r3 + ", " + r4 + ", " + r5);
System.out.println ("Run the lottery again? (y=yes)");
again = keyboard.nextLine();
}
}
}
You can split the user input by " ", like this:
String[] names = fullName.split(" ");
And then you create a method to return true if the user do enters the full name.
for (int i = 0 ; i < names.length ; i++) {
if (names[i].trim().equals("")) {
names[i] = null;
}
}
int elementsWithText = 0;
for (int i = 0 ; i < names.length ; i++) {
if (names[i] != null) {
elementsWithText++;
}
}
return elementsWithText == 2;
Something like that. Hopefully you figure what I am doing. If you don't know what the methods calls are doing, they are all from String. Here is the docs:
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html
indexOf() takes in a char as input (in your case). Change i to " "(space)
You need to write like this
if (fullName.indexOf(" ") == -1)
{
System.out.println ("Error, please enter both first and last name to continue.");
}
else
{
space = true;
spaceIndex = i;
}
But why you choose for loop?
#sweeper has given the best solution.

i don't get the right answer, why?

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

Process of how do I spot the errors in this buggy code?

I have this code:
When I launch it, I am able to get numbers i = 0 to i = 10. However I know this is not the objective of the code as the objective is to reach into the Scanner. But the scanner does not seem to work? Am I making an error importing a file or is this to do with the code? I'm noob.
package buggyProgram;
import java.util.Scanner;
public class BuggyProgram {
/**
* The main method of the program. This is where it all starts.
*/
public static void main(String[] args) {
String[] saNames = new String[5];
String[] saNumbers = new String[5];
Scanner scIn = new Scanner(System.in);
for (int i = 0; i <= 4; i++) {
System.out.print("Enter name: ");
saNames[i] = scIn.nextLine();
System.out.print("Enter number: ");
saNumbers[i] = scIn.nextLine();
}
System.out.println();
for (int i = 1; i < 4; i++) {
System.out.println("The number of " + saNames[i] + " is "
+ saNames[i] + ".");
}
}
}
Java arrays start at 0 (not 1), and you're printing the same array element twice (in your second for-loop). Finally, you could always use a debugger to help you determine where things are no longer working as you expect.
// for (int i = 1; i < 4; i++) {
for (int i = 0; i <= 4; i++) { // <-- to match your first loop.
System.out.println("The number of " + saNames[i] + " is "
+ saNumbers[i] + ".");
}
You might also use formatted output (the formatter syntax) like
for (int i = 0; i <= 4; i++) {
System.out.printf("The number of %s is %s.%n", saNames[i], saNumbers[i]);
}
One of the first things you can do to make it easier to debug is to make the input fixed between runs. If you change Scanner scIn = new Scanner(System.in); to this:
Scanner scIn = new Scanner(new BufferedReader(new FileReader("some-file.txt")));
Assuming that some-file.txt is populated with the appropriate input, then you can run the program multiple times without having to manually re-enter the input. In addition, the input is fixed, so comparing the output of different runs becomes more useful.
I can confirm, that your code works, as long as you change your final output:
String[] saNames = new String[5];
String[] saNumbers = new String[5];
Scanner scIn = new Scanner(System.in);
for (int i = 0; i <= 4; i++) {
System.out.print("Enter name: ");
saNames[i] = scIn.nextLine();
System.out.print("Enter number: ");
saNumbers[i] = scIn.nextLine();
}
System.out.println();
for (int i = 1; i < 4; i++) {
System.out.println("The number of " + saNames[i] + " is "
+ saNumbers[i] + ".");
}

Categories