Java - String Input Exception Handling - java

I´m totally new to Java and I´m stuck. I have to create the game "guess the Number". I´m able to do the most parts but I´m don´t now how to handle the User Input if its a String.
I want to be able to tell the User that the Input was not correct if he enters a String, and repeatedly ask for Input. It would be great if someone could help me here :)
Here is my Code:
import java.util.Scanner;
import java.util.Random;
public class SWENGB_HW_2 {
public static void main(String[] args) {
System.out.println("Welcome to the guess the number game!\n");
System.out.println("Please specify the configuration of the game:\n");
Scanner input = new Scanner(System.in);
System.out.println("Range start number (inclusively):");
int startRange;
startRange = input.nextInt();
System.out.println("Range end (inclusively):");
int endRange;
endRange = input.nextInt();
System.out.println("Maximum number of attemps:");
int maxAttemp;
maxAttemp = input.nextInt();
System.out.println("Your Task is to guess the random number between "
+ startRange + " and " + endRange);
Random randGenerator = new Random();
int randNumber = randGenerator.nextInt((endRange - startRange) + 1)
+ startRange;
int numberOfTries = 0;
System.out
.println("You may exit the game by typing; exit - you may now start to guess:");
String exit;
exit = input.nextLine();
for (numberOfTries = 0; numberOfTries <= maxAttemp - 1; numberOfTries++) {
int guess;
guess = input.nextInt();
if (guess == randNumber) {
System.out.println("Congratz - you have made it!!");
System.out.println("Goodbye");
} else if (guess > randNumber) {
System.out.println("The number is smaller");
} else if (guess < randNumber) {
System.out.println("The number is higher");
}
}
if (numberOfTries >= maxAttemp) {
System.out.println("You reached the max Number of attempts :-/");
}
}
}

You can create a utility method that looks like this:
public static int nextValidInt(Scanner s) {
while (!s.hasNextInt())
System.out.println(s.next() + " is not a valid number. Try again:");
return s.nextInt();
}
and then, instead of
startRange = input.nextInt()
you do
startRange = nextValidInt(input);
If you want to deal with the "exit" alternative, I'd recommend something like this:
public static int getInt(Scanner s) throws EOFException {
while (true) {
if (s.hasNextInt())
return s.nextInt();
String next = s.next();
if (next.equals("exit"))
throw new EOFException();
System.out.println(next + " is not a valid number. Try again:");
}
}
and then wrap the whole program in
try {
...
...
...
} catch (EOFException e) {
// User typed "exit"
System.out.println("Bye!");
}
} // End of main.
Btw, the rest of your code looks great. I've tried it and it works like a charm :-)

You could check that the scanner has an int before you attempt to read it. You can do that by calling hasNextInt() with something like
while (input.hasNext() && !input.hasNextInt()) {
System.out.printf("Please enter an int, %s is not an int%n", input.next());
}
int startRange = input.nextInt();

Related

infinite loop in a while statement

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;
}

Parsing a String to an Integer

So my biggest problem is that I cannot seem to remember how to parse a string into an int so that I can idiot proof my code. My goal here is to find out if the user enters in a word instead of an int and then I can explain to them what an integer is. Can someone please help? I just need a simple list of parsing commands so that I can study them for use in the future, once there is a simple list I think I'll be able to figure all the others out from there.
import java.util.Scanner;
import java.util.*;
public class SelfTestNumberNine
{
public static void main(String[] args)
{
boolean test = false;
int num = 0;
int sum = 0;
int count = 0;
int pos = 0;
int neg = 0;
Scanner in = new Scanner(System.in);
while(!test)
{
num = 0;
System.out.print("Enter in an Integer Value: ");
String letta = in.next();
if(??parsing stuff goes here!!)
{
num = in.nextInt();
count++;
if(num > 0)
{
pos++;
sum = sum + num;
}
else if(num < 0)
{
neg++;
sum = num + sum;
}
else
{
test = true;
}
}
else
{
System.out.println("An Integer is a number that is positive or
negative,\nand does not include a decimal point.");
}
}//end while
System.out.println("Total: " + sum);
double avg = sum / count;
System.out.println("Average: " + avg);
}//end main
}//end class
Basically, the program asks the user to input integers, counts the number of positive and negatives, and prints out the total and average (Ignoring 0). The program ends when the user inputs a 0.
P.S. Thanks for your time!! ]:-)
If you want to ensure that the user has entered an int without throwing an exception if they don't you can use the hasNextInt() method:
System.out.println("Enter an int (0) to quit");
//While the user has not entered a valid int
while (!input.hasNextInt()) {
System.out.println("Please enter an integer: ");
//Consume the bad input
input.nextLine();
}
Which will loop until they enter a valid int. A sample run (- denotes user input):
Enter an int (0 to quit)
-No
Please enter an integer:
-Never!!
Please enter an integer:
-Ok ok fine
Please enter an integer:
-3
You can do this in two ways.
- Integer.parseInt()
- Integer.valueOf()
String myStr = "1";
int parsedInt = Integer.parseInt(myStr);
int valueOf = Integer.valueOf(myStr);
System.out.println("Parse Int: " + parsedInt);
System.out.println("Value Of: " + valueOf);
Note: You might get exception if the input is not parseable. NumberFormatException.
You can use a Boolean method and a try-catch to check if you can parse the string to an Integer.
public static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch(NumberFormatException e) {
return false;
} catch(NullPointerException e) {
return false;
}
// only got here if we didn't return false
return true;
}

Strict integer-only if/then loops

Using Java to compile a code that takes in any input, from strings to doubles, floats, integers, etc., but can only process based on integers. If it receives a double, float, or a string, it will just produce a message prompting the user to try again. I'm not sure exactly how to get this rolling, so here's my current code.
import java.util.Scanner;
public class Sand
{
public static void main(String[] args)
{
int firstInt, secondInt, thirdInt;
Scanner keyboard = new Scanner(System.in);
System.out.println("Hi. I'm going to be asking you for three integers in just a moment.");
System.out.println("An integer is defined as a WHOLE number that's not a fraction or decimal.");
System.out.println("I swear to you, I will go off if you put in a non-whole number...");
System.out.println("Okay go ahead and type in the first of the three integers:");
if (keyboard.hasNextInt())
{
firstInt = keyboard.nextInt();
System.out.println("Red.");
System.out.println("So the first integer is " + firstInt);
System.out.println("Okay go ahead and type in the second of the three integers: ");
if (keyboard.hasNextInt())
{
secondInt = keyboard.nextInt();
System.out.println("Green.");
System.out.println("So the first and second integers are " + firstInt + " and " + secondInt);
}
else
{
System.out.println("Orange.");
System.out.println("Please try again.");
}
}
else
{
System.out.println("Blue.");
System.out.println("Please try again.");
}
}
}
I have orange and blue representing times in which there are some input errors, but it's not complete. I'm not sure how to approach this, be it a while loop or a for loop or a try/catch. I'm new when it comes to learning Java so some #notes would be helpful along the way. The code is to designed to read three numbers that are integers from the user in a string. That's straightforward, but analyzing the input is where I'm struggling.
This is not meant to answer your question totally but to point you in the right direction. There should be enough here to help you figure out what else is needed for your program.
import java.util.Scanner;
public class Sandbox {
// arguments are passed using the text field below this editor
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int num = 0;
System.out.println("enter an integer");
while (true) { //keep prompting the user until they comply
try {
num = Integer.parseInt(keyboard.nextLine());
keyboard.close();
break;
} catch (NumberFormatException e) {
System.out.println("You must enter an integer");
}
}
System.out.println("num: " + num);
}
}
I, personally, would use an array or arrayList (based on your needs) to store the int values and then use a while loop to check and accept the numbers. while (array.length < 3) do {int checking}. This way the script will not run if there are already 3 values in the array and will run until you get 3 values.
this should do the job..
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int[] intArray = new int[3];
Scanner keyboard = new Scanner(System.in);
for (int i = 0; i < intArray.length; i++) {
System.out.print("input integer #"+(i+1)+": ");
if (keyboard.hasNextInt()) {
intArray[i] = keyboard.nextInt();
System.out.println("value for #"+(i+1)+": " + intArray[i]);
} else
{
System.out.println("not an integer");
break;
}
}
keyboard.close();
}
}
or maybe another solution that asks again when the number was no integer
import java.util.Scanner;
public class Main2 {
public static void main(String[] args) {
int[] intArray = new int[3];
Scanner keyboard = new Scanner(System.in);
for (int i = 0; i < intArray.length; i++) {
boolean isInputCorrect = false;
do {
System.out.print("input integer #" + (i + 1) + ": ");
if (keyboard.hasNextInt()) {
intArray[i] = keyboard.nextInt();
System.out.println("value for #" + (i + 1) + ": " + intArray[i]);
isInputCorrect = true;
} else {
System.out.println("not an integer, try again");
keyboard.nextLine();
}
} while (!isInputCorrect);
}
keyboard.close();
}
}

How to find the average in a do-while loop

I have to write a program that asks the user to enter an integer value. After each value, the user has to respond with a "y" or a "n" if he/she wants to continue with the program, and each number the user enters is stated as either odd or even.
I have done this so far with a do-while loop, but I am confused on how to get the averages of the values the user enters. How would you get the average for all the numbers entered?
Here is my code so far:
import java.util.Scanner;
class ProgramTest {
public static void main(String[] args) {
String answer = "";
do {
int num, count = 0;
Scanner scan = new Scanner(System. in );
System.out.print("Enter any number : ");
num = scan.nextInt();
if ((num % 2) == 0) System.out.println(num + " is an even number.");
else System.out.println(num + " is an odd number");
System.out.println("do you want to continue?");
answer = scan.next();
count++;
} while (answer.equals("y"));
}
}
From the Question looks like following things need to handled,
haven't add mechanism for addition into single variable.
put all variable to out from do...while loop body...
created additional variable according to requirement.
see all this things covered by me with following code snippet.
do something likewise,
String answer = "";
double sum = 0; // use for storing addition to all entered values..
int num, count = 0;
Scanner scan = new Scanner(System.in);
do {
System.out.print("Enter any number : ");
num = scan.nextInt(); // getting input from user through console
sum = sum + num; // add every input number into sum-variable
if ((num % 2) == 0) System.out.println(num + " is an even number.");
else System.out.println(num + " is an odd number");
System.out.println("do you want to continue?");
answer = scan.next(); // ask for still want to repeat..
count++;
} while (answer.equals("y"));
System.out.println("Average is : " + sum + "/" + count + " = "+ (sum /count));
In order to calculate Average, you need 2 things: Sum of all numbers and Count of all numbers involved in the Average calculation.
Your sum and count which involved in the Average calculation needs to be out of the do..while scope in order for them to be known at the calculation stage.
I also took the liberty of fixing your code a little bit
import java.util.Scanner;
class ProgramTest {
public static void main(String[] args) {
Scanner scan = new Scanner(System. in );
int count = 0;
int sum = 0;
String answer = "";
do {
System.out.print("Enter any number : ");
int num = scan.nextInt();
boolean isEven = (num % 2 == 0);
System.out.println(num + " is an " + (isEven ? "even" : "odd") + " number.");
sum += num;
System.out.println("do you want to continue?");
answer = scan.next();
count++;
} while (answer.toLowerCase().equals("y"));
System.out.println("Average: " + (sum/count));
}
}
Change your code like this:
import java.util.Scanner;
class ProgramTest {
public static void main(String[] args) {
String answer = "";
int avr =0;
int num, count = 0;
do {
Scanner scan = new Scanner(System. in );
System.out.print("Enter any number : ");
num = scan.nextInt();
if ((num % 2) == 0) System.out.println(num + " is an even number.");
else System.out.println(num + " is an odd number");
System.out.println("do you want to continue?");
avr += num;
answer = scan.next();
count++;
} while (answer.equals("y"));
avr = avr /count;
System.out.println("The avreage of value is:" + avr );
}
}
avr is average. that means when you input an integer. we add num and avr . and when finish looping. we divideto count. like this:
1-5-9-11
avr = 1+5+9+11;
count = 4;
avr = avr/4;

Only allowing numbers to be taken from user input in java

I have a little averaging program I have made and, I am trying to only allow it to take in numbers. Everything else works but, I can't seem to figure it out. I am still learning so, any advise or pointers would be awesome!
Here is my code.
import java.util.Scanner;
public class THISISATEST {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int sum = 0;
int count = 0;
int i = 1;
while (i <= 10) {
i++;
{
System.out.print("Enter the test score: ");
int tS = keyboard.nextInt();
count++;
sum = (sum + tS);
}
System.out.println(sum);
}
System.out.println("The Average is = " + sum / count);
}
}
Inside your while loop use the following code:
System.out.print("Enter the test score: ");
while (!keyboard.hasNextInt()) {//Will run till an integer input is found
System.out.println("Only number input is allowed!");
System.out.print("Enter the test score: ");
keyboard.next();
}
int tS = keyboard.nextInt();
//If input is a valid int value then the above while loop would not be executed
//but it will be assigned to your variable 'int ts'
count++;
sum = (sum + tS);

Categories

Resources