这只是我代码的一部分。相同的结构适用于所有 6 个变量。(级别除外)。读入后,这会打印回计算奖金的输入。奖金应该在 10 时为 0,对于 10 以上的每个偶数累积 +1,对于 10 以下的每个奇数累积 -1。如果输入了无效输入,我该如何终止。我是否必须对所有输入使用 if 条件..
import java.util.Scanner;
public class Game{
public static void main(String[]args){
Scanner sc = new Scanner(System.in);
int bonus,x;
double HP;
System.out.print("Enter Str : ");
int Str = sc.nextInt();
System.out.print("Enter Dex : ");
int Dex = sc.nextInt();
System.out.print("Enter Con : ");
int Con = sc.nextInt();
System.out.print("Enter Int : ");
int Int = sc.nextInt();
System.out.print("Enter Wis : ");
int Wis = sc.nextInt();
System.out.print("Enter Cha : ");
int Cha = sc.nextInt();
System.out.print("Enter Level : ");
int Level = sc.nextInt();
System.out.println("\nLevel : "+Level);
if ( Str == 10 ) {
bonus = 0;
System.out.println("Str : "+Str+"["+bonus+"]");
}
else if ( Str < 10 && Str % 2 == 0 ) {
bonus = 0 ;
for ( x = Str; x <= 10; x++ ) {
if ( x % 2 != 0 ) {
bonus = bonus + 1 ;
}
}
System.out.println("Str : "+Str+"[+"+bonus+"]");
}
else if ( Str < 10 && Str % 2 != 0 ) {
bonus = 0 ;
for ( x = Str; x <= 10; x++ ) {
if ( x % 2 == 0 ) {
bonus = bonus + 1 ;
}
}
System.out.println("Str : "+Str+"[-"+bonus+"]");
}
else if ( Str > 10 && Str % 2 == 0 ) {
bonus = 0 ;
for ( x = 10; x <= Str; x++ ) {
if ( x % 2 != 0 ) {
bonus = bonus + 1 ;
}
}
System.out.println("Str : "+Str+"[+"+bonus+"]");
}
else if ( Str > 10 && Str % 2 != 0 ) {
bonus = 0 ;
for ( x = 10; x <= Str; x++ ) {
if ( x % 2 == 0 ) {
bonus = bonus + 1 ;
}
}
System.out.println("Str : "+Str+"[-"+bonus+"]");
}
int Str = sc.nextInt();
如果用户输入无法解析为整数的字符串,该行将抛出异常。如果您没有捕获此异常,程序将打印回溯并中止。
对于您每次读取整数的其他尝试,都会发生同样的事情。如果您确实成功读取了整数,那么您只需要测试正确的值,如果不正确,正如其他人所说,调用 System.exit() 退出
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句