So I'm trying to make a simple calculator.
How do I make when I enter the first number, it works but if I insert "abc" it will give me an error.
How I make it in order when you write "abc" to say " please enter a number "
import java.util.Scanner;
public class calculator
{
public static void main(String[] args0) {
Scanner test = new Scanner(System.in);
int x;
int y;
String c;
System.out.println("Insert a number ");
x = test.nextInt();
System.out.println("insert a value e.g * / + -");
c = test.next();
System.out.println("Insert another number");
y = test.nextInt();
if ( c.equals("*")) {
System.out.println("the total is " + x*y);
}
if (c.equals("+")) {
System.out.println("the total is " + (x+y));
}
if (c.equals("-")) {
System.out.println("the total is "+ (x-y));
}
if (c.equals("/")) {
System.out.println("the total is "+ (x/y));
}
}
}
You can verify the input until be a int using a scanner property Scanner.hasNextInt()
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number 1: ");
while (!scanner.hasNextInt()) scanner.next();
Example:
public static void main(String[] args0) {
Scanner test = new Scanner(System.in);
int x;
int y;
String c;
System.out.println("Insert a number ");
while (!test .hasNextInt()) test .next(); // Scanner Validation
int x = test .nextInt();
}
JavaDoc of Scanner
The error you get is an exception. You can actually "catch" your exceptions, so that when they appear, your program doesn't break, and you can do what is in place for that error (output a "Please, insert only numeric values" feedback?)
You can find some info on try-catch blocks here try-catch blocks
Try this:
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner test = new Scanner(System.in);
int x;
int y;
String c;
try {
System.out.println("Insert a number ");
x = test.nextInt();
System.out.println("insert a value e.g * / + -");
c = test.next();
System.out.println("Insert another number");
y = test.nextInt();
if (c.equals("*")) {
System.out.println("the total is " + x*y);
}
if (c.equals("+")) {
System.out.println("the total is " + (x+y));
}
if (c.equals("-")) {
System.out.println("the total is "+ (x-y));
}
if (c.equals("/")) {
System.out.println("the total is "+ (x/y));
}
} catch(InputMismatchException e) {
System.out.println("Please enter correct values.");
}
}
Modifications:
The error you are getting is known as RunTime Error or Exceptions due to wrong input type. In order to handle RunTime Exceptions, You need to use try and catch block.
try and catch blocks are used to handle RunTime Exceptions. If any error or exception occurs within try block then It will be thrown to catch block to be handled instead of terminating your program.
Try this:
boolean success = false;
while (!success) {
try {
y = test.nextInt();
success = true;
} catch (InputMismatchException e) {
test.nextLine();
System.out.println("Please enter a number.");
}
}
If you're willing to accept doubles instead of ints, java doubles have a built in method isNaN(), where NaN stands for Not a Number.
if (Double.isNaN(doubleValue)) {
...
}
Related
I'm trying to make a method that gets the user's input of 6 numbers and add them to a Tree set of integers. I'm trying to make a try and catch exception so if the users accidentally enters in a letter it'll catch the exception and ask them to enter in a number. Right now the program crashes when you try to enter in a letter. It'll print out "Invalid" then crashes. I'm not sure whats going on. Can anyone provide some insight?
public static Set<Integer> getTicket()
{
int userInput;
TreeSet<Integer> getNumbers = new TreeSet<Integer>();
Scanner input = new Scanner(System.in);
System.out.println("Enter your 6 numbers between 1-40: ");
for (int i = 0; i<6 ; i++)
{
try
{
System.out.print(i+1 + ": ");
userInput = input.nextInt();
}
catch (InputMismatchException e)
{
System.out.println("Invalid");
userInput = input.nextInt();
}
getNumbers.add(userInput);
}
System.out.println("Your ticket was: " + getNumbers);
return getNumbers;
}
Just a few notes on some of the changes made. From your original code, one thing I noticed that is not really an error but a head scratcher. Both of your methods (getWinning Numbers() and getTicket() ) returned a Set<integer> set, however you did not use it in main. So I simply took the output from the methods and placed them in the main method, where they should be IMHO. Methods like these should do ONE thing and in this case is return a set of integers. No printing or anything else that’s all it does.
I changed the logic in the getTicket() method. I simply set up a loop that continued until you had 6 valid numbers. Inside that loop I use a try statement to weed out the invalid input. The way the try statement is set up is one of many ways that you could accomplish this. As you can see the statement immediately after the try (guess = Integer.parseInt(userInput);) is where the invalid input problem could pop up and throw a NumberFormatException. If the input is invalid, you drop immediately to the catch where we output a message and continue. If the input is valid then we simply check for duplicates and the range of the number. If the numbers are ok then add it to pickedNumbers and increment numberCount.
public class Lottery
{
public static Set<Integer> generateWinningNumbers()
{
Random rndNumbers = new Random();
TreeSet<Integer> winningNumbers = new TreeSet<Integer>();
int max = 40;
int min = 1;
int range;
int sixNum;
for (int i = 0; i < 6; i++)
{
range = max - min + 1;
sixNum = rndNumbers.nextInt(range) + min;
while (winningNumbers.contains(sixNum))
{
sixNum = rndNumbers.nextInt(range) + min;
}
winningNumbers.add(sixNum);
}
return winningNumbers;
}
public static Set<Integer> getTicket(Scanner input)
{
String userInput;
int guess;
TreeSet<Integer> pickedNumbers = new TreeSet<Integer>();
System.out.println("Enter your 6 numbers between 1-40: ");
int numberCount = 1;
while(numberCount < 7)
{
System.out.print(numberCount + ": ");
userInput = input.nextLine();
try
{
guess = Integer.parseInt(userInput);
if( guess > 0 && guess < 41 && (!pickedNumbers.contains(guess)) )
{
pickedNumbers.add(guess);
numberCount++;
}
else
{
if (pickedNumbers.contains(guess))
{
System.out.println("Number already picked: " + guess);
}
else
{
System.out.println("Invalid number. Pick a number between 1-40: " + guess);
}
}
}
catch (NumberFormatException e)
{
// bad input
System.out.println("Invalid input: " + userInput);
}
}
return pickedNumbers;
}
}
Changes in the Main now take advantage of the methods returning a Set of integers for us. We create two Set<Integer> variables (winningTicket and userTicket) then we simply get the returned sets from the methods and output the results as opposed to printing the results from the methods.
public static void main(String[] args) throws IOException
{
Scanner userInput = new Scanner(System.in);
boolean done = false;
String yesNo;
Set<Integer> winningTicket;
Set<Integer> userTicket;
while(!done)
{
winningTicket = Lottery.generateWinningNumbers();
userTicket = Lottery.getTicket(userInput);
System.out.println("Your ticket was: " + userTicket);
System.out.println("Winning Numbers: " + winningTicket);
System.out.print("\nWould you like to try again? ");
yesNo = userInput.nextLine();
if(!yesNo.equalsIgnoreCase("y"))
{
System.out.println("Done");
done = true;
}
}
userInput.close();
}
Hope this helps
This happens because you don't catch exceptions inside cath block. for loop doesn't look good here, try while:
public static Set<Integer> getTicket()
{
int userInput;
TreeSet<Integer> getNumbers = new TreeSet<Integer>();
Scanner input = new Scanner(System.in);
System.out.println("Enter your 6 numbers between 1-40: ");
int correct = 0;
while(correct < 6)
{
try
{
System.out.print((correct+1) + ": ");
userInput = input.nextInt();
getNumbers.add(userInput);
correct++;
}
catch (InputMismatchException e)
{
System.out.println("Invalid input");
}
}
System.out.println("Your ticket was: " + getNumbers);
return getNumbers;
}
Also you cant't print collection that simple:
System.out.println("Your ticket was: " + getNumbers);
What you can do, is to use streams:
System.out.println("Your ticket was: " + getNumbers.stream().map(Object::toString).collect(Collectors.joining(" ")));
import javax.swing.*;
import java.awt.*;
public class JCD {
public static void main(String[] args) {
String input, inputs;
int input1, input2;
input = JOptionPane.showInputDialog("Enter first number");
inputs = JOptionPane.showInputDialog("Enter second number");
input1 = Integer.parseInt(input);
input2 = Integer.parseInt(inputs);
JOptionPane.showMessageDialog(null, "The GCD of two numbers " + input
+ "and" + inputs + " is: " + findGCD(input1, input2));
}// close void
private static int findGCD(int number1, int number2) {
// base case
if (number2 == 0) {
return number1;
}// end if
return findGCD(number2, number1 % number2);
}// end static
} // close class
What can I add so that it will only accept integers? If not given an integer then it will go back to ask again.....
Put your input request in a while statement, check if it's an int, if not repeat the loop, otherwise exit. Do it for both your inputs.
Something like this
public static void main(String[] args) {
String input=null, inputs=null;
int input1 = 0, input2=0;
boolean err=true;
do{
try{
input = JOptionPane.showInputDialog("Enter first number");
input1 = Integer.parseInt(input);
err=false;
}catch(NumberFormatException e){
e.printStackTrace();
}
}while(err);
err=true;
do{
try{
inputs = JOptionPane.showInputDialog("Enter second number");
input2 = Integer.parseInt(inputs);
err=false;
}catch(NumberFormatException e){
e.printStackTrace();
}
}while(err);
JOptionPane.showMessageDialog(null, "The GCD of two numbers " + input
+ "and" + inputs + " is: " + findGCD(input1, input2));
}
Note that this solution requires you to initialize your variables when you declare them
String input = null, inputs = null;
int input1=0, input2=0;
You should try with "try and catch".
input = JOptionPane.showInputDialog("Enter first number");
inputs=JOptionPane.showInputDialog("Enter second number");
try {
input1=Integer.parseInt(input);
input2=Integer.parseInt(inputs);
// establish and use the variables if the characters inserted are numbers
}
catch(NumberFormatException e){
JOptionPane.showMessageDialog(null, e+ "is not a number");
//display a warning to le the user know
}
You could use something like this :-
boolean inputAccepted = false;
while(!inputAccepted) {
try {
input1=Integer.parseInt(input);
input2=Integer.parseInt(inputs);
inputAccepted = true;
} catch(NumberFormatException e) {
JOptionPane.showMessageDialog("Please input a number only");
}
... do stuff with good input value
}
If I remove input.nextLine() from the catch block, an infinite loop starts. The coment says that input.nextLine() is discarding input. How exactly is it doing this?
import java.util.*;
public class InputMismatchExceptionDemo {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean continueInput = true;
do {
try {
System.out.print("Enter an integer: ");
int number = input.nextInt();
// Display the result
System.out.println(
"The number entered is " + number);
continueInput = false;
}
catch (InputMismatchException ex) {
System.out.println("Try again. (" +
"Incorrect input: an integer is required)");
input.nextLine(); // discard input
}
} while (continueInput);
}
}
One more thing.. The code listed below, on the other hand, works perfectly without including any input.nextLine() statement. Why?
import java.util.*;
public class InputMismatchExceptionDemo {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter four inputs::");
int a = input.nextInt();
int b = input.nextInt();
int c = input.nextInt();
int d = input.nextInt();
int[] x = {a,b,c,d};
for(int i = 0; i<x.length; i++)
System.out.println(x[i]);
}
}
Because input.nextInt(); will only consume an int, there is still pending characters in the buffer (that are not an int) in the catch block. If you don't read them with nextLine() then you enter an infinite loop as it checks for an int, doesn't find one, throws an Exception and then checks for an int.
You could do
catch (InputMismatchException ex) {
System.out.println("Try again. (" +
"Incorrect input: an integer is required) " +
input.nextLine() + " is not an int");
}
Valid integer being a letter. I don't know the command to make it check the strings, nor do I know where to find it. Any help would be appreciated.
import java.util.Scanner;
public class Stringtest{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int test = 10;
while (test>0){
System.out.println("Input the maximum temperature.");
String maxTemp = input.nextLine();
System.out.println("Input the minimum temperature.");
String minTemp = input.nextLine();
}
}
}
Use the nextInt() to get the next integer value.
You should try/catch it in case user types a non-integer value.
Here's an example:
Scanner input = new Scanner(System.in);
// infinite loop
while (true){
System.out.println("Input the maximum temperature.");
try {
int maxTemp = input.nextInt();
// TODO whatever you need to do with max temp
}
catch (Throwable t) {
// TODO handle better
t.printStackTrace();
break;
}
System.out.println("Input the minimum temperature.");
try {
int minTemp = input.nextInt();
// TODO whatever you need to do with min temp
}
catch (Throwable t) {
// TODO handle better
t.printStackTrace();
break;
}
}
Just use input.nextInt(), and then a simple try-catch for an invalid int value.
You shouldn't try to save temperature indexes as Strings either.
You should use Integer.parseInt i.e User can enter any String and then you can check if it is an integer using this api, if it is not integer you will get an exception and then you can for another entry from user. Check below link for usage.
http://www.tutorialspoint.com/java/number_parseint.htm
try{
int num = Integer.parseInt(str);
// is an integer!
} catch (NumberFormatException e) {
// not an integer!
}
Maybe you can do something like this:
Scanner scanner = new Scanner(System.in);
int number;
do {
System.out.println("Please enter a positive number: ");
while (!scanner.hasNextInt()) {
String input = scanner.next();
System.out.printf("\"%s\" is not a valid number.\n", input);
}
number = scanner.nextInt();
} while (number < 0);
So, I was looking for an efficient way, using Java's standard packages, to read an input integer... For example, I came across the class "Scanner", but I found two main difficulties:
if I don't insert an int, I'm not actually able to solve the exception;
this class works with tokens, but my aim is to load the string in its full length.
This is an example of execution I would like to realize:
Integer: eight
Input error - Invalid value for an int.
Reinsert: 8 secondtoken
Input error - Invalid value for an int.
Reinsert: 8
8 + 7 = 15
And this is the (incorrect) code I tried to implement:
import java.util.Scanner;
import java.util.InputMismatchException;
class ReadInt{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
boolean check;
int i = 0;
System.out.print("Integer: ");
do{
check = true;
try{
i = in.nextInt();
} catch (InputMismatchException e){
System.err.println("Input error - Invalid value for an int.");
System.out.print("Reinsert: ");
check = false;
}
} while (!check);
System.out.print(i + " + 7 = " + (i+7));
}
}
Use a BufferedReader. Check NumberFormatException. Otherwise very similar to what you have. Like so ...
import java.io.*;
public class ReadInt{
public static void main(String[] args) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
boolean check;
int i = 0;
System.out.print("Integer: ");
do{
check = true;
try{
i = Integer.parseInt(in.readLine());
} catch (NumberFormatException e){
System.err.println("Input error - Invalid value for an int.");
System.out.print("Reinsert: ");
check = false;
}
} while (!check);
System.out.print(i + " + 7 = " + (i+7));
}
}
To use with tokens:
int i = Integer.parseInt(in.next());
Then you could do:
int i;
while (true) {
System.out.print("Enter a number: ");
try {
i = Integer.parseInt(in.next());
break;
} catch (NumberFormatException e) {
System.out.println("Not a valid number");
}
}
//do stuff with i
That above code works with tokens.