identifier expected in try catch block - java

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.

Related

Checking if userInput is number with exception

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;

To compute digits of Integer

This program is for computing the digits of an integer. So there is chances to enter the input by user may string("raju" whatever it may be), number(12334), combination(string & number i.e, 234dsd) and nothing(he doesn't enter anything), isn't it? There might be another chances too I don't know(If there is mention it here).Try out with various inputs and the problems here are when I entered number and nothing. If input is number "result not coming" cmd prompt not continuing further and input is nothing(not entered) if statement is not executing. when the cmd prompt goes like that?
//computing digits of integer.
import java.util.Scanner;
class Main
{
public static void main (String w[])
{
Scanner s=new Scanner(System.in);
System.out.print("Enter a number");
String g=s.nextLine();
System.out.println("Entered value is"+g);
if(g==null)
{
System.out.println("Enter atleast one number");
}
else
{
try
{
int st=Integer.parseInt(g);
int sum=0;
while(st>=0)
{
int value=st%10;
st=st/10;
sum=value+sum;
}
System.out.println("the sum of digits: "+sum);
}catch (NumberFormatException nfe)
{
System.err.println("Invalid input. Enter only number...");
}
}
}
}
It is hard to understand you are asking here, but if you are asking you code is not trying again when the user inputs invalid input, the answer is that it is because your code has no loop to do that.
Repetition of something (in this case, the task of asking for input) generally requires a loop of some kind.
If you indented your code properly, this would probably be more obvious to you.
Try this one
//computing digits of integer.
import java.util.Scanner;
public class Main {
public static void main(String w[]) {
Scanner s = new Scanner(System.in);
System.out.println("Enter a number");
String g = s.nextLine();
System.out.println("Entered value is " + g);
try {
int st = Integer.parseInt(g);
int sum = 0;
while (st > 0) {
int value = st % 10;
st = st / 10;
sum = value + sum;
}
System.out.println("the sum of digits: " + sum);
} catch (NumberFormatException nfe) {
System.err.println("Invalid input. Enter only number...");
}
}
}
None of the answers so far explicitly mentioned the problem: There is an endless loop here:
int st=Integer.parseInt(g);
int sum=0;
while(st>=0)
{
int value=st%10;
st=st/10;
sum=value+sum;
}
because st never becomes negative when you start with a positive value.

In java, how can I handle exceptions regarding Windows command line arguments?

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.

Using try and catch to get the input

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;

Why is my catch block looping forever?

I am doing a program that calculates factorials, and I wrote a loop that catches NumberFormatException and InputMismatchException. The NumberFormatException runs fine and loops back to the try block, but the InputMismatchException displays its message over and over again without looping back to the try block. I'm not sure what I'm doing wrong. Here's my code:
import java.util.*;
public class Factorial
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.println("Factorial Test Program\n");
boolean success = false;
while (!success)
{
try
{
System.out.print("Enter an integer number: ");
int number = s.nextInt();
if (number < 0) throw new NumberFormatException();
long f = number;
for (int i = number-1; i>0; i--)
f *= i;
if (number==0) f=1;
System.out.printf("The factorial of %s is %s.\n", number, f);
success=true;
System.out.println("Done!");
}
catch (NumberFormatException e)
{
System.out.println("Factorial of this value cannot be represented as an integer");
}
catch (InputMismatchException e)
{
System.out.println("You must enter an integer - please re-enter:");
}
}
}
}
Once an invalid integer is entered s.nextInt() continously passes the newline character through the while loop and the process repeats itself ad infinitum. On the other hand, when the NumberFormatException occurs, a valid integer has already been read, so there's no newline character being passed through to the while loop.
Adding s.nextLine() within the InputMismatchException exception block will correct this issue.
add break; in the catch block.
or make the while loop inside the try block
try {
while() {
}
} catch () {
}

Categories