问题
Alright so I am an intro student in a programming class and I am trying to test a catch statement of a NFE. I don't know how to format the code properly, but here it is.
import java.util.Scanner;
public class Geo {
public static void main(String[] args) {
try {
Scanner inp = new Scanner(System.in);
System.out.print("Name?");
String name = inp.nextLine();
System.out.print("Number?");
double num = inp.nextDouble();
System.out.print("Integer?");
int num2 = inp.nextInt();
} catch(NumberFormatException e) {
System.out.println("Usage error");
}
System.out.println(name);
System.out.println(num);
System.out.println(num2);
}
}
It keeps saying the variables, name, num, and num2 are undefined. What am I doing wrong here, because I was looking back at an old lab and that is exactly how I had done it before. Any hints?
Now I fixed it so the code looks like this
public static void main(String[] args) {
try {
Scanner inp = new Scanner(System.in);
System.out.print("Name?");
String name = inp.nextLine();
System.out.print("Number?");
double num = inp.nextDouble();
System.out.print("Integer?");
int num2 = inp.nextInt();
System.out.println(name);
System.out.println(num);
System.out.println(num2);
} catch(NumberFormatException e) {
System.out.println("Usage error");
}
}
but the catch isnt running. How does that get fixed. Like I want it run the try completely, but if something is wrong it keeps running, then out of try, then catches the issue.
回答1:
You must initial variables on top of try/catch.
public static void main(String[] args) {
String name = null;
double num = 0;
int num2 = 0;
try {
Scanner inp = new Scanner(System.in);
System.out.print("Name?");
name = inp.nextLine();
System.out.print("Number?");
num = inp.nextDouble();
System.out.print("Integer?");
num2 = inp.nextInt();
} catch (Exception e) {
System.out.println("Usage error");
}
System.out.println(name);
System.out.println(num);
System.out.println(num2);
}
or
public static void main(String[] args) {
try {
Scanner inp = new Scanner(System.in);
System.out.print("Name?");
String name = inp.nextLine();
System.out.print("Number?");
double num = inp.nextDouble();
System.out.print("Integer?");
int num2 = inp.nextInt();
System.out.println(name);
System.out.println(num);
System.out.println(num2);
} catch (Exception e) {
System.out.println("Usage error");
}
}
回答2:
The variables you are referring to are defined in the try
block and are therefore visible only in it, while you are trying to read them outside of the try
block.
You can either do the printing in the try
block, or define the variables in main
function.
来源:https://stackoverflow.com/questions/26203958/testing-catch-statements-of-a-nfe