我是java程序新手,我想计算和,如果用户输入"N“,我想退出程序;如果用户输入"Y".But,则再次循环,即使我输入"N”,也不能使我退出循环。
public class Program {
public static void main(String[] args) {
boolean a=true;
while (a) {
System.out.println("enter a number");
Scanner c=new Scanner(System.in);
int d=c.nextInt();
System.out.println("enter a number2");
Scanner ce=new Scanner(System.in);
int df=ce.nextInt();
int kk=d+df;
System.out.println("total sum is"+kk);
System.out.println("do you want to continue(y/n)?");
Scanner zz=new Scanner(System.in);
boolean kkw=zz.hasNext();
if(kkw) {
a=true;
}
else {
a=false;
System.exit(0);
}
}
}我不知道我在哪里犯了这个错误?还有别的办法吗?
发布于 2020-03-16 16:04:23
首先,如果a变量是真的,则scanner.hasNext()变量是真的,这导致a是带有每个输入(包括"N" )的true,这意味着您的while循环将继续进行,直到没有更多的输入。
其次,您可以通过以下方式优化代码:
a和kkw,以使代码更简洁、更短。Scanner,并在循环的之外定义Scanner。对于相同的输入,您不需要多个Scanner。另外,用每个循环初始化一个resource-consuming.下面是您的代码的优化和工作版本:
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("Enter a number");
int input1 = scanner.nextInt();
scanner.nextLine(); // nextInt() doesn't move to the next line
System.out.println("Enter a second number:");
int input2 = scanner.nextInt();
scanner.nextLine();
System.out.println("Total sum is " + (input1 + input2)); /* Important to
surround the sum with brackets in order to tell the compiler that
input1 + input2 is a calculation and not an appending of
"Total sum is "*/
System.out.println("Do you want to continue? (Y/N)");
if (scanner.hasNext() && scanner.nextLine().equalsIgnoreCase("n"))
break;
}
scanner.close();发布于 2020-03-16 16:08:22
try (Scanner in = new Scanner(System.in)) {
boolean done = false;
while (!done) {
System.out.println("enter first number");
int d = in.nextInt();
System.out.println("enter second number");
int df = in.nextInt();
int kk = d + df;
System.out.println(String.format("total sum is %d", kk));
System.out.println("do you want to continue(y/n)?");
String cont = in.next();
done = cont.equalsIgnoreCase("n");
}
} catch(Exception e) {
e.printStackTrace();
}https://stackoverflow.com/questions/60709118
复制相似问题