Only allow double inputs with java scanner - java

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

Related

Java Sum of numbers until string is entered

i've just started java programming and was wondering on how to approach or solve this problem i'm faced with.
I have to write a program that asks a user for a number and continually sums the numbers inputted and print the result.
This program stops when the user enters "END"
I just can't seem to think of a solution to this problem, any help or guidance throughout this problem would be much appreciated and would really help me understand problems like this. This is the best i could do
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while (true) {
System.out.print("Enter a number: ");
int x = scan.nextInt();
System.out.print("Enter a number: ");
int y = scan.nextInt();
int sum = x + y;
System.out.println("Sum is now: " + sum);
}
}
}
The output is supposed to look like this:
Enter a number: 5
Sum is now: 5
Enter a number: 10
Sum is now: 15
Enter a number: END
One solution would be to not use the Scanner#nextInt() method at all but instead utilize the Scanner#nextLine() method and confirm the entry of the numerical entry with the String#matches() method along with a small Regular Expression (RegEx) of "\d+". This expression checks to see if the entire string contains nothing but numerical digits. If it does then the matches() method returns true otherwise it returns false.
Scanner scan = new Scanner(System.in);
int sum = 0;
String val = "";
while (val.equals("")) {
System.out.print("Enter a number (END to quit): ");
val = scan.nextLine();
// Was the word 'end' in any letter case supplied?
if (val.equalsIgnoreCase("end")) {
// Yes, so break out of loop.
break;
}
// Was a string representation of a
// integer numerical value supplied?
else if (val.matches("\\-?\\+?\\d+")) {
// Yes, convert the string to integer and sum it.
sum += Integer.parseInt(val);
System.out.println("Sum is now: " + sum); // Display Sum
}
// No, inform User of Invalid entry
else {
System.err.println("Invalid number supplied! Try again...");
}
val = ""; // Clear val to continue looping
}
// Broken out of loop with the entry of 'End"
System.out.println("Application ENDED");
EDIT: Based on Comment:
Since since an integer can be signed (ie: -20) or unsigned (ie: 20) and the fact that an Integer can be prefixed with a + (ie: +20) which is the same as unsigned 20, the code snippet above takes this into consideration.
Do it like this:
public static void main(String[] args) throws Exception {
int sum = 0;
Scanner scan = new Scanner(System.in);
while (scan.hasNext()) {
System.out.print("Enter a number: ");
if (scan.hasNextInt())
sum += scan.nextInt();
else
break;
System.out.println("Sum is now: " + sum);
}
System.out.print("END");
}
This will end if the input is not a number (int).
As pointed out in the comments, if you want the program to stop when the user specifically enters "END", change the else-statement to:
else if (scanner.next().equals("END"))
break;

Java scanner adding variable conditions

I'd like to ask how do i exactly condition what my program does if my user types in a character or a string if i want him to type an integer instead? I tried to do it how i showed here in quotes and also tried with "equals". The second method didn't work the first seems to be behaving strangely the IF part works but ELSE is completely ignored.
public static void main(String[] args){
Scanner input=new Scanner(System.in);
System.out.print("Enter first integer: ");
int number1 = input.nextInt();// prompt
if (number1 == (char)number1){
System.out.println("Ok.");
}
else{
System.out.println("You were supposed to type in an int..");
System.exit(1);
}
System.out.print("Enter second integer: ");
int number2 = input.nextInt();// prompt
int sum =(number1 + number2);
System.out.printf("Your sum is: %d%n", sum);
}
I suggest you to use the regular expression in the hasNext() function as follows to have a finer control, for example use the following pattern if you look for the numbers,
sc.hasNext("[0-9]+")
Here is the documentation for the hasNext(String pattern) function,
public boolean hasNext(Pattern pattern)
Returns true if the next complete token matches the specified pattern. A complete token is prefixed and postfixed by input that matches the delimiter pattern. This method may block while waiting for input. The scanner does not advance past any input.
Here is the simple code to perform the check,
Scanner sc=new Scanner(System.in);
int input = 0;
while(true) {
System.out.println("enter a number");
if(sc.hasNext("[0-9]+")) {
input = sc.nextInt();
break;
} else {
System.out.println("not a number, try again");
sc.next(); // just consume, but ignore as its not a number
}
}
System.out.println("Entered number is : "+input);
You can use a user defined function as shown below and call it
public static boolean isNum(String input)
{
try
{
int d = Integer.parseInt(input);
}
catch(NumberFormatException e)
{
return false;
}
return true;
}
Then you can call this method from your main function.
if(isNum(number1))
I am not sure if I understand your question, but I see this as follows:
Users will always type a sequence of characters from the input, then your program has to check if that String can be converted to Int, if it can not be converted it should prompt back to the user telling the typed data is not an int. In that case your nextInt will throw an InputMismatchException.
Probably a much more elegant solution is to use hasNextInt(10):
public static void main(String[] args){
Scanner input=new Scanner(System.in);
System.out.print("Enter first integer: ");
if (input.hasNextInt(10)){
System.out.println("Ok. Typed number: " + input.nextInt());
}else{
System.out.println("You were supposed to type in an int..");
System.exit(1);
}
[...]
}
Try this,
try {
int number1 = sc.nextInt();// prompt
System.out.println("Ok.");
} catch (InputMismatchException ex) {
System.out.println("You were supposed to type in an int..");
System.exit(1);
}
Scanner.nextInt(); Scans the next token of the input as an int.
Program won't execute beyond this line if input is not int.
So it will never enter else part. Don't do any int validation.
I would suggest always use try/catch block to handle incorrect input and show useful message. Also don't forget to close Scanner object.

How do I make sure User input integer type only and integer that is greater than 0?

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

how to check the data type validity of user's input (Java Scanner class)

I am trying to make a simple UI that asks users to input double-type numbers, if theirs input is not of double type, the program should keep printing the prompt until user inputs a valid double type. My code below is not quite working yet, because when a user types in a valid double type, the program does not do anything unless the user types another double type number. I guess the condition (sc.hasNextDouble()) in the while loop consumes the first valid input. How to correct this? thanks a lot
Scanner sc = new Scanner(System.in);
System.out.println("Type a double-type number:");
while (!sc.hasNextDouble())
{
System.out.println("Invalid input\n Type the double-type number:");
sc.next();
}
userInput = sc.nextDouble(); // need to check the data type?
Since you may not get a double entered, best to read in a String, then attempt to convert it to a double. The standard pattern is:
Scanner sc = new Scanner(System.in);
double userInput = 0;
while (true) {
System.out.println("Type a double-type number:");
try {
userInput = Double.parseDouble(sc.next());
break; // will only get to here if input was a double
} catch (NumberFormatException ignore) {
System.out.println("Invalid input");
}
}
The loop can't exit until a double has been entered, after which userInput will hold that value.
Note also how by putting the prompt inside the loop, you can avoid code duplication on invalid input.
Your code works perfect: http://ideone.com/NN42UG and http://ideone.com/MVbjMz
Scanner sc = new Scanner(System.in);
System.out.println("Type a double-type number:");
while (!sc.hasNextDouble())
{
System.out.println("Invalid input\n Type the double-type number:");
sc.next();
}
double userInput = sc.nextDouble(); // need to check the data type?
System.out.println("Here it is: " + userInput);
For this input:
test test
int
49,5
23.4
Gives:
Type a double-type number:
Invalid input
Type the double-type number:
Invalid input
Type the double-type number:
Invalid input
Type the double-type number:
Invalid input
Type the double-type number:
Here it is: 23.4
Which is correct, since 49,5 is not a decimal number because it uses the wrong separator.
The way I would do it, for int vs. double would be to round and check if its still the same..
double input = sc.nextdouble();
if(input == Math.floor(input) {
//Double
} else {
//Int
}
Here is a way to check if the input is an Int, Double, String, or Character
import java.util.Scanner;
public class Variables {
/**
* #param args
*/
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String input = scan.next();
try{
double isNum = Double.parseDouble(input);
if(isNum == Math.floor(isNum)) {
System.out.println("Input is Integer");
}else {
System.out.println("Input is Double");
}
} catch(Exception e) {
if(input.toCharArray().length == 1) {
System.out.println("Input is Character");
}else {
System.out.println("Input is String");
}
}
}
}
What about Double.parseDouble(stringInput); when you scan the input as a String you can then parse it to see if it is a double. But, if you wrap this static method call in a try-catch statement, then you can handle the situation where a double value is not parsed.
I think the reason your code is not working due to first it will check the given input is of type double or not(sc.hasNextDouble()) if not then take again input(sc.hasNext()... no use of this line),then again you are taking input (userInput = sc.nextDouble())
I would suggest to do like this:
Scanner sc = new Scanner(System.in);
System.out.println("Type a double-type number:");
double userinput;
while (!sc.hasNextDouble())
{
System.out.println("Invalid input\n Type the double-type number:");
}
userInput = sc.nextDouble();
you need to give the input again if you are providing double input at first time,i think if any time you give double input then you have to provide it again ,it looks to impossible to provide input only one time.

Why am I getting InputMismatchException?

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() .

Categories

Resources