So I was just trying to create a simple program with bit more complicated code.
What I was asked to do was write a program which controls whether it's a positive or negative number (I know, it's easy).
What I was trying to do was to catch what was being entered, so if its not a float it will say to use a comma instead of point or enter a number instead of String.
package example1;
import java.util.InputMismatchException;
import java.util.Scanner;
public class numbritest
{
public static void main(String[] args)
{
float num;
Scanner sisse1 = new Scanner(System.in);
try
{
System.out.println("Sisesta number:");
System.out.println("Kaks komakohta on lubatud");
num = sisse1.nextFloat();
}
catch(InputMismatchException exception) //juhul kui sisestab miskit muud
{
System.out.println("Kontrolli kas kasutasid koma!");
}
if (num < 0) //kui arv väiksem
{
System.out.println("Number " +num +" on negatiivne.");
System.out.println("Seega on arv väiksem nullist");
}
else //Kui arv on suurem või võrdne
{
System.out.println("Number " +num +" on positiivne.");
System.out.println("Positiivsed arvud on suuremad");
System.out.println("või võrdsed nulliga.");
}
System.out.println();
System.out.println("Programm lõpetada!");
}
}
Sorry that it's in Estonian, but I hope you get my point.
Change float num; to float num = 0.0f; and it should work properly
What you should do is create a loop and ask user to input number as long as the number is not correct:
So this code:
try
{
System.out.println("Sisesta number:");
System.out.println("Kaks komakohta on lubatud");
num = sisse1.nextFloat();
}
catch(InputMismatchException exception) //juhul kui sisestab miskit muud
{
System.out.println("Kontrolli kas kasutasid koma!");
}
Should be in a loop - for example:
boolean incorrectNumberFormat;
do
{
incorrectNumberFormat = false;
try
{
System.out.println("Sisesta number:");
System.out.println("Kaks komakohta on lubatud");
num = sisse1.nextFloat();
}
catch(InputMismatchException exception) //juhul kui sisestab miskit muud
{
System.out.println("Kontrolli kas kasutasid koma!");
sisse1.nextLine();
incorrectNumberFormat = true; //repeat the loop;
}
} while(incorrectNumberFormat);
By the way - comma won't generate the exception (for me 3,3 doesn't), but 3%3 should give you the exception.
The loop can be created in various ways it's just an quick example.
I'd change it to
Float num = null;
(note we're now using a Float object rather than float primitive, so it can be null) and then use a while condition:
while (num == null) {
try {
//...
num = sisse1.nextFloat();
} catch (InputMismatchException e) {
//give error
}
}
This will not put anything into num until the num = ... line succeeds, so it'll stay null whenever it fails. This is better than just setting it to 0.0f, because otherwise it'll cause problems if the user enters zero.
Initialize the local varible before use;
In these case compiler consider that try block may execute or not so that num.nextFloat() may execute or not so compiler throws error: variable num might not have been initialized.
so that change float num; to float num=0.0f;
Related
Im trying to check whether the input from the User is an int or not.
Heres my code so far:
static int readInt(Scanner userInput) {
int intValue = 0;
try {
System.out.print("Please enter a number:");
intValue = Integer.parseInt(userInput.nextLine());
} catch (NumberFormatException ex) {
Input.readInt(userInput);
}
return intValue;
}
The problem is: if I first give it input which is not a number and then after that i give it a number it always returns 0. If i give it a number the first attempt it returns the number I have given it.
What am I missing?
Thanks in advance
edit: Im only allowed to use Integer.parseInt and Exceptions.
To avoid your problem, in the catch block you need to assign this Input.readInt(userInput) to your variable. like this :
intValue = Input.readInt(userInput);
It looks like you are not setting the variable in the catch
intValue = Input.readInt(userInput);
Recursion is overhead here. use loop:
Integer result = null;
do {
System.out.print("Please enter a number:");
try {
result = Integer.parseInt(userInput.nextLine());
} catch (NumberFormatException ex) {
System.out.print("Not a number");
}
} while(result==null);
return result;
I have a try-catch that is meant to catch anything that is not an integer. When I enter a non integer (e.g. 5.6) it tells me only integers are allowed and lets me try again (as it should). But if I enter a non-integer again it doesn't say anything and will keep taking inputs, leaving output blank.
if (choicesObjects == b) {
System.out.println("TEST 2");
System.out.println("Object: Right triangle");
System.out.println("\nEnter length of Right triangle: ");
int lengthOfTriangle = 0;
try {
lengthOfTriangle = input.nextInt();
} catch(InputMismatchException e) {
System.out.println("\nError: user input must be an integer greater than 0.\n");
System.out.println("Object: Right triangle");
System.out.println("\nEnter length of Right triangle: ");
input.next();
}
//method stuff
}
The try/catch statement is not a loop. It will always be executed once.
Of course, if there is a loop inside the try block, that block will keep executing until terminated. But such a loop requires an explicit command like while or for to be used.
Apparently what happens when entering a non-integer value (e.g., 5.6), is that the nextInt() statement throws an Exception and goes to the catch block. A better explanation can be given if the full code of the method is provided.
For this you could define a function, something like this should work
private int getNextInt(Scanner input) {
boolean isInt = false;
int userInput;
while(!isInt) {
try {
userInput = Integer.valueOf(input.next());
isInt = true;
} catch(NumberFormatException e) {
// Do nothing with the exception
}
}
return userInput;
}
This should run until an input given was an int and then return said int
You can update your code to something like this -
Scanner in = new Scanner(System.in);
int num = 0;
while(true) {
try{
num = in.nextInt();
break;
}catch(Exception e){
//print statements
System.out.println("Try again");
}
}
System.out.println("Done");
something like this
Boolean check = true;
while (check) {
if choicesObjects == b {
enter code here` System.out.println("TEST 2");
System.out.println("Object: Right triangle");
System.out.println("\nEnter length of Right triangle: ");
int lengthOfTriangle = 0;
try {
lengthOfTriangle = input.nextInt();
} catch(InputMismatchException e) {
System.out.println("\nError: user input must be an integer greater than 0.\n");
check = false;
System.out.println("Object: Right triangle");System.out.println("\nEnter length of Right triangle:");
input.next();
}
//method stuff
}
}
`
I looked through a bunch of other questions and online, but I can't find anything that answers this specifically. I'm trying to handle dealing with and determining valid input based on a Windows command line argument. As a sample, I was just seeing if an entered number was positive to be as easy as possible. The biggest issue, and what made me unable to find a specific answer, was I'm really trying to use recursion to make it keep asking until a valid input is entered, rather than just killing the program.
Algorithm:
If there is an argument provided and it's a positive integer
Display value
Otherwise
Until the argument is a positive number
Prompt for a positive integer
Display value
I wrestled with the code and eventually got this to work, but it seems really inefficient, repetitive and hacked together. At first, I had the while-loop inside the caught exceptions, but this allowed other things to slip through from the command line. How can I make this as efficient as possible and also prevent any logic errors or exceptions? What approach should I take with my algorithm when tackling this? Here's my code:
import java.util.Scanner;
public class Test
{
public static void main( String[] args )
{
String arg;
Scanner user_input = new Scanner(System.in);
int i = 0;
try {
arg = args[0];
i = Integer.parseInt(arg);
} catch( ArrayIndexOutOfBoundsException e ) {
arg = "";
} catch( NumberFormatException e2 ) {
arg = "";
}
while( i <= 0 )
{
System.out.print("Please type in a positive whole number. ");
arg = user_input.next();
try {
i = Integer.parseInt(arg);
} catch( NumberFormatException e2 ) {
System.out.print("That's a letter! ");
continue;
}
if( i <= 0 )
{
System.out.print("That's a negative. ");
}
}
System.out.println("Input is " + i);
}
}
Try this:
The code is quite lengthy this is because two separate try blocks are required; one for the command-line argument & the other for the argument provided via the scanner...
I had to create my own custom exception, "NegativeNumberException"...
import java.util.Scanner;
public class NegativeNumberException extends Exception{
NegativeNumberException(){
System.out.println(exceptionMessage);
}
String exceptionMessage = "Number must be positive";
static int num;
public static void main(String[] args) throws NegativeNumberException{
try
{
if(Integer.parseInt(args[0])<0){
throw new NegativeNumberException();
}
else{
int num = Integer.parseInt(args[0]);
System.out.println("Your number is: " + num);
}
}
catch(NumberFormatException ex){
System.out.println("That's not even a number.");
}
catch(NegativeNumberException ex){
ex.getMessage();
}
while(num==0){
try{
System.out.println("Enter a positive number:");
Scanner input = new Scanner(System.in);
int num1 = input.nextInt();
if(num1<0){
throw new NegativeNumberException();
}
num = num1;
break;
}catch(Exception ex){
System.out.println("Positive number only, try again...");
}
}//End While
System.out.println("Your number is:" + num);
}
}
Input: (Command-line): lol
Output
(Console):That's not even a number
Enter a positive int
(Console input via Scanner): -4
(Console):Number must be positive
Positive number only, try again...
Enter a positive number:
(Console input via Scanner): 3
(Console):Your number is: 3
I modified your code so that it runs the way you want. Try using this:
public static void main( String[] args ) {
String arg;
Scanner user_input = new Scanner(System.in);
int numTries = 0, value = 0;
try {
numTries = Integer.parseInt(args[0]); // get max number of tries
} catch (ArrayIndexOutOfBoundsException e) {
arg = "";
} catch (NumberFormatException e2) {
arg = "";
}
// try 'numTries' times to read a valid number input
for (int i=numTries; i > 0; --i) {
System.out.print("Please type in a positive whole number: ");
arg = user_input.next();
try {
value = Integer.parseInt(arg);
} catch(NumberFormatException e2) {
System.out.println("That's a letter! ");
continue;
}
if (value <= 0) {
System.out.println("That's a negative. ");
}
break; // exit loop if number input found
}
System.out.println("Input is " + value);
}
This code has been tested on IntelliJ and it runs with no problems.
I am trying to run a catch block but it keeps saying that an identifier is expected. Any help would be welcome. The object of this method (it is in a main so I can test it) is to get a valid value for an integer. If the value is not valid it should loop until a valid number is entered. I attempted to do this using a while loop, and the try...catch to fix any exceptions. Thank you
import javax.swing.JOptionPane;
import java.lang.Integer;
public class test
{
public static void main (String[] args) throws NumberFormatException
{
String input;
boolean x = false;
int number;
input = JOptionPane.showInputDialog("Enter an integer: "); //creates input box for user to enter integer value
number = Integer.parseInt(input);
try
{
while (number < -2147483648 && number > 2147483647)
{
x = false;
number = Integer.parseInt(input);
System.out.println("You selected: " + number)
}
}
catch (NumberFormatException)
{
input = JOptionPane.showInputDialog("Enter a valid integer: ");
}
}
}
You are not defining a name (identifier) for the NumberFormatException in the catch statement.
You need:
catch (NumberFormatException e)
{
...
}
Regarding your numbers problem:
number < -2147483648 && number > 2147483647
Those are the min and max values of integer, so perhaps using long type instead of int will help.
I have been trying to stop the exceptions but I cannot figure out how.
I tried parseInt, java.util.NormalExceptionMismatch etc.
Does anyone have any insight how to fix this problem? Formatting is a bit off due to copy and paste.
do
{
System.out.print(
"How many integers shall we compare? (Enter a positive integer):");
select = intFind.nextInt();
if (!intFind.hasNextInt())
intFind.next();
{
// Display the following text in the event of an invalid input
System.out.println("Invalid input!");
}
}while(select < 0)
Other methods I have tried :
do
{
System.out.print(
"How many integers shall we compare? (Enter a positive integer):");
select = intFind.nextInt();
{
try{
select = intFind.nextInt();
}catch (java.util.InputMismatchException e)
{
// Display the following text in the event of an invalid input
System.out.println("Invalid input!");
return;
}
}
}while(select < 0)
It seems to me that you want to skip everything until you get an integer. This code here skips any input except an integer.
As long as there is no integer available (while (!in.hasNextInt())) discard the available input (in.next). When integer is available - read it (int num = in.nextInt();)
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (!in.hasNextInt()) {
in.next();
}
int num = in.nextInt();
System.out.println("Thank you for choosing " + num + " today.");
}
}
Quick sample of how to catch exceptions:
int exceptionSample()
{
int num = 0;
boolean done = false;
while(!done)
{
// prompt for input
// inputStr = read input
try {
num = Integer.parseInt(inputStr);
done = true;
}
catch(NumberFormatException ex) {
// Error msg
}
}
return num;
}
IMO, the best practice is to use nextLine() to get a String input, then parseInt it to get the integer. If unparsable, just complain back to the user and request re-entry.
Remember you may have to do a second nextLine() (discard the input) to clear up the buffer.