input value stays 0 when trying to prompt their input - java

I am trying to prompt a user with the value they inputted and an error message if it's not an integer. When I try to prompt them, their input stays 0 when the input is a double or string.
//main method
public static void main(String[] args) {
int i = 0;
//instantiate new Scanner for user input
Scanner input = new Scanner(System.in);
//parse imput, display value
//and prompt user that their input is not a int
try {
inputNum = Integer.parseInt(input.next());
System.out.println("Value entered is " +
String.valueOf(inputNum));
} catch(NumberFormatException e) {
System.out.println("Value entered is " +
String.valueOf(inputNum));
System.out.println(String.valueOf(inputNum) + " is not an integer.");
}
}
}

If the input is a double or a string then parseInt would throw an exception and inputNum would not be assigned any new value. You could store input.next() in a string before passing it to parseInt - or you might be able to use e in the catch block to figure out the bad value
String s;
//parse imput, display value
//and prompt user that their input is not a int
try {
s = input.next();
System.out.println("Value entered is " + s);
inputNum = Integer.parseInt(s);
} catch(NumberFormatException e) {
System.out.println(s + " is not an integer.");
}
}
}

Well, it's a concept ('ask user for some input, keep asking if it is not valid') that you may want to do more than once, so it has no business being in main.
Give it its own method.
This method would take as input a 'prompt' and will return a number. The purpose is to ask the user (with that prompt) for a number, and to keep asking until they enter one.
You can use while() to loop code until a certain condition is met, or simply forever, using return to escape the loop and the entire 'ask the user for a number' method in one fell swoop.

I've modified the code to make it work according to your need:
public static void main(String[] args) {
//instantiate new Scanner for user input
Scanner input = new Scanner(System.in);
//parse imput, display value
//and prompt user that their input is not a int
String inputNum = input.next();
try {
System.out.println("Value entered is " +
Integer.parseInt(inputNum));
} catch (NumberFormatException e) {
System.out.println("Value entered is " +
inputNum);
System.out.println(inputNum + " is not an integer.");
}
}
Above is the standard approach to check if a String is an integer in java. If you want a simpler & powerful way you can leverage the Apache Commons library:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
final String num = input.next();
// check to see if num is a number
if (NumberUtils.isCreatable(num)) {
System.out.println("Value entered is " + num);
} else {
System.out.println("Value entered is " + num);
System.out.println(num + " is not a number.");
}
}
Note that NumberUtils#isCreatable checks for a wide variety of number formats(integer, float, scientific...)
If you want something equivalent to Integer#parseInt, Long#parseLong, Float#parseFloat or Double#parseDouble. Use instead, NumberUtils#isParsable.

There is an another concise way to do it without throwing any exception, you can use hasNextInt() to pre-validate if the input value is a valid integer before hand, then use nextInt() to read an integer without parsing the string:
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
int inputNum;
if(scanner.hasNextInt()){
inputNum = scanner.nextInt();
System.out.println("Value entered is " + inputNum);
}else{
System.out.println(scanner.next() + " is not an integer.");
}
}

Related

Having trouble with implementing a system that detects if an input is a integer or not

I'm trying to make a system that asks the user how many times they want a phrase to be repeated and then it checks if the answer is an integer or a string. The program works well when I don't try to implement this system and leave it just at asking the phrase and how many times it should be repeated but it falls appart when I try to check if the amount of times is an integer or not.
import java.util.*;
public class Phrase {
public static Scanner phraseScan = new Scanner (System.in);
public static Scanner amountScan = new Scanner (System.in);
public static void main (String[] args ) {
System.out.println("What phrase do you want repeated?");
String phrase = phraseScan.nextLine();
int phraseLoops = 0;
System.out.println("How many " + phrase + "s" + " do you want?");
int desiredPhraseLoops = amountScan.nextInt();
for (;;) {
if (!amountScan.hasNextInt()) {
System.out.println("Integers only please");
amountScan.next();
}
desiredPhraseLoops = amountScan.nextInt();
if (desiredPhraseLoops >= 0) {
System.out.println("Valid amount!");
continue;
} else {
break;
}
}
System.out.println(desiredPhraseLoops + " " + phrase + "s coming your way!");
do {
System.out.println(phrase);
phraseLoops++;
} while (phraseLoops != desiredPhraseLoops);
System.out.println("You printed " + phraseLoops + " " + phrase + "s" );
}
}
What I've tried:
try {
desiredPhraseLoops = amountScan.nextInt();
} catch (InputMismatchException exception) {
System.out.println("This is not an integer.");
}
if (!amountScan.hasNextInt()) {
System.out.println("Good.");
} else {
System.out.println("Enter an Integer please.");
}
Any time I tried anything, it would ask which phrase I wanted and how many times I wanted it repeated. And then the program just stopped afterward, no matter if I put in an integer or a string, it just didnt give me any other prompts.
The output is this:
What phrase do you want repeated?
Test
How many Tests do you want?
3
And that's it.
To begin with, just use one Scanner object. You don't need more than that for keyboard input.
If you like, you can just stick with the Scanner#nextLine() method, for example:
Scanner userInput = new Scanner(System.in);
String phrase = "";
while (phrase.equals("")) {
System.out.println("What phrase do you want repeated?");
phrase = userInput.nextLine();
// VALIDATION:
// Was anything other than a empty string (spaces)
// or longer than 2 characters supplied?
if (phrase.trim().equals("") || phrase.length() < 3) {
// Nope!
System.err.println("Invalid Input!. Enter a proper phrase!");
phrase = "";
}
// Yes, allow the prompt loop to exit.
}
String phraseLoopsNumber = "";
while (phraseLoopsNumber.equals("")) {
System.out.println("How many " + phrase + "s" + " do you want?");
phraseLoopsNumber = userInput.nextLine();
// VALIDATION:
// Did the User supply a string representation of an integer value?
if (!phraseLoopsNumber.matches("\\d+")) {
// Nope!
System.out.println("Invalid Input (" + phraseLoopsNumber + ")! An integer value is expected!");
phraseLoopsNumber = "";
}
// Yes he/she/it did...Allow prompt loop to exit.
}
int numberOfLoops = Integer.parseInt(phraseLoopsNumber);
// Do what you have to do with the desired number of loops contained
// within the numberOfLoops integer variable.
In the above code, the String#matches() method was used along with a small Regular Expression (RegEx). The "\\d" expression passed to the matches() method checks to see if the string it is working against contains all (1 or more) digits.
If however you're hell bent on using the Scanner#nextInt() method then you can do it this way:
int numberOfLoops = -1;
while (numberOfLoops == -1) {
System.out.println("How many " + phrase + "'s" + " do you want?");
// Trap any input errors against the Scanner.nextInt() method...
// This would be a form of validation.
try {
numberOfLoops = userInput.nextInt();
// Consume the newline from ENTER key in case a nextLine() prompt is next.
userInput.nextLine();
} catch (Exception ex) {
System.out.println("Invalid Input! An integer value is expected!");
// Consume the newline from ENTER key in case a nextLine() prompt is next.
// The first one above would of been skipped past if nextInt() threw an exception.
userInput.nextLine();
numberOfLoops = -1;
continue; // continue loop so as to re-prompt
}
// Further Validation:
// Did the User supply a number greater than 0?
if (numberOfLoops < 1 ) {
// Nope!
System.out.println("Invalid Input (" + numberOfLoops + ")! A value 1 or greater is expected!");
numberOfLoops = -1;
}
// Yes he/she did...Allow prompt loop to exit.
}
// Do what you have to do with the desired number of loops contained
// within the numberOfLoops integer variable.

Keep running int errors while trying to ask my code to run a y/n while loop [duplicate]

I attempted to create a calculator, but I can not get it to work because I don't know how to get user input.
How can I get the user input in Java?
One of the simplest ways is to use a Scanner object as follows:
import java.util.Scanner;
Scanner reader = new Scanner(System.in); // Reading from System.in
System.out.println("Enter a number: ");
int n = reader.nextInt(); // Scans the next token of the input as an int.
//once finished
reader.close();
You can use any of the following options based on the requirements.
Scanner class
import java.util.Scanner;
//...
Scanner scan = new Scanner(System.in);
String s = scan.next();
int i = scan.nextInt();
BufferedReader and InputStreamReader classes
import java.io.BufferedReader;
import java.io.InputStreamReader;
//...
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();
int i = Integer.parseInt(s);
DataInputStream class
import java.io.DataInputStream;
//...
DataInputStream dis = new DataInputStream(System.in);
int i = dis.readInt();
The readLine method from the DataInputStream class has been deprecated. To get String value, you should use the previous solution with BufferedReader
Console class
import java.io.Console;
//...
Console console = System.console();
String s = console.readLine();
int i = Integer.parseInt(console.readLine());
Apparently, this method does not work well in some IDEs.
You can use the Scanner class or the Console class
Console console = System.console();
String input = console.readLine("Enter input:");
You can get user input using BufferedReader.
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String accStr;
System.out.println("Enter your Account number: ");
accStr = br.readLine();
It will store a String value in accStr so you have to parse it to an int using Integer.parseInt.
int accInt = Integer.parseInt(accStr);
Here is how you can get the keyboard inputs:
Scanner scanner = new Scanner (System.in);
System.out.print("Enter your name");
String name = scanner.next(); // Get what the user types.
The best two options are BufferedReader and Scanner.
The most widely used method is Scanner and I personally prefer it because of its simplicity and easy implementation, as well as its powerful utility to parse text into primitive data.
Advantages of Using Scanner
Easy to use the Scanner class
Easy input of numbers (int, short, byte, float, long and double)
Exceptions are unchecked which is more convenient. It is up to the programmer to be civilized, and specify or catch the exceptions.
Is able to read lines, white spaces, and regex-delimited tokens
Advantages of BufferedInputStream
BufferedInputStream is about reading in blocks of data rather than a single byte at a time
Can read chars, char arrays, and lines
Throws checked exceptions
Fast performance
Synchronized (you cannot share Scanner between threads)
Overall each input method has different purposes.
If you are inputting large amount of data BufferedReader might be
better for you
If you are inputting lots of numbers Scanner does automatic parsing
which is very convenient
For more basic uses I would recommend the Scanner because it is easier to use and easier to write programs with. Here is a quick example of how to create a Scanner. I will provide a comprehensive example below of how to use the Scanner
Scanner scanner = new Scanner (System.in); // create scanner
System.out.print("Enter your name"); // prompt user
name = scanner.next(); // get user input
(For more info about BufferedReader see How to use a BufferedReader and see Reading lines of Chars)
java.util.Scanner
import java.util.InputMismatchException; // import the exception catching class
import java.util.Scanner; // import the scanner class
public class RunScanner {
// main method which will run your program
public static void main(String args[]) {
// create your new scanner
// Note: since scanner is opened to "System.in" closing it will close "System.in".
// Do not close scanner until you no longer want to use it at all.
Scanner scanner = new Scanner(System.in);
// PROMPT THE USER
// Note: when using scanner it is recommended to prompt the user with "System.out.print" or "System.out.println"
System.out.println("Please enter a number");
// use "try" to catch invalid inputs
try {
// get integer with "nextInt()"
int n = scanner.nextInt();
System.out.println("Please enter a decimal"); // PROMPT
// get decimal with "nextFloat()"
float f = scanner.nextFloat();
System.out.println("Please enter a word"); // PROMPT
// get single word with "next()"
String s = scanner.next();
// ---- Note: Scanner.nextInt() does not consume a nextLine character /n
// ---- In order to read a new line we first need to clear the current nextLine by reading it:
scanner.nextLine();
// ----
System.out.println("Please enter a line"); // PROMPT
// get line with "nextLine()"
String l = scanner.nextLine();
// do something with the input
System.out.println("The number entered was: " + n);
System.out.println("The decimal entered was: " + f);
System.out.println("The word entered was: " + s);
System.out.println("The line entered was: " + l);
}
catch (InputMismatchException e) {
System.out.println("\tInvalid input entered. Please enter the specified input");
}
scanner.close(); // close the scanner so it doesn't leak
}
}
Note: Other classes such as Console and DataInputStream are also viable alternatives.
Console has some powerful features such as ability to read passwords, however, is not available in all IDE's (such as Eclipse). The reason this occurs is because Eclipse runs your application as a background process and not as a top-level process with a system console. Here is a link to a useful example on how to implement the Console class.
DataInputStream is primarily used for reading input as a primitive datatype, from an underlying input stream, in a machine-independent way. DataInputStream is usually used for reading binary data. It also provides convenience methods for reading certain data types. For example, it has a method to read a UTF String which can contain any number of lines within them.
However, it is a more complicated class and harder to implement so not recommended for beginners. Here is a link to a useful example how to implement a DataInputStream.
You can make a simple program to ask for user's name and print what ever the reply use inputs.
Or ask user to enter two numbers and you can add, multiply, subtract, or divide those numbers and print the answers for user inputs just like a behavior of a calculator.
So there you need Scanner class. You have to import java.util.Scanner; and in the code you need to use
Scanner input = new Scanner(System.in);
Input is a variable name.
Scanner input = new Scanner(System.in);
System.out.println("Please enter your name : ");
s = input.next(); // getting a String value
System.out.println("Please enter your age : ");
i = input.nextInt(); // getting an integer
System.out.println("Please enter your salary : ");
d = input.nextDouble(); // getting a double
See how this differs: input.next();, i = input.nextInt();, d = input.nextDouble();
According to a String, int and a double varies same way for the rest. Don't forget the import statement at the top of your code.
Also see the blog post "Scanner class and getting User Inputs".
To read a line or a string, you can use a BufferedReader object combined with an InputStreamReader one as follows:
BufferedReader bufferReader = new BufferedReader(new InputStreamReader(System.in));
String inputLine = bufferReader.readLine();
Here, the program asks the user to enter a number. After that, the program prints the digits of the number and the sum of the digits.
import java.util.Scanner;
public class PrintNumber {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int num = 0;
int sum = 0;
System.out.println(
"Please enter a number to show its digits");
num = scan.nextInt();
System.out.println(
"Here are the digits and the sum of the digits");
while (num > 0) {
System.out.println("==>" + num % 10);
sum += num % 10;
num = num / 10;
}
System.out.println("Sum is " + sum);
}
}
Here is your program from the question using java.util.Scanner:
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
int input = 0;
System.out.println("The super insano calculator");
System.out.println("enter the corrosponding number:");
Scanner reader3 = new Scanner(System.in);
System.out.println(
"1. Add | 2. Subtract | 3. Divide | 4. Multiply");
input = reader3.nextInt();
int a = 0, b = 0;
Scanner reader = new Scanner(System.in);
System.out.println("Enter the first number");
// get user input for a
a = reader.nextInt();
Scanner reader1 = new Scanner(System.in);
System.out.println("Enter the scend number");
// get user input for b
b = reader1.nextInt();
switch (input){
case 1: System.out.println(a + " + " + b + " = " + add(a, b));
break;
case 2: System.out.println(a + " - " + b + " = " + subtract(a, b));
break;
case 3: System.out.println(a + " / " + b + " = " + divide(a, b));
break;
case 4: System.out.println(a + " * " + b + " = " + multiply(a, b));
break;
default: System.out.println("your input is invalid!");
break;
}
}
static int add(int lhs, int rhs) { return lhs + rhs; }
static int subtract(int lhs, int rhs) { return lhs - rhs; }
static int divide(int lhs, int rhs) { return lhs / rhs; }
static int multiply(int lhs, int rhs) { return lhs * rhs; }
}
Scanner input = new Scanner(System.in);
String inputval = input.next();
Scanner input=new Scanner(System.in);
int integer=input.nextInt();
String string=input.next();
long longInteger=input.nextLong();
Just one extra detail. If you don't want to risk a memory/resource leak, you should close the scanner stream when you are finished:
myScanner.close();
Note that java 1.7 and later catch this as a compile warning (don't ask how I know that :-)
Here is a more developed version of the accepted answer that addresses two common needs:
Collecting user input repeatedly until an exit value has been entered
Dealing with invalid input values (non-integers in this example)
Code
package inputTest;
import java.util.Scanner;
import java.util.InputMismatchException;
public class InputTest {
public static void main(String args[]) {
Scanner reader = new Scanner(System.in);
System.out.println("Please enter integers. Type 0 to exit.");
boolean done = false;
while (!done) {
System.out.print("Enter an integer: ");
try {
int n = reader.nextInt();
if (n == 0) {
done = true;
}
else {
// do something with the input
System.out.println("\tThe number entered was: " + n);
}
}
catch (InputMismatchException e) {
System.out.println("\tInvalid input type (must be an integer)");
reader.nextLine(); // Clear invalid input from scanner buffer.
}
}
System.out.println("Exiting...");
reader.close();
}
}
Example
Please enter integers. Type 0 to exit.
Enter an integer: 12
The number entered was: 12
Enter an integer: -56
The number entered was: -56
Enter an integer: 4.2
Invalid input type (must be an integer)
Enter an integer: but i hate integers
Invalid input type (must be an integer)
Enter an integer: 3
The number entered was: 3
Enter an integer: 0
Exiting...
Note that without nextLine(), the bad input will trigger the same exception repeatedly in an infinite loop. You might want to use next() instead depending on the circumstance, but know that input like this has spaces will generate multiple exceptions.
import java.util.Scanner;
class Daytwo{
public static void main(String[] args){
System.out.println("HelloWorld");
Scanner reader = new Scanner(System.in);
System.out.println("Enter the number ");
int n = reader.nextInt();
System.out.println("You entered " + n);
}
}
Add throws IOException beside main(), then
DataInputStream input = new DataInputStream(System.in);
System.out.print("Enter your name");
String name = input.readLine();
It is very simple to get input in java, all you have to do is:
import java.util.Scanner;
class GetInputFromUser
{
public static void main(String args[])
{
int a;
float b;
String s;
Scanner in = new Scanner(System.in);
System.out.println("Enter a string");
s = in.nextLine();
System.out.println("You entered string " + s);
System.out.println("Enter an integer");
a = in.nextInt();
System.out.println("You entered integer " + a);
System.out.println("Enter a float");
b = in.nextFloat();
System.out.println("You entered float " + b);
}
}
import java.util.Scanner;
public class Myapplication{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int a;
System.out.println("enter:");
a = in.nextInt();
System.out.println("Number is= " + a);
}
}
You can get user input like this using a BufferedReader:
InputStreamReader inp = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(inp);
// you will need to import these things.
This is how you apply them
String name = br.readline();
So when the user types in his name into the console, "String name" will store that information.
If it is a number you want to store, the code will look like this:
int x = Integer.parseInt(br.readLine());
Hop this helps!
Can be something like this...
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Enter a number: ");
int i = reader.nextInt();
for (int j = 0; j < i; j++)
System.out.println("I love java");
}
You can get the user input using Scanner. You can use the proper input validation using proper methods for different data types like next() for String or nextInt() for Integer.
import java.util.Scanner;
Scanner scanner = new Scanner(System.in);
//reads the input until it reaches the space
System.out.println("Enter a string: ");
String str = scanner.next();
System.out.println("str = " + str);
//reads until the end of line
String aLine = scanner.nextLine();
//reads the integer
System.out.println("Enter an integer num: ");
int num = scanner.nextInt();
System.out.println("num = " + num);
//reads the double value
System.out.println("Enter a double: ");
double aDouble = scanner.nextDouble();
System.out.println("double = " + aDouble);
//reads the float value, long value, boolean value, byte and short
double aFloat = scanner.nextFloat();
long aLong = scanner.nextLong();
boolean aBoolean = scanner.nextBoolean();
byte aByte = scanner.nextByte();
short aShort = scanner.nextShort();
scanner.close();
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.println("Welcome to the best program in the world! ");
while (true) {
System.out.print("Enter a query: ");
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
if (s.equals("q")) {
System.out.println("The program is ending now ....");
break;
} else {
System.out.println("The program is running...");
}
}
}
}
This is a simple code that uses the System.in.read() function. This code just writes out whatever was typed. You can get rid of the while loop if you just want to take input once, and you could store answers in a character array if you so choose.
package main;
import java.io.IOException;
public class Root
{
public static void main(String[] args)
{
new Root();
}
public Root()
{
while(true)
{
try
{
for(int y = 0; y < System.in.available(); ++y)
{
System.out.print((char)System.in.read());
}
}
catch(IOException ex)
{
ex.printStackTrace(System.out);
break;
}
}
}
}
I like the following:
public String readLine(String tPromptString) {
byte[] tBuffer = new byte[256];
int tPos = 0;
System.out.print(tPromptString);
while(true) {
byte tNextByte = readByte();
if(tNextByte == 10) {
return new String(tBuffer, 0, tPos);
}
if(tNextByte != 13) {
tBuffer[tPos] = tNextByte;
++tPos;
}
}
}
and for example, I would do:
String name = this.readLine("What is your name?")
Keyboard entry using Scanner is possible, as others have posted. But in these highly graphic times it is pointless making a calculator without a graphical user interface (GUI).
In modern Java this means using a JavaFX drag-and-drop tool like Scene Builder to lay out a GUI that resembles a calculator's console.
Note that using Scene Builder is intuitively easy and demands no additional Java skill for its event handlers that what you already may have.
For user input, you should have a wide TextField at the top of the GUI console.
This is where the user enters the numbers that they want to perform functions on.
Below the TextField, you would have an array of function buttons doing basic (i.e. add/subtract/multiply/divide and memory/recall/clear) functions.
Once the GUI is lain out, you can then add the 'controller' references that link each button function to its Java implementation, e.g a call to method in your project's controller class.
This video is a bit old but still shows how easy Scene Builder is to use.
The most simple way to get user input would be to use Scanner. Here's an example of how it's supposed to be used:
import java.util.Scanner;
public class main {
public static void main(String[]args) {
Scanner sc=new Scanner(System.in);
int a;
String b;
System.out.println("Type an integer here: ");
a=sc.nextInt();
System.out.println("Type anything here:");
b=sc.nextLine();
The line of code import java.util.Scanner; tells the program that the programmer will be using user inputs in their code. Like it says, it imports the scanner utility. Scanner sc=new Scanner(System.in); tells the program to start the user inputs. After you do that, you must make a string or integer without a value, then put those in the line a=sc.nextInt(); or a=sc.nextLine();. This gives the variables the value of the user inputs. Then you can use it in your code. Hope this helps.
Using JOptionPane you can achieve it.
Int a =JOptionPane.showInputDialog(null,"Enter number:");
import java.util.Scanner;
public class userinput {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Name : ");
String name = input.next();
System.out.print("Last Name : ");
String lname = input.next();
System.out.print("Age : ");
byte age = input.nextByte();
System.out.println(" " );
System.out.println(" " );
System.out.println("Firt Name: " + name);
System.out.println("Last Name: " + lname);
System.out.println(" Age: " + age);
}
}
class ex1 {
public static void main(String args[]){
int a, b, c;
a = Integer.parseInt(args[0]);
b = Integer.parseInt(args[1]);
c = a + b;
System.out.println("c = " + c);
}
}
// Output
javac ex1.java
java ex1 10 20
c = 30

Beginner Java program

I'm a beginner with Java and I have the following code:
public class test
{
public static void main(String[] args)
{
int a ;
String b;
Scanner input = new Scanner(System.in);
try {
System.out.println("Enter a: ");
a = input.nextInt();
} catch(Exception e )
{
System.out.println("That is not a number!");
}
System.out.println("Enter your name: ");
b = input.next();
System.out.println("Hello " + b);
}
}
when I give a string instead of int the code performs further and I receive this result:
"Enter a:
fsd
That is not a number!
Enter your name:
Hello fsd"
How can I make an interruption after the catch? (I have already try with a new Scanner after catch, but I think there are also another ways)
Thanks in advance!
LE: I have managed to do that with the "input.next();". I actually wanted to tip in another value for the string b, but the program takes automatically the int a instead of a new value and prints "Hello vsd", although vsd was the input for a.
As stated by the documentation, the Scanner will not advance to the next token if the current token does not match an integer's format. Therefore, if an exception is not thrown, the token in not consumed, and you just get it the next time you call a nextXYZ method.
Scans the next token of the input as an int. This method will throw InputMismatchException if the next token cannot be translated into a valid int value as described below. If the translation is successful, the scanner advances past the input that matched.
Instead of throwing and catching the exception (which is a heavy operation), you could use hasNextInt() to check it in advance:
int a ;
String b;
Scanner input = new Scanner(System.in);
System.out.println("Enter a: ");
if (input.hasNextInt()) {
a = input.nextInt();
} else {
System.out.println("That is not a number!");
// Skip the token so you won't get it later:
input.nextLine();
}
System.out.println("Enter your name: ");
b = input.next();
System.out.println("Hello " + b);
Try this
public class Test{
public static void main(String[] args){
int a ;
String b;
Scanner input = new Scanner(System.in);
try {
System.out.println("Enter a: ");
a = input.nextInt();
System.out.println("Enter your name: ");
b = input.next();
System.out.println("Hello " + b);
}
catch(Exception e ){
System.out.println("That is not a number!");
}
}
}
Just modify your catch block as follow:
catch(Exception e )
{
System.out.println("That is not a number!");
System.exit(0);
}
You should try to use the following block
input.hasNextInt()
instead as it doesn't require you to use a catch or throw exception, but rather if and else statements.
Your code still carries on because the catch block simply catches the exception and replaces it with a System.out.println that prints "That is not a number!"
} catch(Exception e )
{
System.out.println("That is not a number!");
}
Upon doing so the code continues to
System.out.println("Enter your name: ");
b = input.next();
System.out.println("Hello " + b);

Why is my try and catch stuck in a loop?

I want the user to enter integers into an array. I have this loop I wrote which has a try and catch in it, in case a user inserts a non integer. There's a boolean variable which keeps the loop going if is true. This way the user will be prompted and prompted again.
Except, when I run it, it gets stuck in a loop where it repeats "Please enter # " and "An Integer is required" without letting the user input a new number. I reset that number if an exception is caught. I don't understand.
import java.util.*;
public class herp
{
//The main accesses the methods and uses them.
public static void main (String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Hello and welcome!\n");
System.out.print("This program stores values into an array"+" and prints them.\n");
System.out.println("Please enter how many numbers would like to store:\n");
int arraysize = scan.nextInt();
int[] mainarray = new int[arraysize+1];
int checkint = 0;
boolean notint = true;
int prompt = 1;
while (prompt < mainarray.length)
{
// Not into will turn true and keep the loop going if the user puts in a
// non integer. But why is it not asking the user to put it a new checkint?
while(notint)
{
try
{
notint = false;
System.out.println("Please enter #"+ prompt);
checkint = scan.nextInt();
}
catch(Exception ex)
{
System.out.println("An integer is required." +
"\n Input an integer please");
notint = true;
checkint = 1;
//See, here it returns true and checkint is reset.
}
}
mainarray[prompt] = checkint;
System.out.println("Number has been added\n");
prompt++;
notint = true;
}
}
}
Once the scanner has thrown an InputMismatchException it cannot continue to be used. If your input is not reliable, instead of using scanner.nextInt() use scanner.next() to obtain a String then convert the string to an int.
Replace:
checkint = scan.nextInt();
With:
String s = scan.next();
checkint = Integer.parseInt(s);
I have corrected it like below. I don't rely on exception, but check if the next Scanner input is int (using hasNextInt()). If not int, just consume Scanner token and wait for the next user input.
Looks like it is working, apart from 0 being inserted as a first array element, because you started indexing prompt from 1.
public class Herp {
//The main accesses the methods and uses them.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Hello and welcome!\n");
System.out.print("This program stores values into an array" + " and prints them.\n");
System.out.println("Please enter how many numbers would like to store:\n");
int arraysize = scan.nextInt();
int[] mainarray = new int[arraysize + 1];
int checkint = 0;
boolean notint = true;
int prompt = 1;
while (prompt < mainarray.length) {
while (notint) {
notint = false;
System.out.println("Please enter #" + prompt);
// check if int waits for us in Scanner
if (scan.hasNextInt()) {
checkint = scan.nextInt();
} else {
// if not, consume Scanner token
scan.next();
System.out.println("An integer is required."
+ "\n Input an integer please");
notint = true;
}
}
mainarray[prompt] = checkint;
System.out.println("Number has been added\n");
prompt++;
notint = true;
}
for (int i : mainarray) {
System.out.print(i + " ");
}
}
}

Java scanner used in an if statement

I am new at Java and am currently trying to create a super super simple code just to test how to have a scanner input compared in an if statement to another number and then print out a response depending on the if. This is what I have and I'm getting an error on the if line and I'm getting this error:
The operator > is undefined for the argument type(s) String, int.
Any help would be great because once I figure this out I'm going to try to do some other things with it. Thanks!
import java.util.Scanner;
class damagecalc {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
System.out.println("How much damage did you do?");
String damage = input.nextLine();
if(damage > 50){
System.out.println("You have died!");
}else{
System.out.println("Your damage amount is:" + input);
}
}
}
You have
String damage = input.nextLine();
You want
int damage = input.nextInt();
And this
System.out.println("Your damage amount is:" + input);
Should be
System.out.println("Your damage amount is:" + damage);
You can't compare Strings using > operator. In Java you cannot define your own operator behaviour.
Instead of
String damage = input.nextLine();
use
Integer damage = input.nextInt();
If you're looking for a more robust solution, perhaps you could try something like:
public static int readInt(final String prompt){
final Scanner reader = new Scanner(System.in);
while(true){
System.out.println(prompt);
try{
return Integer.parseInt(reader.nextLine());
}catch(Exception ex){
System.err.println("Enter a valid integer: " + ex);
}
}
}
I'd probably suggest declaring your Scanner as a static class field if you plan on reading multiple user input (which presumably you do). You could invoke it like:
final int damage = readInt("How much damage did you do?");
System.out.println(damage > 50 ? "You have died!" : ("Your damage amount is: " + damage));
You cannot compare string with integer. Just parse it.
try {
if (Integer.parseInt(damage) > 50) {i
System.out.println("You have died!");
} else {
System.out.println("Your damage amount is:" + input);
}
} catch (NumberFormatException e) {
e.printStackTrace();
System.out.println("You have entered a non integer number!");
}

Categories