My full code is pasted here. Below are the 2 methods that are related to my question.
private static boolean playGameAgain()
{
char playAgain = 'y';
Scanner input = new Scanner(System.in);
while(playAgain != 'n')
{
System.out.println("Go again?(y/n)");
/// PROBLEM HERE.... Somehow, it will NOT wait for INPUT. It just throws an error
playAgain = input.next().charAt(0);
}
input.close();
return (playAgain != 'y')?false:true;
}
// [Trimmed]
public static void initialize(ArrayList<String> names, ArrayList<Integer> scores)
{
Scanner input = new Scanner(System.in);
for (int i = 1; i <= 5; i++)
{
System.out.println("Enter the name for score #" + i + ":");
names.add(input.nextLine());
System.out.println();
System.out.println("Enter the score for score #" + i + ":");
while(!input.hasNextInt())
{
//input.nextLine();
System.out.println("Please input a valid integer value for the score for #" + i + ":");
if(!input.hasNextInt())
input.nextLine();
}
scores.add(input.nextInt());
input.nextLine();
}
input.close();
}
I have tried many combinations of how to read in one character. This used to work, that I could read in one character by using:
Scanner input = new Scanner(System.in);
char temp = input.next().charAt(0);
But, somehow, in this program I wrote, it won't work.
It's a program that will read in 5 user names (strings) & 5 scores (integers) and put them in 2 arrays. It will sort the arrays in descending order and then it will print them out. So, the only problem I have is asking if they want to play again and taking some char input to see if they want to play again (y/n)?
Please help if you can. I've tried many combinations of: if (input.hasNext()), to no avail.
You are not setting playAgain to something other than 'y' in playGameAgain(). You have a bug here.
Related
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.println("\nThe sum of the numbers is: " + getSumOfInput());
}
public static int getSumOfInput () {
int counter = 0;
int sumOfNums = 0;
Scanner userInput = new Scanner(System.in);
while(counter <= 10) {
System.out.print("Enter the number " + counter + ": ");
boolean checkValidity = userInput.hasNextInt();
if(checkValidity) {
int userNum = userInput.nextInt();
userInput.nextLine();
System.out.println("Number " + userNum + " added to the total sum.");
sumOfNums += userNum;
counter++;
} else {
System.out.println("Invalid input. Please, enter a number.");
}
}
userInput.close();
return sumOfNums;
}
}
Hello everybody!
I just started java and I learned about control flow and now I moved on to user input, so I don't know much. The problem is this code. Works just fine if you enter valid input as I tested, nothing to get worried about. The problem is that I want to check for wrong input from user, for example when they enter a string like "asdew". I want to display the error from else statement and to move on back to asking the user for another input, but after such an input the program will enter in an infinite loop displaying "Enter the number X: Invalid input. Please, enter a number.".
Can you tell me what's wrong? Please, mind the fact that I have few notions when it comes to what java can offer, so your range of solutions it's a little bit limited.
Call userInput.nextLine(); just after while:
...
while(counter <= 10) {
System.out.print("Enter the number " + counter + ": ");
userInput.nextLine();
...
The issue is, that once you enter intput, which can not be interpreted as an int, userInput.hasNextInt() will return false (as expected). But this call will not clear the input, so for every loop iteration the condition doesn't change. So you get an infinite loop.
From Scanner#hasNextInt():
Returns true if the next token in this scanner's input can be interpreted as an int value in the default radix using the nextInt() method. The scanner does not advance past any input.
The fix is to clear the input if you came across invalid input. For example:
} else {
System.out.println("Invalid input. Please, enter a number.");
userInput.nextLine();
}
Another approach you could take, which requires less input reads from the scanner, is to always take the next line regardless and then handle the incorrect input while parsing.
public static int getSumOfInput() {
int counter = 0;
int sumOfNums = 0;
Scanner userInput = new Scanner(System.in);
while (counter <= 10) {
System.out.print("Enter the number " + counter + ": ");
String input = userInput.nextLine();
try {
int convertedInput = Integer.parseInt(input);
System.out.println("Number " + convertedInput + " added to the total sum.");
sumOfNums += convertedInput;
counter++;
} catch (NumberFormatException e) {
System.out.println("Invalid input. Please, enter a number.");
}
}
return sumOfNums;
}
I am making a program that will take a user's input on how many numbers he wants and determine the highest number between the given. After that the user will be prompt with a Yes or no question. If the user decides to say yes, the program will loop again and if not, the program will end. Now my question is why does it take the highest number from the previous run?
import java.util.Scanner;
public class IT_VILLAFLOR_Lab1_Prog2
{
public static void main(String[] Args){
int num=1,num2,Largest=0,max;
char YN;
Scanner sc = new Scanner(System.in);
System.out.print("Enter the Max Number = ");
max = sc.nextInt();
for(num=1; num<=max; num++)
{
System.out.print("Enter Number " + num + ": ");
num2 = sc.nextInt();
if(Largest<num2)
{
Largest=num2;
}
else if(num==max)
{
System.out.println("The Biggest number is " + Largest );
System.out.print( "Do you want to try again? Y/N ");
YN = sc.next().charAt(0);
if(YN =='Y'|| YN =='y')
{
num=0;
System.out.print('\f');
System.out.print("Enter the Max Number " );
max = sc.nextInt();
}
else
{
System.exit(0);
}
}
}
}
}
If the user wants to continue, you are resetting num to 0. Along with this, Largest also needs to be reset to 0.
num=0;
Largest=0; //new code
By the way, you need to change the line else if(num==max) to if(num==max) . Try the test case with max of 2 and values as 12 ,23.
This question already has an answer here:
java.lang.IllegalStateException: Scanner closed
(1 answer)
Closed 4 years ago.
I'm trying to write a program where it will tell you:
The number of integers in a list entered by the user at the command prompt
The sum of those integers.
But I'm having some trouble figuring out how to access those individual numbers. I've tried writing the while loop already, as well as the "if" statements.
Another issue I'm having is that when I try to run my program, I get this error message: Exception in thread "main" java.lang.IllegalStateException: Scanner closed.
NOTE: I'm very new to Java so a simpler solution that mainly uses scanners, next methods, and hasNext methods would be better!
import java.util.Scanner;
public class InputParser
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.print("How many values do you want to parse?: ");
int numValues = scanner.nextInt();
System.out.println("Please enter " + numValues + " values: ");
while(scanner.hasNextLine())
{
if(scanner.hasNext())
{
if(scanner.hasNextInt())
{
int sum;
System.out.println("The sum of your values is: " + sum + ".");
}
}
scanner.close();
}
}
}
Your code should be like:
Scanner scanner = new Scanner(System.in);
System.out.print("How many values do you want to parse?: ");
int numValues = scanner.nextInt();
int[] values = new int(numValues);
int sum = 0,i=0;
while(i<numValues)
{ i++;
System.out.print("Enter "+ i+" number : ");
values[i-1] = scanner.nextInt();
sum+= values[i-1];
}
System.out.println("Sum is : "+sum);
scanner.close();
Haven't really consider error handling.
I don't understand why you would ask the user how many numbers they want to sum ahead of time. Basically, your code can be simplified and handle an arbitrary number of numbers. It's also a really bad idea to call close() on a Scanner wrapping System.in (Because you can't re-open it, and if you extract it into a method you will create a hard to debug and find issue). Anyway, you could do something like,
Scanner scanner = new Scanner(System.in);
// System.out.print("How many values do you want to parse?: ");
// int numValues = scanner.nextInt();
System.out.println("Please enter values to sum (type quit to stop)");
int sum = 0; // <-- start at 0.
int count = 0;
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
count++;
sum += scanner.nextInt();
} else {
String str = scanner.next();
if (str.equalsIgnoreCase("quit")) {
break; // <-- end the loop.
}
System.out.printf("The value '%s' is not an int (quit to stop).%n", str);
}
}
System.out.printf("The sum of your %d values is %d.%n", count, sum);
// scanner.close(); // <-- Really Bad Idea
Edit Based on your comment,
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter values to sum (type quit to stop)");
while (scanner.hasNextLine()) {
String str = scanner.nextLine();
str = (str != null) ? str.trim() : "";
if (str.equalsIgnoreCase("quit")) {
break; // <-- end the loop.
} else if (str.length() == 0) {
continue;
}
int sum = 0; // <-- start at 0.
int count = 0;
Scanner scan2 = new Scanner(str);
while (scan2.hasNextInt()) {
count++;
sum += scan2.nextInt();
}
System.out.printf("The sum of your %d values is %d.%n", count, sum);
}
import java.util.Scanner;
public class Cardhelp2{
private static String[] pairArray={"A,A","K,K","Q,Q","J,J","10,10","9,9","8,8","7,7","6,6","5,5","4,4","3,3","2,2"};
public static void generateRandom(int k){
int minimum = 0;
int maximum = 13;
for(int i = 1; i <= k; i++)
{
int randomNum = minimum + (int)(Math.random()* maximum);
System.out.print("Player " + i +" , You have been dealt a pair of: ");
System.out.println(pairArray[randomNum]);
}
} //reads array and randomizes cards
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("How many players would you like to play with? ");
int m = scan.nextInt();
generateRandom(m);
//displays the cards
___________________________________________________
System.out.println("Would you like to play?");
Scanner scanner = new Scanner(System.in);
if(scanner.next().equalsIgnoreCase("y")||scanner.next().equalsIgnoreCase("yes")) {
System.out.println("This will be fun");
} else if(scanner.next().equalsIgnoreCase("n")||scanner.next().equalsIgnoreCase("no")) {
System.out.println("Maybe next time");
} else {
System.out.println("Invalid character");
}
}
}
Im having trouble understanding why the end part is not working, I've been told i need to change scanner.next(); to a variable but im not sure how to do it and get the code working. Is there a simple way of reading in the users answer then displaying a response to the user?
Thanks
Your conditional expression
if(scanner.next().equalsIgnoreCase("y")||scanner.next().equalsIgnoreCase("yes"))
calls scanner.next() twice, which means the second call will read/wait for more input. Instead you need to call it only once, store the result and use that in the comparison:
String tmp = scanner.next();
if(tmp.equalsIgnoreCase("y")||tmp.equalsIgnoreCase("yes"))
Let's assume the user inputs "yes".
At
if(scanner.next().equalsIgnoreCase("y")||scanner.next().equalsIgnoreCase("yes")) {
Scanner.next() produces "yes" in the first test. So the code is effectively
"yes".equalsIgnoreCase("y")
Which is false, so it moves to the next test:
scanner.next().equalsIgnoreCase("yes")
Here's where your issue is.
the "yes" entered has already been consumed by the first test. Now the Scanner has nothing in the buffer.
If you want to test the SAME input again, you must capture it, and use that in your tests.
So
String userReply= Scanner.next();
if(userReply.equalsIgnoreCase("y")||userReply.equalsIgnoreCase("yes")) {...
This is becauswe, with each call to scanner.next(), the Scanner returns the next value in the stream, and then MOVES PAST IT
If the user had entered "yes" and then "no", the tests would be performed like this:
if("yes".equalsIgnoreCase("y")||"no".equalsIgnoreCase("yes")) {...
You need change the way of Scanner's calls.
The user input \n and Scanner seems don't follow with the next token. Then you need read line by line.
:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("How many players would you like to play with? ");
int m = Integer.parseInt(sc.nextLine()); // May thrown NumberFormatException
generateRandom(m);
//displays the cards
System.out.print("Would you like to play? ");
String input = sc.nextLine();
if (input.equalsIgnoreCase("y") || input.equalsIgnoreCase("yes")) {
System.out.println("This will be fun");
} else if (input.equalsIgnoreCase("n") || input.equalsIgnoreCase("no")) {
System.out.println("Maybe next time");
} else {
System.out.println("Invalid character");
}
}
I am having trouble coding a hw program that is made to generate test with multiple choice and essay questions. Everything works except my program skips lines when it goes to read a part of the essay class. I know it has to do with the scanner and scan.nextline, scan.nextInt and scan.next, etc but I am confused on how exactly to fix it.
Thank you for your help.
import java.util.*;
public class TestWriter
{
public static void main (String [] args)
{
Scanner scan = new Scanner (System.in);
String type=null;
System.out.println ("How many questions are on your test?");
int num = scan.nextInt ();
Question [] test = new Question [num];
for (int i=0; i <num; i++)
{
System.out.println ("Question " + (i+1) + ": Essay or multiple choice question? (e/m)");
type = scan.next ();
scan.nextLine ();
if (type.equals ("e"))
{
test [i] = new Essay ();
test [i].readQuestion ();
}
if (type.equals ("m"))
{
test [i] = new MultChoice ();
test [i].readQuestion ();
}
}
for (int i=0; i <num; i++)
{
System.out.println ("Question " + (i+1)+": "+ type);
test [i].print ();
}
}
}
here is the essay class
public class Essay extends Question
{
String question;
int line;
public void readQuestion ()
{
System.out.println ("How many lines?");
line = scan.nextInt ();
scan.next ();
System.out.println ("Enter the question");
question = scan.nextLine ();
}
public void print ()
{
System.out.println (question);
for (int i=0; i <line; i++)
System.out.println ("");
}
}
Using scan.nextInt() will generate the following problems
If your input is "5 5", nextInt() will get the next integer leaving the remaining " 5" of the buffer line. Of which the remaining " 5" will be caught by
type = scan.next();
In the class test writer:
System.out.println("How many questions are on your test?");
int num = scan.nextInt();
Question[] test = new Question[num]; for(int i=0; i<num; i++)
{
System.out.println("Question " + (i+1) + ": Essay or multiple choice question? (e/m)");
type = scan.next();
This will generate the issue as i have mentioned above.
To fix this you can either
a) Ensure that input is solely a number
b) Get the entire line like so String temp = scan.nextLine(); then convert it to a integer. This will you can play with the string and check if its the input you require i.e if the 1st letter / set of numerical digits is an e/m or an integer.
The problem with scan.nextInt() is that it only gets the next integer of the input line. If there are spaces after the input it was taken from i.e "5 5" it will grab only the next int 5 and leave " 5" behind.
Thus i would recommend using scan.nextLine() and manipulating the string to ensure that the input can be handled and verified and at the same time ensuring that you do not get confused of where the scanner is at.
You should use .next() / .nextInt() if you are handling an input with various parameters you want to specifically catch such as "25 Male Student 1234" in this case the code would be as such
int age = scan.nextInt();
String sex = scan.next();
String job = scan.next();
int score = scan.nextInt();
Your readQuestion function should be ...
public void readQuestion()
{
System.out.println("How many lines?");
line = scan.nextInt();
scan.nextLine();
System.out.println("Enter the question");
question = scan.nextLine();
}
It should be scan.nextLine(); to add an empty new line at the end
In your TestWriter.main() method what are you expecting at 3 line in following code:
System.out.println("Question " + (i+1) + ": Essay or multiple choice question? (e/m)");
type = scan.next();
scan.nextLine(); //LINE 3: What are you expecting user to enter over here.
the control flow will stuck at this point unless you enter something on the console.