首页 > 解决方案 > 我无法识别代码中的错误

问题描述

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

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

}

标签: javaloopswhile-loopchar

解决方案


您需要初始化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");

推荐阅读