Results 1 to 4 of 4
Thread: NullPointerException
- 10-09-2010, 07:52 PM #1
Member
- Join Date
- Sep 2010
- Posts
- 42
- Rep Power
- 0
NullPointerException
I'm trying to make a program. I'm using a while loop to keep asking for a name and when "done" is entered it exits the loop. It stores the names in an array and prints it out as you enter it. I cant get it to exit the loop.
This is the Source Code:
Java Code:import java.util.*; public class TimeCard { public static void main(String sArgs[]){ Scanner oScan = new Scanner(System.in); String[] aStudentNames = new String[150]; final String[] sDone = {"done"}; int iA = 0; while(aStudentNames[iA].compareToIgnoreCase(sDone[0]) > 0 || aStudentNames[iA].compareToIgnoreCase(sDone[0]) < 0){ System.out.println("What is your name?"); aStudentNames[iA] = oScan.nextLine(); System.out.println(aStudentNames[iA]); ++iA; } } }
- 10-09-2010, 08:02 PM #2
Senior Member
- Join Date
- Oct 2010
- Location
- Germany
- Posts
- 780
- Rep Power
- 4
its shorter to writeJava Code:while(aStudentNames[iA].compareToIgnoreCase(sDone[0]) > 0 || aStudentNames[iA].compareToIgnoreCase(sDone[0]) < 0)
(an array with only one string makes no sense in my opinion)Java Code:while(!aStudentNames[iA].equalsIgnoreCase("done"))
So your problem is, that you access aStudentNames[iA] before you store the name on that array position. use maybe a do-while-loop instead of a normal while-loop.
Maybe:
but you store "done" in your array too, dont know if you really want this :)Java Code:Scanner oScan = new Scanner(System.in); String[] aStudentNames = new String[150]; int iA = 0; do { System.out.println("What is your name?"); aStudentNames[iA] = oScan.nextLine(); System.out.println(aStudentNames[iA]); } while (!aStudentNames[iA++].equalsIgnoreCase("done"));
Java Code:Scanner oScan = new Scanner(System.in); String[] aStudentNames = new String[150]; int iA = 0; while(iA<149){ System.out.println("What is your name?"); String s = oScan.nextLine(); if("done".equalsIgnoreCase(s)){ break; } aStudentNames[iA] =s; System.out.println(aStudentNames[iA++]); }Last edited by eRaaaa; 10-09-2010 at 08:06 PM.
- 10-09-2010, 08:10 PM #3
Member
- Join Date
- Sep 2010
- Posts
- 42
- Rep Power
- 0
Thanks I'll try that!
- 10-09-2010, 08:12 PM #4
Member
- Join Date
- Sep 2010
- Posts
- 42
- Rep Power
- 0
Similar Threads
-
NullPointerException
By sanu in forum Java AppletsReplies: 3Last Post: 08-21-2010, 08:37 PM -
NullPointerException: I can't get rid of it.
By mcashe in forum AWT / SwingReplies: 2Last Post: 08-17-2009, 09:16 PM -
I get a NullPointerException and don't know why
By hendrix79 in forum New To JavaReplies: 9Last Post: 12-14-2008, 06:18 AM -
NullPointerException
By adeeb in forum AWT / SwingReplies: 3Last Post: 06-11-2008, 08:42 AM -
NullPointerException
By mensa in forum Java 2DReplies: 5Last Post: 05-03-2008, 11:19 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks