java - 我无法识别代码中的错误
问题描述
// 我不知道问题出在哪里
包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
为某个值,否则会出现编译错误。
此外,在 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");
推荐阅读
- azure - NSG 流日志记录和访问
- django - 连接路径(相对路径)位于基本路径组件(完整路径)之外
- mediawiki - 如何在 MediaWiki 的链接或表格中包含模板的值?
- javascript - 为什么重新分配超级方法不会导致稍后调用重新分配的方法?
- jquery - 日期选择器不适用于动态添加的 html 元素
- android - 如何以fab为中心制作bottomnavigationview并在滚动时隐藏整个视图
- apache-flink - 如何在处理键控窗口后立即清除状态?
- jquery - 内部部分的路线名称相同不起作用
- android - 如何从 SD 卡在 web 视图中打开 .ppt、.pptx、.doc、.xlsx 文件?
- android - 当我将文本输入布局添加到我的 xml 文件时,它的工作但当我单击日期选择器类应用程序崩溃时