How to take input using Scanner in java? - java

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.

Related

Unable to Pass input to multiple methods in a Java program using command line arguments

I'm passing the input to the java program using the below command:
java Main - <"input.txt" > "output.txt"
by using this method the inputs are only received by first method (main)
Code:
import java.util.Scanner;
import java.util.Arrays;
class Main {
public static int read() {
Scanner input = new Scanner(System.in);
int num2 = input.nextInt();
System.out.println(num2);
return num2;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num1 = input.nextInt();
System.out.println(num1);
read();
}
}
Input input.txt contents:
1
2
Expected Output:
1
2
Actual Output
1
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.read(main.java:7)
at Main.main(main.java:16)
This can be fixed by reusing a single instance of Scanner, rather than creating a new instance in the read method:
import java.util.Scanner;
import java.util.Arrays;
class Main {
public static int read(Scanner input) {
int num2 = input.nextInt();
System.out.println(num2);
return num2;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num1 = input.nextInt();
System.out.println(num1);
read(input);
}
}
This produces the expected output, and does not throw an exception.

Input a number until -1

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!");
}
}

Make user only input integer in scanner Java

i have some problems here.
I want to user only can input as an integer. I have tried by many code, but still doesn't work. Btw, this is my code
import java.util.Scanner;
public class test {
public static void main (String []args){
Scanner scan = new Scanner(System.in);
int number = scan.nextInt();
}
}
When error, the message will shown as
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at test.main(test.java:6)
Please help me (Beginner Programmer);
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while (!scan.hasNextInt()) {
System.out.println("Input is not a number.");
scan.nextLine();
}
int number = scan.nextInt();
}
This code will check if the input is an Integer, if it is then it will continue.
Try this:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (true) {
System.out.print("Enter a number -> ");
String input = sc.next();
int intInputValue = 0;
try {
intInputValue = Integer.parseInt(input);
break;
} catch (NumberFormatException ne) {
System.out.println("This is not a number");
}
}
}
This program will end when the user enter a integer input value.
Output
Such an error only occurs if the user did not enter an integer.For such a situation, you could create a try-catch block, that catches the exception, like this:
String input = sc.next();
int number = 0;
try {
number = Integer.valueOf(input);
} catch (NumberFormatException ne) {
System.out.println("Invalid input!");
}
To optimize the solution even more, put this all in a loop, and break out of it in the try-block, and keep polling for input if the user enters a bad number.

java Scanner force user to input a int value

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

Input compilation error Java

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.

Categories