Java 扫描仪调试
我在使用Java 扫描仪调试,java,Java,我在使用扫描仪时遇到一些问题 这就是问题代码: public static void main(String[] args) { System.out.println("Chose 1 or 2 = "); Scanner scan = new Scanner(System.in); byte a = scan.nextByte(); scan.close(); if (a==1) HW(); els
扫描仪时遇到一些问题
这就是问题代码:
public static void main(String[] args) {
System.out.println("Chose 1 or 2 = ");
Scanner scan = new Scanner(System.in);
byte a = scan.nextByte();
scan.close();
if (a==1) HW();
else if (a==2) {
System.out.print("Calculation program ... !\nInput Number 1st number = ");
Scanner Catch = new Scanner(System.in);
int x = Catch.nextInt();
System.out.println("");
System.out.print("Input Operand +,-,*,/ = ");
Scanner Catchc = new Scanner (System.in);
char z = Catchc.next().charAt(0);
System.out.println("");
System.out.print("Input 2nd number = ");
Scanner Catch2 = new Scanner (System.in);
int y = Catch2.nextInt();
Catch.close();
Catchc.close();
Catch2.close();
calc(x,y,z);
}
else System.out.println("Please input number 1 or 2 ");
}
}
这是一个简单的计算器,我没有得到任何错误,程序没有终止,而是进行调试。它显示“无此类元素异常”
计算方法:
public static void calc(int x, int y, char z) {
int result;
result = 0;
switch (z) {
case '+': result = x + y;
case '-': result = x - y;
case '/': result = x / y;
case '*': result = x * y;
}
System.out.println("Result of " + x + " " + z + " " + y + " is..." + " " + result);
}
使用Scanner
s时,您应该只创建1个,并且在程序完成之前不要关闭它们。这是因为关闭扫描仪会关闭传入的InputStream
,而此InputStream是您程序的输入,因此您的程序在该点之后不会再接收输入
重写代码以仅创建1个扫描仪,并将其传递给其他函数:
public static void main(String[] args) { // TODO Auto-generated method stub
System.out.println("Chose 1 or 2 = ");
Scanner scan = new Scanner(System.in);
byte a = scan.nextByte();
if (a==1)
HW();
else if (a==2) {
System.out.print("Calculation program ... !\nInput Number 1st number = ");
int x = scan.nextInt();
System.out.println("");
System.out.print("Input Operand +,-,*,/ = ");
char z = scan.next().charAt(0);
System.out.println("");
System.out.print("Input 2nd number = ");
int y = scan.nextInt();
calc(x,y,z);
}
else
System.out.println("Please input number 1 or 2 ");
}
这很有帮助,谢谢@Ferrybig