我无法在代码中识别错误

时间:2019-03-25 18:55:49

标签: java loops while-loop char

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

package 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?");
    }

}

1 个答案:

答案 0 :(得分: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");