使用switch和try语句验证用户输入... [英] Using switch and try statements to validate user input...
本文介绍了使用switch和try语句验证用户输入...的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
一旦我尝试编译我的程序,我收到以下错误:
Once I try to compile my program I receive the following errors:
C:\Java 1\New folder (2)\Chapter 04\MyType.java:53: 'catch' without 'try'
catch(NumberFormatException e)
C:\Java 1\New folder (2)\Chapter 04\MyType.java:23: 'try' without 'catch' or 'finally'
try
我的尝试:
What I have tried:
import java.io.*;
import javax.swing.JOptionPane;
public class MyType
{
public static void main(String[] args)
{
String strChoice = "", strTryString, strTryInt, strTryDouble;
int choice, tryInt;
double tryDouble;
boolean done = false;
while(!done)
{
try // 1st error
{
System.out.println("What's my type?");
strChoice = JOptionPane.showInputDialog(null,"\n\n\n1) String\n2) integer\n3) double\n4) Quit the program");
choice = Integer.parseInt(strChoice);
switch(choice)
{
case 1:
JOptionPane.showMessageDialog(null, "Correct, any input can be saved as a String");
break;
case 2:
JOptionPane.showMessageDialog(null, "Correct!");
tryInt = Integer.parseInt(strChoice);
break;
case 3:
JOptionPane.showMessageDialog(null, "Correct!");
tryDouble = Integer.parseInt(strChoice);
break;
case 4:
done = true;
JOptionPane.showMessageDialog(null, "Exit.");
System.exit(0);
break;
default:
throw new NumberFormatException();
}
catch(NumberFormatException e) // 2nd error
{
JOptionPane.showMessageDialog(null, "Invalid, try again.");
}
}
}
}
}
//所有大括号都正确对齐。
// All of the braces are correctly aligned.
推荐答案
你的catch块在你的try块里面; s / b
Your "catch" block is "inside" your "try" block; s/b
try {
...
} catch (...) {
...
}
这篇关于使用switch和try语句验证用户输入...的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文