I need int num to only accept numbers. If I input letters I get an error. Is there a way to immediately flag letters, or do I have to take num in as a string and run loops?
import java.util.Scanner;
public class Test
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Input a number.");
int num = input.nextInt();
}
}
You must use Scanner.hasNextInt():
It 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.
public static void main(String[] args)
{
System.out.println("Input a number.");
Scanner sc = new Scanner(System.in);
System.out.print("Enter number 1: ");
while (!sc.hasNextInt()) sc.next();
int num = sc.nextInt();
System.out.println(num);
}
You probably want to do something like this:
import java.util.InputMismatchException
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Input an integer.");
int num = 0; // or any other default value
try {
num = input.nextInt();
} catch (InputMismatchException e) {
System.out.println("You should've entered an integer like I told you. Fool.");
} finally {
input.close();
}
}
}
If the user enters something that is not an integer, the code within the catch block will be executed.
Related
I have written a JAVA program that takes input from the user and check if the user has entered the correct thing or not. I have taken the input from the Scanner class. If the user enters an invalid character like a String, I want to display 'Invalid Input'.
public class Main {
public static void main(String[] args) {
Scanner takeInteger = new Scanner(System.in);
System.out.println("Enter a number");
int enteredNumber = takeInteger.nextInt();
}
}
Just ask the Scanner whether the next input is a valid int value, e.g.
Scanner takeInteger = new Scanner(System.in);
System.out.println("Enter a number");
while(!takeInteger.hasNextInt()) {
System.out.println("Invalid Input: " + takeInteger.next());
}
int enteredNumber = takeInteger.nextInt();
This will retry the operation until the user entered a number. If you just want a single attempt, use something like
Scanner takeInteger = new Scanner(System.in);
System.out.println("Enter a number");
if(!takeInteger.hasNextInt()) {
System.out.println("Invalid Input: " + takeInteger.next());
}
else {
int enteredNumber = takeInteger.nextInt();
// ... proceed with the input
}
You will get an Exception that is InputMismatchException when an invalid input is passed.(i.e except integer value),you can use a try-catch block to hold the exception and inform the user about the invalid input. Try block , Catch block
import java.util.*;
Scanner takeInteger = new Scanner(System.in);
System.out.println("Enter a number");
try{
int enteredNumber = takeInteger.nextInt();
}
catch(InputMismatchException e) {
System.out.println("Enter a valid input");
}
You can use Exception handling for the same.
public class Main {
public static void main(String[] args) {
Scanner takeInteger = new Scanner(System.in);
System.out.println("Enter a number");
try {
int enteredNumber = takeInteger.nextInt();
}
catch (Exception e) {
System.out.println("Invalid Input");
}
}
}
You can add a try-catch block in your program to check if the user's input is a number or not.
Scanner takeInteger = new Scanner(System.in);
System.out.println("Enter a number");
String input = takeInteger.next();
int enteredNumber;
try
{
enteredNumber = Integer.parseInt(input); // Input is a number
}
catch(NumberFormatException ex)
{
System.out.println("Wrong Input!"); // Invalid input
}
You need to call the .nextLine method of the Scanner class and then parse to the desired type.
Example:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number");
String line = sc.nextLine();
try {
int enteredNumber = Integer.parseInt(line);
System.out.println("You have entered: " + enteredNumber);
} catch (Exception e) {
System.out.println("Invalid Input");
}
}
}
Result with a number:
Enter a number
12
You have entered: 12
Result a text:
Enter a number
abcd
Invalid Input
I am taking input using java Scanner by writing following code:
import java.util.Scanner;
class main{
public static void main(String args[]){
Scanner scan=new Scanner(System.in);
System.out.println("Enter number");
int i=scan.nextInt();
}
}
but above code in throwing following exception:
Enter number
Exception in thread "main" java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:937)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at main.main(main.java:7)
Tool completed with exit code 1
import java.util.Scanner;
class Input {
public static void main(String[] args) {
Scanner input = new Scanner(System.in); System.out.print("Enter an integer: ");
int number = input.nextInt();
System.out.println("You entered " + number);
}
}
Try this code.....
Here, input object of Scanner class is created. Then, the nextInt() method of the Scanner class is used to get integer input from the user.
To get long, float, double and Stringinput from the user, you can use nextLong(), nextFloat(), nextDouble() and next() methods respectively.
You are almost there. One note is you expect int value and if user enter e.g. string, then you get an exception.
public static int askIntNumber(Scanner scan) {
while(true) {
try {
System.out.print("Enter number: ");
return scan.nextInt();
} catch (Exception e) {
System.err.println("This is not an integer number");
}
}
You should try this:
import java.util.Scanner;
public class main {
public static void main(String[]args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter number: ");
int i=sc.nextInt();
}
}
The block of code sc.nextInt scans the entire input and then puts it into play. This should solve your problem.
Create a program that asks the user to input numbers (integers). The program prints "Type numbers” until the user types the number -1. When the user types the number -1, the program prints "Thank you and see you later!" and ends.
This is the code:
import java.util.Scanner;
public class TheSumOfSetOfNumbers {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int number=0, sum=0, count=0, even=0, odd=0;
double average=0;
System.out.println("Type numbers: ");
while(true)
{
number=Integer.parseInt(reader.nextLine());
if(number==(-1)) break;
}
}
When I check it, this is the error :
remember to read user input with Integer.parseInt( reader.nextLine() );
call it only once!
If I only call it once, how it will be possible to scan a lot numbers?
This is what you will use in this scenario. Using a do while loop, you can get your output
public static void main(String args[]){
Scanner scan = new Scanner(System.in);
int num = 0;
do {
System.out.println("Enter Numbers");
num = scan.nextInt();
} while (num != -1);
System.out.println("Thanks ! See you later");
}
Note: This runs until the user enters -1:
while (reader.hasNextLine()) {
number = Integer.parseInt(reader.nextLine());
if (number == -1) {
System.out.println("Thank you and see you later!");
break;
}
}
If you are always typing numbers I will use this:
final Scanner scanner = new Scanner(System.in);
boolean exit = false;
System.out.println("Type numbers:");
while (!exit){
if (scanner.nextInt() != -1)
exit = true;
}
System.out.println("Thank you and see you later!");
But you have to call scanner object each time you would like to read something from the imput.
You need to put System.out.println("Type numbers: "); inside while loop.
Since you are giving only integers as input, no need to parse it.
Below is required code:
import java.util.Scanner;
public class TheSumOfSetOfNumbers {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int number=0, sum=0, count=0, even=0, odd=0;
double average=0;
// we need to loop "Type numbers:" each time umtil "-1" is pressed
while(number != -1)
{
System.out.println("Type numbers: ");
number=reader.nextInt();
}
// user must have been typed "-1" therefore it exits from whle loop
System.out.println("Thank you and see you later!");
// now there is nothing in main() fxn, therefore, the program will stop
}
}
Output:
Type numbers:
1
Type numbers:
3
Type numbers:
8
Type numbers:
9
Type numbers:
0
Type numbers:
-1
Thank you and see you later!
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num = -1;
do {
System.out.println("Welcome to Java Programming!");
System.out.println("Print Again? (y/n)");
num = input.nextLine();
} while (num.equalsIgnoreCase(-1));
}
}
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
int flag=0,n;
while(flag!=1){
n=sc.nextInt();
if(n==-1){
flag=1;
}
}
System.out.print("Thank you and see you later!");
}
}
public class Main{
public static void main(String args[]){
int i = nextInt();
}
public int nextInt(){
int i=0;
boolean done=false;
Scanner scanner = new Scanner(System.in);
while (!scanner.hasNextInt()){
scanner.nextLine();
Printer.println(Printer.PLEASE_NUMBER);
}
i=scanner.nextInt();
scanner.close();
return i;
}
}
The code above is how I'm trying to force a user to input a int value, but I get the nosuchelement exception, as the scanner.nextLine() reads a NULL.
In c++ the software waits for the user to input something. Is there anything I can do to force the program to stop, wait for the user to input something and then make the check?
EDIT:
So I'm having problems regardless, if I use scanner outside of Main class, it gives that error...
If you want the user to input and the scanner to pick up solely an integer value Scanner provides the method:
int i = scanner.nextInt();
Where i will store the next value entered into the console. It will throw an exception if i is not an integer.
Here is an example: Let's say I want the user to input a number and then I want to spit it back out to the user. Here would be my main method:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Please print your number: ");
int i = sc.nextInt();
System.out.println("Your Number is: " + i);
}
Now to check whether i is a integer you can use an if statement. However if you want the program to repeat until the user inputs an integer you can use a while loop or a do while loop where the loop's arguments would check if i is an integer.
Hope this is what you were looking for! By the way avoid naming your method nextInt() as the import java.util.Scanner; already has that method name. Don't forget imports as well!
You can do this:
public static void main(String[] args) {
System.out.println("" + nextInt());
}
public static int nextInt(){
int i=0;
boolean done=false;
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter a number:");
while (!scanner.hasNextInt()){
System.out.println("Please enter a number:");
scanner.nextLine();
}
i = scanner.nextInt();
scanner.close();
return i;
}
This will cause the program to stop and wait for input each time the loop is executed. It will keep looping until it has an int in the scanner.
This works. There surely is a better solution.
EDIT As predicted. Check this,
import java.util.Scanner;
public class NewMain{
static boolean badNumber;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
do{
System.out.print("Please print your number: ");
try{
int i = sc.nextInt();
System.out.println("Your Number is: " + i);
badNumber = false;
}
catch(Exception e){
System.out.println("Bad number");
sc.next();
badNumber = true;
}
}while(badNumber);
}
}
package exercises;
import java.util.*;
public class Try_and_catch {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int x=1;
do
{
System.out.println("Enter first number");
int n1 = input.nextInt();
System.out.println("Enter second number");
int n2 = input.nextInt();
int sum= n1/n2;
System.out.println(sum);
} while(x==1);
}
}
The code above requires input only integers, my question is how to handle the error whenever the user input a character?
Use a try block:
boolean again = true;
int n1;
while (again) {
try {
System.out.println("Enter first number");
input.nextInt();
again=false;
}
catch(InputMismatchException ime)
{
// do nothing!
}
}
What happens here is pretty simple: if we get an exception, then "again" is not set to true and we go back around in the loop. If we get out of the try block without an exception, then again is toggled and we go merrily on our way.