【问题标题】:i can not identify the mistake in my code [closed]我无法识别我的代码中的错误[关闭]
【发布时间】:2019-03-25 18:55:49
【问题描述】:

//我不知道问题出在哪里

包javaapplication3; 导入 java.util.Scanner;

公共类 JavaApplication3 {

public static void main(String[] args) 
{
    Scanner keyboard=new Scanner(System.in);
    int num1,num2;
    String input;
    input= new String();
    char again;
    while (again =='y' || again =='Y')
    {
        System.out.print("enter a number:");
        num1=keyboard.nextInt();
        System.out.print("enter another number:");
        num2=keyboard.nextInt();
        System.out.println("their sum is "+ (num1 + num2));
        System.out.println("do you want to do this again?");
    }

}

【问题讨论】:

  • 你没有为again赋值,你应该这样做。
  • char again; 永远不会是 'y''n'
  • 到底发生了什么问题?

标签: java loops while-loop char


【解决方案1】:

您需要将again初始化为某个值,否则会出现编译错误。

另外,在while循环结束时,您需要从扫描器对象中读取数据并将值分配给again变量。检查您修改后的 Java 代码,

Scanner keyboard = new Scanner(System.in);
int num1, num2;
String input;
input = new String();
char again = 'y'; // You need to initialize it to y or Y so it can enter into while loop
while (again == 'y' || again == 'Y') {
    System.out.print("enter a number:");
    num1 = keyboard.nextInt();
    System.out.print("enter another number:");
    num2 = keyboard.nextInt();
    System.out.println("their sum is " + (num1 + num2));
    System.out.println("do you want to do this again?");
    again = keyboard.next().charAt(0); // You need to take the input from user and assign it to again variable which will get checked in while loop condition
}
System.out.println("Program ends");

编辑:这里最好使用do while 循环

检查此代码是否有 do while 循环,您无需担心初始化 again 变量。

Scanner keyboard = new Scanner(System.in);
int num1, num2;
char again;
do { // the loop first executes without checking any condition and you don't need to worry about initializing "again" variable
    System.out.print("enter a number:");
    num1 = keyboard.nextInt();
    System.out.print("enter another number:");
    num2 = keyboard.nextInt();
    System.out.println("their sum is " + (num1 + num2));
    System.out.println("do you want to do this again?");
    again = keyboard.next().charAt(0); // here "again" variable is initialized and assigned the value anyway
} while (again == 'y' || again == 'Y'); // checks the condition and accordingly executes the while loop or quits
keyboard.close();
System.out.println("Program ends");

【讨论】:

  • 嗨,谢谢你的回答,但我还有一个问题,你让我再次为变量设置一个值,我怎样才能再次将值'y'赋给变量而不是'Y' 因为在代码中它说 'y' 或 'Y' ......我想说的是,你不认为该变量可以再次使用它们,但在不同的时间????跨度>
  • @aminhadi:不确定我是否能得到您的问题,但您可以将again 的值初始化为yY,因为您的while 循环同时接受这两者。同样,当它要求您再次输入时,您可以输入yY,这两种情况都可以。如果您有任何其他疑问,请告诉我。另外,我建议使用更适合您的情况的 do while 循环。 do while loop 首先执行循环,然后检查条件是否应该再次执行循环。
  • @aminhadi:我已经用do while 循环代码更新了我的答案,这可能更适合您。如果您有任何疑问,请查看并告诉我。
猜你喜欢
  • 2017-03-19
  • 2023-03-23
  • 1970-01-01
  • 2023-01-05
  • 2016-08-09
  • 2017-07-12
  • 1970-01-01
  • 2013-05-02
  • 1970-01-01
相关资源
最近更新 更多