I'm very new to Java and currently doing an introduction course. I'm working on a program which creates two basketball teams and asks the user to input scores for the two teams.
To add a score to the first team the user enters 'a' followed by a space and the amount of points to be added. To add to the second team 'b' followed by space and points is used.
Now everything works great but I want the game to finish when the user enters 'exit' instead of 'a 2' or 'b 1' etc.
I've set up my class and methods accordingly but my problem is that it either works great adding scores or reading exit and bringing up the final score..not both.
In other words, I manage to store the input 'exit' correctly or 'a 2' etc. but whenever the one works the other one doesn't.
I've played around with various code combinations but none work, this is what I've got currently:
if (keyboard.nextLine().equals("exit")) {
System.out.println("exit");
}
else {
team = keyboard.next();
points = keyboard.next();
System.out.println("not exit");
}
This prints out exit when I type exit when asked for a score...but when I enter for arguments sake 'a 2' it just hangs.
I'm not allowed to use array's unfortunately. Please help.
You need to do
final String input = keyboard.nextLine();
if(input.equals("exit")) {
//do whatever on exit
}
else {
//work with input string, probably using StringTokenizer or something
}
and then check what that line is instead of doing it in the if statment like you are doing now.
Currently your problem is that you are reading the entire line and if it is not exit
, you are expecting 2 more string inputs instead of using the last one. That is why it freezes.
You could solve it like this:
String firstToken = keyboard.next();
if (firstToken.equalsIgnoreCase("exit")) {
System.out.println("exit");
}
else {
team = firstToken;
points = keyboard.next();
}
What this does is:
team
and the next one should be the points. When you call
keyboard.nextLine()
in the if
condition you tell the scanner to deliver the next line but you don't store the result. If it doesn't match exit
you should check what the line was. Instead you ask the scanner again for the next values.
Just ask for the line once
String line = keyboard.nextLine();
and then work use it in your code.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.