//我不知道问题出在哪里
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?");
}
}
答案 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");