Not getting user input as required in Java - java

I am new to java but not to programming as I know C++.
I am simply trying to get input from user either of integer or string form but when i execute my program, it just stands still and does nothing until I press enter.
My program and result after pressing "Enter" is given.
My question is "why I am not getting user input?"
import java.util.Scanner;
class roomarea
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int input = scanner.nextInt();
System.out.println("Enterd value is " + input);
}
}
the result is
Start Running math >Command: "C:\Program Files\Java\jdk1.6.0\bin\java.exe"
-classpath "C:\Documents and Settings\Ahmad Abdullah\My Documents\NaviCoder IDE for
Java\projects\math\output\classes";"C:\Program Files\Java\jdk1.6.0\jre\lib\rt.jar";
roomarea
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
roomarea.main(Main.java:14) >Run
Process Completed

When you say "it just stands still and does nothing untill i press enter", it is doing exactly what you told it to - it is waiting for you to input an int. You just hitting enter meant that there was no input, which your scanner could not interpret as an int, hence the exception.
If you enter an integer number then press the enter key, your program should work.

Your program should work if you enter an int as input. (By pressing Enter while "waiting" for the program, you could arise the exception you're talking about).
If you enter a char for example, you'll get InputMismatchException exception:
Thrown by a Scanner to indicate that the token retrieved does not
match the pattern for the expected type, or that the token is out of
range for the expected type.

Related

InputMismatchException with floating point numbers despite the input matching the expected data type

When I use the the .nextDouble() in the Scanner class, I get a InputMismatchException error, despite the input being a floating point number
This is a simple code to show the problem:
import java.util.Scanner;
public class BasicJava1
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter a number");
double n = input.nextDouble();
}
}
Output:
Enter a number
5.5
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextDouble(Scanner.java:2564)
at BasicJava1.main(BasicJava1.java:11)
This only happens with floating point numbers, when I enter an integer to this same code, it works
This only happens when I use a local Terminal or IDE, I tried it with an online compiler, and it worked fine
I use a mac

java: Scanner asks for an extra value when using useDelimiter

So I wanna create this program that stores 4 values. the first one being string and the remaining 3 being integers. However, when i enter 4 values and press enter, i get an error java.util.InputMismatchException but when I enter 5 values, i get the result for my for values. for example lets say i input the following values:
Japan,1,2,3
I will get the java.util.InputMismatchException error. And if I enter the following values:-
Japan,1,2,3,4
I get the output as I want:-
Japan,1,2,3
Why is this happening? Here is my code
public class satisfaction {
public static void main(String args[])
{
Scanner src= new Scanner(System.in);
src.useDelimiter("\\,|\\n");
String name=src.next();
int a=src.nextInt();
int b=src.nextInt();
int c=src.nextInt();
System.out.println(name+","+a+","+b+","+c);
}
}
I've tested this a bit myself, and I think the \n in the pattern is not matching the line ending used by your console.
For me, I had to use \r\n instead, but you could also use System.lineSeparator() e.g. like this:
src.useDelimiter(",|" + System.lineSeparator());
The way it's written, it needs another comma at the end of the input. I would recommend checking the string to make sure it ends in a comma, and if not, append one.
I believe that if you enter Japan,1,2,3, it will give you the output you want.

My file isn't opening in cmd

Hi I am totally new in Java and don't know much about it .I Have just made a program and not sure if it's correct.I want a input from user so that it will calculate the answer.Here's the code:
import java.util.Scanner;
class Vedant
{
public static void main(String[] args)
{
Scanner inputa=new Scanner(System.in);
int b=inputa.nextInt();
if(b<20);
int a=5;
{
System.out.println("Answer ="+a);
}
}
}
When I run this file in cmd it does nothing.It doesn't even ask for input.If I type random things and press enter it gives me this
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 Vedant.main(Vedant.java:8)
Please help.And yeah I am just a beginner
When I run this file in cmd it does nothing.
That's incorrect
It doesn't even ask for input
You didn't tell it to, the command you gave is inputa.nextInt() which only reads input, but doesn't output anything.
If I type random things and press enter it gives me this
inputa.nextInt() means "read the next input as a number". If you're typing random things it can't convert it to a number.
There are some more issues with your code:
if(b<20);
The semicolon at the end means that nothing is done if b actually is less than 20
int a=5;
{
System.out.println("Answer ="+a);
}
The parentheses are not needed here, and because you explicitly set the variable a to 5 your application, if it gets this far, will always say Answer =5
If you are wanting it to ask for a number. You have to tell it to ask for a number like so.
System.out.println("Enter a number.");
By what you typed in your code it seems like you are trying to add 'b' and 'a' for "Answer". If so, it will be easier for you to make a new variable that is adding 'a' and 'b'.
int answer = a + b;
System.out.printf("Answer = %d", answer);

User input and Exception in Java

I want to add an integer to a list based on user input. The user has to type all the integers he/she wishes then press enter. if they finish inputting integer, they are supposed to press the "enter" button without typing anything.
I have made my code, but there are several mistakes
the exception keeps popping up because every time say for example I enter integer 10, then I finish. I press "enter" with nothing. this raises the exception. how do I tackle this problem?
and another thing, how do I make the program so that if the user puts invalid input, instead of crashing or breaking. It asks the user again to prompt the correct input.
this is what I have done
package basic.functions;
import java.util.*;
import java.text.DecimalFormat;
public class Percent {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
reader.useDelimiter(System.getProperty("line.separator"));
List<Integer> list = new ArrayList<>();
System.out.println("Enter Integer: ");
while (true) {
try {
int n = reader.nextInt();
list.add(Integer.valueOf(n));
} catch (InputMismatchException exception) {
System.out.println("Not an integer, please try again");
break;
}
}
reader.close();
}
}
output
Enter Integer:
10
Not an integer, please try again
[10]
I'd suggest you utilise Scanner#hasNextInt to identify whether an integer has been entered or not. As for when the "user presses enter without typing anything", we can simply use the String#isEmpty method.
while (true) {
if(reader.hasNextInt()) list.add(reader.nextInt());
else if(reader.hasNext() && reader.next().isEmpty()) break;
else System.out.println("please enter an integer value");
}
note - in this case, you don't need to catch InputMismatchException because it won't be thrown.
while (true) is generally a bad sign, if you ever have that in your code you are almost certainly wrong.
What you probably want is something like this:
String input;
do {
input = reader.next();
// Parse the input to an integer using Integer.valueOf()
// Add it to the list if it succeeds
// You will need your try/catch etc here
while (!input.isEmpty());
Here the loop is checking the exit condition and running until it meets it. Your processing is still done inside the loop as normal but the program flow is a lot cleaner.

How to stop reading multiple lines from stdin using Scanner?

I'm working on an JAVA assignment should process multiple lines of input. The instructions read "Input is read from stdin."
An example of sample input is given:
one 1
two 2
three 3
I don't understand what the above sample input "read from stdin" means.
Here's a test program I wrote that isolates my confusion:
import java.io.*;
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner stdin = new Scanner(System.in);
while(stdin.hasNextLine())
{
String line = stdin.nextLine();
String[] tokens = line.split(" ");
System.out.println(Integer.parseInt(tokens[1]));
}
}
When I run this program in the console, it waits for my input and each time I input a line it echos it back as I would expect. So I thought perhaps the sample input above would be achieved by entering each of the 3 lines in this fashion. However, there seems to be no way to end the process. After I enter the 3 lines, how do I terminate the input? I tried just pressing enter twice, but that seems to read as a line consisting of only the newline character, which causes an error because the line doesn't fit the 2 token format it expects.
Here's what the console interaction looks like:
javac Test.java
java Test
one 1
1
two 2
2
three 3
3
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at Test.main(Test.java:13)
I'd appreciate any help in pointing out the gap in my understanding.
You could try asking for empty inputs
import java.util.Scanner;
public class Test
{
public static void main(String[] args)
{
String line;
Scanner stdin = new Scanner(System.in);
while(stdin.hasNextLine() && !( line = stdin.nextLine() ).equals( "" ))
{
String[] tokens = line.split(" ");
System.out.println(Integer.parseInt(tokens[1]));
}
stdin.close();
}
}
Your code is almost completed. All that you have to do is to exit the while loop. In this code sample I added a condition to it that first sets the read input value to line and secondly checks the returned String if it is empty; if so the second condition of the while loop returns false and let it stop.
The array index out of bounds exception you will only get when you're not entering a minimum of two values, delimitted by whitespace. If you wouldn't try to get the second value >token[1]< by a static index you could avoid this error.
When you're using readers, keep in mind to close after using them.
Last but not least - have you tried the usual Ctrl+C hotkey to terminate processes in consoles?
Good luck!
You could also put your values in a file e.g. input.txt and do:
java Test < input.txt
From the shell, hit Ctrl-D and it will close stdin. Alternatively, pipe input in
cat your-input-file | java Test
To stop the input, you could either prompt the user to enter quit to exit, and then test for the presence of that String in the input, exiting the loop when found, or you could use a counter in the loop, exiting the loop when the maximum iterations have been reached. The break statement will get you out of the loop.

Categories