So far I have this:
public double checkValueWithin(int min, int max) {
double num;
Scanner reader = new Scanner(System.in);
num = reader.nextDouble();
while (num < min || num > max) {
System.out.print("Invalid. Re-enter number: ");
num = reader.nextDouble();
}
return num;
}
and this:
public void askForMarks() {
double marks[] = new double[student];
int index = 0;
Scanner reader = new Scanner(System.in);
while (index < student) {
System.out.print("Please enter a mark (0..30): ");
marks[index] = (double) checkValueWithin(0, 30);
index++;
}
}
When I test this, it can't take double number and I got this message:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextDouble(Scanner.java:2456)
at MarkingSystem.checkValueWithin(MarkingSystem.java:25)
at MarkingSystem.askForMarks(MarkingSystem.java:44)
at World.main(World.java:6)
Java Result: 1
How do I fix this?
Instead of using a dot, like: 1.2, try to input like this: 1,2.
Here you can see the nature of Scanner:
double nextDouble()
Returns the next token as a double. If the next token is not a float or
is out of range, InputMismatchException is thrown.
Try to catch the exception
try {
// ...
} catch (InputMismatchException e) {
System.out.print(e.getMessage()); //try to find out specific reason.
}
UPDATE
CASE 1
I tried your code and there is nothing wrong with it. Your are getting that error because you must have entered String value. When I entered a numeric value, it runs without any errors. But once I entered String it throw the same Exception which you have mentioned in your question.
CASE 2
You have entered something, which is out of range as I have mentioned above.
I'm really wondering what you could have tried to enter. In my system, it is running perfectly without changing a single line of code. Just copy as it is and try to compile and run it.
import java.util.*;
public class Test {
public static void main(String... args) {
new Test().askForMarks(5);
}
public void askForMarks(int student) {
double marks[] = new double[student];
int index = 0;
Scanner reader = new Scanner(System.in);
while (index < student) {
System.out.print("Please enter a mark (0..30): ");
marks[index] = (double) checkValueWithin(0, 30);
index++;
}
}
public double checkValueWithin(int min, int max) {
double num;
Scanner reader = new Scanner(System.in);
num = reader.nextDouble();
while (num < min || num > max) {
System.out.print("Invalid. Re-enter number: ");
num = reader.nextDouble();
}
return num;
}
}
As you said, you have tried to enter 1.0, 2.8 and etc. Please try with this code.
Note : Please enter number one by one, on separate lines. I mean, enter 2.7, press enter and then enter second number (e.g. 6.7).
I encountered the same problem.
Strange, but the reason was that the object Scanner interprets fractions depending on localization of system.
If the current localization uses a comma to separate parts of the fractions, the fraction with the dot will turn into type String.
Hence the error ...
Since you have the manual user input loop, after the scanner has read your first input it will pass the carriage/return into the next line which will also be read; of course, that is not what you wanted.
You can try this
try {
// ...
} catch (InputMismatchException e) {
reader.next();
}
or alternatively, you can consume that carriage return before reading your next double input by calling
reader.next()
Are you providing write input to the console ?
Scanner reader = new Scanner(System.in);
num = reader.nextDouble();
This is return double if you just enter number like 456.
In case you enter a string or character instead,it will throw java.util.InputMismatchException when it tries to do num = reader.nextDouble() .
Related
import java.util.Scanner;
import java.io.*;
public class Positive {
public static void main (String args[]) {
double first;
Scanner scan = new Scanner(System.in);
System.out.print("Please enter first value" + "\n");
first= scan.nextDouble();
if (first>0.00) {
System.out.println("Please enter second value");
}
else if (first <0.00) {
first =-first;
System.out.println(first);
System.out.println("Please enter second value");
}
double second;
Scanner scaning = new Scanner(System.in);
second = scan.nextDouble();
if (first>second) {
System.out.println(first-second);
}
else if (second>first) {
System.out.println(second-first);
}
}
}
Task:
If the value is positive, request a second value. Print the difference between these two numbers so that the difference is always positive. For instance, if the first value is 10.3 and the second is 4.1, you would print the result of 6.2. If the first value is 3.8 and the second is 13.4 you would print the result 9.6.
If the first value read is negative, print its positive equivalent. For instance, if its value is –89.6 you should print 89.6.
If the first value is not a number, give appropriate error message (The standard error message from Java (e.g. “Exception in thread "main” ...”) does not count! Have a look at the Java API or Stack Overflow how to approach this).
The rest of the code runs correctly but I don't know how to only include double values in the input
By using Scanner::nextDouble you are forcing the input to only be doubles, but if you were to use Scanner::nextLine then you could then try to convert to a double and if that fails then print the message
Scanner scan = new Scanner(System.in);
System.out.println("Enter double");
String line = scan.nextLine();
double firstNum = 0.00;
try {
firstNum = Double.parseDouble(line);
}
catch (NumberFormatException e) {
System.err.println("Not a double");
}
Also, rather than doing
if (first>second) {
System.out.println(first-second);
}
else if (second>first) {
System.out.println(second-first);
}
it would be easier to do
System.out.println (Math.abs(first - second));
and also you should remove this line as it is not necessary and you are not even using it
Scanner scaning = new Scanner(System.in);
I am a noob in programming.
I wanted to write code for a prog which asks user to enter value until an integer is entered.
public class JavaApplication34 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int flag = 0;
while(flag == 0) {
int x = 0;
System.out.println("Enter an integer");
try {
x = sc.nextInt();
flag = 1;
} catch(Exception e) {
System.out.println("error");
}
System.out.println("Value "+ x);
}
}
}
I think the code is correct and it should ask me to enter the value again if i have entered anything other than an integer.
But when i run it , and say i enter xyz
it iterates infinite time without asking me to enter the value.
test run :
Enter an integer
xyz
error
Value 0
Enter an integer
error
Value 0
Enter an integer
error
Value 0
Enter an integer
error
Value 0
Enter an integer
error
Value 0
Enter an integer
error
Value 0
Enter an integer
error
Value 0
Enter an integer
error
Value 0
Enter an integer
error
Value 0
When a scanner throws an InputMismatchException, the scanner will not
pass the token that caused the exception.
Hence sc.nextInt() reads the same token again and throws the same exception again.
...
...
...
catch(Exception e){
System.out.println("error");
sc.next(); // <---- insert this to consume the invalid token
}
You can change your logic as shown below :
int flag = 0;
int x = 0;
String str="";
while (flag == 0) {
System.out.println("Enter an integer");
try {
str = sc.next();
x = Integer.parseInt(str);
flag = 1;
} catch (Exception e) {
System.out.println("Value " + str);
}
}
Here we have first read the input from Scanner and then we are trying to parse it as int, if the input is not an integer value then it will throw exception. In case of exception we are printing what user has enter. When user enters an integer then it will parsed successfully and value of flag will update to 1 and it will cause loop to exit.
In the error case, you need to clear out the string you've entered (for instance, via nextLine). Since it couldn't be returned by nextInt, it's still pending in the scanner. You also want to move your line outputting the value into the try, since you don't want to do it when you have an error.
Something along these lines:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int flag = 0;
while(flag == 0)
{
int x = 0;
System.out.println("Enter an integer");
try
{
x = sc.nextInt();
flag = 1;
System.out.println("Value "+ x);
}
catch (Exception e){
System.out.println("error");
if (sc.hasNextLine()) { // Probably unnecessary
sc.nextLine();
}
}
}
}
Side note: Java has boolean, there's no need to use int for flags. So:
boolean flag = false;
and
while (!flag) {
and
flag = true; // When you get a value
The answers to this question might help you
It makes use of Scanners .hasNextInt() function!
I wrote a short piece of code with the purpose of setting an integer value. However, it does not seem to return the correct value. For example, for the following inputs I would expect it to work like so.
Please enter a positive integer value
-458
Please enter a positive valid integer
58
58
However, the actual output is the following.
Please enter a positive integer value
-458
Please enter a positive valid integer
58
-458
In this example why does it return -458 instead of 58?
import java.util.InputMismatchException;
import java.util.Scanner;
public class IncorectValueReturned {
public void run() {
System.out.println("Please enter a positive integer value");
System.out.println(setInt());
}
private int setInt() {
int i = -1;
Scanner sc = new Scanner(System.in);
try {
i = sc.nextInt();
if(i < 0) {
System.out.println("Please enter a positive valid integer");
setInt();
}
} catch(InputMismatchException iME) {
System.out.println("Please enter a positive valid integer");
setInt();
}
sc.close();
return i;
}
public static void main(String[] args) {
IncorectValueReturned iVR = new IncorectValueReturned();
iVR.run();
}
}
You never change the first i that was invalid, you need to recover the value of the recursive calls
i = setInt();
And of course, you should not redeclare this Scanner over and over.
Use a Instance variable instead.
Scanner sc = new Scanner(System.in);
private int setInt() {
int i = -1;
try {
i = sc.nextInt();
if(i < 0) {
System.out.println("Please enter a positive valid integer");
i = setInt();
}
} catch(InputMismatchException iME) {
//Clear the scanner of this value
sc.next();
System.out.println("Please enter a positive valid integer");
i = setInt();
}
return i;
}
And close the scanner when you are done with it.
Careful, a value that throws an exception will remain in the input, you need to read it, I used Scanner.next() to remove a bad input like a a value bigger than Integer.MAX_VALUE.
You didn't assign i the new value from SetInt().
if(i < 0) {
System.out.println("Please enter a positive valid integer");
i = setInt(); // <- HERE
}
When using scanner is there a way to check that the user input is what we expect?
Say I want a double but the user enters a String what can I do to prompt the user to re-enter the value as a double?
With the following code if a number is not entered I get a mismatchException. I don't want the program to crash if the input is wrong.
Here is my code:
import java.util.Scanner;
public class RoundingNumbers {
private double y;
private double x;
public RoundingNumbers(){
double y = 0;
double x = 0;
}
public void getNumber(){
System.out.print("Enter a decimal number: ");
Scanner num = new Scanner(System.in);
x = num.nextDouble();
}
public void roundNum(){
y = Math.floor(x + 0.5);
}
public void displayNums(){
System.out.println("The actual number is: " + x);
System.out.println("The rounded number is: " + y);
}
}
You can wrap it in a try catch block. See the below example function.
Whoops. I wasn't paying close enough attention and didn't see your code example.
Change your getNumber() function to the below definition. Note that there are many different ways to do this. This is just an example.
public void getNumber(){
Scanner num = new Scanner(System.in);
while(true) {
System.out.print("Enter a decimal number: ");
try {
x = num.nextDouble();
break;
catch(InputMismatchException e) {}
}
}
You already noticed that you recieve a InputMismatchException if they don't type what you expect. With this in mind, you can surround the x = num.nextDouble() with a try-catch block and check for that kind of Exception. For example:
while (true) {
try {
x = num.nextDouble();
// move along if no exception is thrown
break;
} catch (InputMismatchException e) {
// give the user an error message
System.out.println("Type mismatch when reading your input. Please insert a double: ");
}
}
By the way, this is not directly related to your question, but you shouldn't name your Scanner variable as num, because that name doesn't make anyone think of a Scanner - people in general would think it's an int or something. It's a good programming practice to give your variables names that fits them.
I am attempting to make sure the user input int type only and make sure the integer inputted is greater than 0.
I was able to come up with the following to make sure the input is int type:
Scanner scan = new Scanner(System.in);
while(!scanner.hasNextInt())
{
scanner.next();
}
int input = scan.nextInt();
But how should I include a condition checking to make sure the integer is greater than 0 as well?
The problem with your current approach is you've already ready the value from the Scanner before it reaches int input = scan.nextInt();, meaning that by the time you use nextInt, there's nothing in the Scanner to be read and it will wait for the next input from user...
Instead, you could read the String from the Scanner using next, use Integer.parseInt to try and parse the result to an int and then check the result, for example...
Scanner scanner = new Scanner(System.in);
int intValue = -1;
do {
System.out.print("Please enter a integer value greater than 0: ");
String next = scanner.next();
try {
intValue = Integer.parseInt(next);
} catch (NumberFormatException exp) {
}
} while (intValue < 0);
System.out.println("You input " + intValue);
put an if statement inside your while loop like this
if(num <= 0){
System.out.println("Enter a number greater than zero");
}
else{
break;
}
You may use a condition in your code but not in the loop as.
`
Scanner scan = new Scanner(System.in);
abc:
while(!scanner.hasNextInt())
{
scanner.next();
}
int input = scan.nextInt();
if(input <= 0){
goto abc;
}
`
using .isDigit() method then checking to see if that number is greater than 0 if it is a digit