For loop - validating input, program crashes (.hasNextInt()) - java

I am writting a program in java that adds 5 numbers (positive integers) entered by the user using a for loop.
I have managed to make it work when the right input is given and even when negative integers are given, but the program crashes when a non int is entered.
Any help is appreciated!
for (int i = 0; i < 5 ; i++ ) {
if (myScanner.hasNextInt()) {
x = myScanner.nextInt();
if (x < 0) {
System.out.println("Invalid input, enter again:");
x = myScanner.nextInt();
}
}
else {
System.out.println("Invalid input, enter again:");
x = myScanner.nextInt();// this works in the nested if but not here, why?
}
sum += x;
}
System.out.println("Sum is: " + sum);
}//end class

You check whether the scanner has a next integer and then afterwards, still ask for an integer which it doesn't have...
Here's a corrected version:
for (int i = 0; i < 5 ; i++ ) {
if (myScanner.hasNextInt()) {
x = myScanner.nextInt();
if (x < 0) {
System.out.println("Invalid input, enter again:");
} else {
sum += x;
}
}
else {
// get whatever is on the scanner, since we know it isn't and int
String crud = s.next();
System.out.println("Invalid input "+crud+" enter again:");
}
}

InputMismatchException is being thrown, try this logic where the x = myScanner.nextInt is being called from one place,
int count = 0;
while (true)
{
try
{
if (myScanner.hasNextInt())
{
x = myScanner.nextInt();
if (x < 0)
{
System.out.println("Invalid input, enter again:");
}
}
else
{
System.out.println("Invalid input, enter again:");
continue;
}
}
catch(Exception e)
{
System.out.println("Invalid input, enter again:");
continue;
}
count++;
sum += x;
if(count==5)break;
}

Related

How to display error message instead of java exception?

I am trying to make a Guessing Game for a Java assignment, I have everything I need except exception handling, you see I'm trying to make it display an error message instead of displaying Exception in thread "main" java.util.InputMismatchException when someone tries to enter a numerical number in alphabetical form. The code I have is followed.
(I know I need a try and catch but I don't know what to put exactly.)
package guessNumber;
import java.util.Scanner;
public class GuessNumberApp {
public static void main(String[] args) {
final int LIMIT = 10;
System.out.println("Guess the number!");
System.out.println("I'm thinking of a number from 1 to " + LIMIT);
System.out.println();
// get a random number between 1 and the limit
double d = Math.random() * LIMIT; // d is >= 0.0 and < limit
int number = (int) d; // convert double to int
number++; // int is >= 1 and <= limit
// prepare to read input from the user
Scanner sc = new Scanner(System.in);
int count = 1;
while (true) {
int guess = sc.nextInt();
System.out.println("You guessed: " + guess);
if (guess < 1 || guess > LIMIT) {
System.out.println("Your Guess is Invalid.");
continue;
}
if (guess < number) {
System.out.println("Too Low.");
} else if (guess > number) {
System.out.println("Too High.");
} else {
System.out.println("You guessed it in " + count + " tries.\n");
break;
}
count++;
}
System.out.println("Bye!");
}
}
try something like that:
try {
int guess = sc.nextInt();
} catch(InputMismatchException e) {
System.out.println("some nice error message");
continue;
}
This would replace
int guess = sc.nextInt();

How can I check that the next input is an integer while checking if it's > and < at the same time in Java?

There's two things I'm needing help with. Loop issue 1) I have to initialize this variable outside of the loop, which makes the loop fail if the user inputs a string. Is there a way around that? Basically, if I set N to anything then the do-while loop just immediately reads it after getting out of the
import java.util.Scanner;
/**
* Calculates sum between given number
*/
public class PrintSum {
public static void main(String[] args) {
int N = 0;
String word;
boolean okay;
Scanner scan = new Scanner(System.in);
System.out.print("Please enter a number from 1-100: ");
do {
if (scan.hasNextInt()) {
N = scan.nextInt();
} else {
okay = false;
word = scan.next();
System.err.print(word + " is an invalid input. Try again. ");
}
if (N > 100 || N < 1) {
okay = false;
System.err.print("Invalid Input. Try again. ");
} else {
okay = true;
}
} while (!okay);
loop(N, 0);
}
public static void loop(int P, int total) {
while (P >= 1) {
total = total + P;
P--;
}
System.out.println(total);
}
}
If not, then the issue becomes, how do I solve this? I thing that I need to be able to say
if (scan.hasNextInt() || ??? > 100 || ??? < 1) {
okay = false;
word = scan.next();
System.err.print(word + " is an invalid input. Try again. ");
} else {
okay = true;
}
What do I put in the ??? to make this work? I think I just don't know enough syntax.
Thank you!
Why don't you try this?
do {
if (scan.hasNextInt()) {
N = scan.nextInt();
} else {
okay = false;
word = scan.next();
System.err.print(word + " is an invalid input. Try again. ");
continue;
}
if (N > 100 || N < 1) {
okay = false;
System.err.print("Invalid Input. Try again. ");
continue;
} else {
okay = true;
}
} while (!okay);
break is used to end the loop as soon as the user enters the invalid character(condition of the else clause), so the loop doesn't fail.
Looking at your edited question, continue is what you are looking for if you might want to allow the user to enter another value after entering the invalid value.
Use break or continue based on requirement. More on breaks and continue.
Your second approach can be solved as follows:
if (scan.hasNextInt()){
N = scan.nextInt();
if (N > 100 || N < 1) {
System.err.print("Invalid input. Try again. ");
}
//perform some operation with the input
}
else{
System.err.print("Invalid Input. Try again. ");
}

Loop in a loop and If statement?

I am a beginner programming, I want to ask multiple questions using arrays and tell the user whether he got each question right or wrong, which I managed to get it running, but now how do I implement the code so that the user will only have up to 3 attempts to get a question right.
for(int n = 0; n <QArray.length; n++)
{
System.out.println("Question" + (n+1));
System.out.println(QArray[n]);
String ans = scanner.nextLine();
if (ans.equalsIgnoreCase(AArray[n]))
{
System.out.println("That is correct!");
}
else
{
System.out.println("That is incorrect!");
}
}
So if I correctly understand your goal, you've a list of questions, and whilst they have made fewer than three failed attempts at them, you would like for the users to get to try and answer them?
Using your existing style, you could do something like
for(int n = 0; n < QArray.length; n++)
{
System.out.println("Question" + (n+1));
System.out.println(QArray[n]);
int incorrectAnswers = 0;
while(incorrectAnswers < 3)
{
String ans = scanner.nextLine();
if (ans.equalsIgnoreCase(AArray[n]))
{
System.out.println("That is correct!");
break;
}
else
{
System.out.println("That is incorrect!");
incorrectAnswers++;
}
}
}
Depending how the data is displayed and transferred and concerns regarding security etc, it would make for easier to manage code to have a QuestionAnswer object that contains the question and the answer, as well as a method for what constitutes a valid answer (e.g. case insensitive, or maybe you want to accept multiple words etc, whatever works for your case), so you could end up with code that looks like the below.
for(int i = 0; i < questionAnswerArray.length; i++)
{
QuestionAnswer qa = questionAnswerArray[i];
System.out.println("Question " + (i+1));
System.out.println(qa.getQuestion());
int incorrectAnswers = 0;
while(incorrectAnswers < 3)
{
String ans = scanner.nextLine();
if (qa.isValidAnswer(ans))
{
System.out.println("That is correct!");
break;
}
else
{
System.out.println("That is incorrect!");
incorrectAnswers++;
}
}
}
Try to use while with the number of attempt you need:
for (int n = 0; n < QArray.length; n++) {
System.out.println("Question" + (n + 1));
System.out.println(QArray[n]);
int attempt = 3;
while (attempt > 0) {
System.out.print("Please enter the answer: ");
String ans = scanner.nextLine();
if (ans.equalsIgnoreCase(AArray[n])) {
System.out.println("That is correct!");
break;
} else {
System.out.println("That is incorrect!");
}
attempt--;
}
}
Put a second loop inside the first.
for(int n = 0; n < QArray.length; n++) {
boolean correct = false;
for(int m = 0; m < 3; m ++) {
String ans = scanner.nextLine();
if (ans.equalsIgnoreCase(AArray[n])) {
System.out.println("That is correct!");
correct = true;
break;
} else {
System.out.println("That is incorrect!");
}
}
if(!correct) {
//something
} else {
//something else
}
}
Note the break;. That command will exit the inner for-loop (which contains the scanner input) when a correct answer is submitted. If the user doesn't get the right answer in 3 tries, the for-loop will end by reaching the end of its counter.

How to check if user input is String, double or long in Java

I'm a beginner in java. I want to check first if the user input is String or Double or int. If it's String, double or a minus number, the user should be prompted to enter a valid int number again. Only when the user entered a valid number should then the program jump to try. I've been thinking for hours and I come up with nothing useful.Please help, thank you!
import java.util.InputMismatchException;
import java.util.Scanner;
public class Fizz {
public static void main(String[] args) {
System.out.println("Please enter a number");
Scanner scan = new Scanner(System.in);
try {
Integer i = scan.nextInt();
if (i % 3 == 0 && (i % 5 == 0)) {
System.out.println("FizzBuzz");
} else if (i % 3 == 0) {
System.out.println("Fizz");
} else if (i % 5 == 0) {
System.out.println("Buzz");
} else {
System.out.println(i + "は3と5の倍数ではありません。");
}
} catch (InputMismatchException e) {
System.out.println("");
} finally {
scan.close();
}
}
One simple fix is to read the entire line / user input as a String.
Something like this should work. (Untested code) :
String s=null;
boolean validInput=false;
do{
s= scannerInstance.nextLine();
if(s.matches("\\d+")){// checks if input only contains digits
validInput=true;
}
else{
// invalid input
}
}while(!validInput);
You can also use Integer.parseInt and then check that integer for non negativity. You can catch NumberFormatException if the input is string or a double.
Scanner scan = new Scanner(System.in);
try {
String s = scan.nextLine();
int x = Integer.parseInt(s);
}
catch(NumberFormatException ex)
{
}
Try this one. I used some conditions to indicate the input.
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
int charCount = input.length();
boolean flag = false;
for(int x=0; x<charCount; x++){
for(int y=0; y<10; y++){
if(input.charAt(x)==Integer.toString(y))
flag = true;
else{
flag = false;
break;
}
}
}
if(flag){
if(scan.hasNextDouble())
System.out.println("Input is Double");
else
System.out.println("Input is Integer");
}
else
System.out.println("Invalid Input. Please Input a number");
Try this. It will prompt for input until an int greater than 0 is entered:
System.out.println("Please enter a number");
try (Scanner scan = new Scanner(System.in)) {
while (scan.hasNext()) {
int number;
if (scan.hasNextInt()) {
number = scan.nextInt();
} else {
System.out.println("Please enter a valid number");
scan.next();
continue;
}
if (number < 0) {
System.out.println("Please enter a number > 0");
continue;
}
//At this stage, the number is an int >= 0
System.out.println("User entered: " + number);
break;
}
}
boolean valid = false;
double n = 0;
String userInput = "";
Scanner input = new Scanner(System.in);
while(!valid){
System.out.println("Enter the number: ");
userInput = input.nextLine();
try{
n = Double.parseDouble(userInput);
valid = true;
}
catch (NumberFormatException ex){
System.out.println("Enter the valid number.");
}
}

Java While Loop

Whenever I try to run this loop, I receive:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:840)
at java.util.Scanner.next(Scanner.java:1461)
at java.util.Scanner.nextInt(Scanner.java:2091)
at java.util.Scanner.nextInt(Scanner.java:2050)
at test.readNumber(Lab2.java:28)
at test.go(Lab2.java:15)
at test.main(Lab2.java:7)
I'm trying to repeatedly prompt the user until the keyboard input is positive. Can anyone tell me how I can go about doing that without running into error?
public int readNumber() {
int x = keyboard.nextInt();
while (x < 0) {
System.out.println("Please enter a positive number.");
x = keyboard.nextInt();
}
return x;
}
It is always a good idea to check the docs. The exception is thrown if input data doesn't match the "Integer" pattern. Wrap input with try/catch:
public int readNumber() {
int x = -1;
while (x < 0) {
System.out.println("Please enter a positive number.");
try {
x = keyboard.nextInt();
} catch (java.util.InputMismatchException e) {
// oops, wrong input
}
}
return x;
}
public int readNumber() {
int x = -1;
do {
try {
System.out.println("Please enter a positive number.");
x = keyboard.nextInt();
} catch (InputMismatchException e) {
// normally you always want to handle the exception but in this case it is okay because mismatched input is the same as a non-positive integer input
}
} while (x < 0);
return x;
}
You are either not supplying an integer or giving a value for an integer which is out of range.
You have to read the EOL after reading te int value.
public int readNumber() {
int x = keyboard.nextInt();
keyboard.readNextLine();
while (x < 0) {
System.out.println("Please enter a positive number.");
x = keyboard.nextInt();
keyboard.readNextLine();
}
return x;
}

Categories