gpt4 book ai didi

java - 扫描仪调试

转载 作者:行者123 更新时间:2023-11-30 10:49:32 24 4
gpt4 key购买 nike

我在使用 Scanner 时遇到一些问题那是有问题的代码:

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 时,您应该只创建 1 个并且永远不要关闭它们,直到您的程序完成。这是因为关闭扫描器会关闭传入的 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 ");
}

关于java - 扫描仪调试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35380717/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com