Skip to main content

get stuck in do while loop

Please note these java.net forums are being decommissioned and use the new and improved forums at https://community.oracle.com/community/java.
1 reply [Last post]
canadaedmonton
Offline
Joined: 2011-06-04

import java.util.Scanner;
import static java.lang.System.out;
class guestroom {

public static void main(String[] args) {
Scanner myScanner=new Scanner(System.in);
int whichRoom, numGuests;
int guestsIn[]=new int[10];

for (int roomNum=0;roomNum<10;roomNum++){
guestsIn[roomNum]=0;
}
do {
out.print("Room number: ");
whichRoom=myScanner.nextInt();
out.print("How many guests? ");
numGuests=myScanner.nextInt();
guestsIn[whichRoom]=numGuests;
out.println();
out.print("Do another? ");
}while (myScanner.findInLine(".").charAt(0)=='Y');

out.println();
out.println("Room\tGuests");

for (int roomNum=0; roomNum<10; roomNum++){
out.print(roomNum);
out.print("\t");
out.println(guestsIn[roomNum]);
}

}
}

i got an error message that

--------------------Configuration: guestroom - Java home directory <Default> - <Default>--------------------
Room number: 3
How many guests? 2

Do another? Exception in thread "main" java.lang.NullPointerException
at guestroom.main(guestroom.java:21)

Process completed.

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
OneJumpedUp
Offline
Joined: 2012-04-05

Hey you're almost there, just a couple of hiccups; see below and compare:

        Scanner myScanner = new Scanner(System.in);
        int whichRoom, numGuests;
        int guestsIn[] = new int[10];
        String ans = null;  // looking for a string !!!

        for (int roomNum = 0; roomNum < 10; roomNum++)
        {
            guestsIn[roomNum] = 0;
        }
       
        do
        {
            System.out.print("Room number: ");
            whichRoom = myScanner.nextInt();
            System.out.print("How many guests? ");
            numGuests = myScanner.nextInt();
            guestsIn[whichRoom] = numGuests;
            System.out.println();
            System.out.print("Do another? ");
            ans = myScanner.next();  // looking for a string !!!
        }
        while( ans.equals( "y" )); // looking for a string !!!

        System.out.println();
        System.out.println("Room\tGuests");

        for (int roomNum = 0; roomNum < 10; roomNum++)
        {
            System.out.print(roomNum);
            System.out.print("\t");
            System.out.println(guestsIn[roomNum]);
        }