[英]How can I write the following Java code better?
我已经以多种方式尝试了以下代码,但是它根本无法正常工作。 我有两个问题。
我真的很感激这里的帮助,因为我被困住了谷歌并没有帮助。 我是编程的新手,以前没有任何语言的经验,所以我非常感谢详细的帮助。
这是代码:
import java.util.Scanner;
class WHY
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
boolean count = true;
for (int i = 0; count; i++)
{
System.out.print("CODE: (X to terminate)");
String code = in.nextLine();
System.out.print("QUANTITY: ");
int quantity = in.nextInt();
if (code.equals("X"))
count = false;
}
}
}
Scanner in = new Scanner(System.in);
while (true) {
System.out.print("CODE: (X to terminate)");
String code = in.nextLine();
if (code.equalsIgnoreCase("x")) {
break;
}
System.out.print("QUANTITY: ");
int quantity = in.nextInt();
in.nextLine();
}
这是有关如何简化语句(使其适合您的类)的示例,过程性伪代码。
private static final String QUIT = "X";
String code = ""
while (!(code = readCode()).equalsIgnoreCase(QUIT)) {
//Process the code read....
System.out.println();
System.out.print("QUANTITY: ");
int quantity = in.nextInt();
}
public String readCode() {
Scanner in = new Scanner(System.in);
System.out.println();
System.out.print("CODE: (X to terminate)");
return in.nextLine();
}
使用System.out.println()
。 这将创建一个新行。
由于您希望在用户输入“X”后立即中断循环,因此您可以使用break
关键字来停止循环。 我还建议用while(true)
循环替换你的for
循环。 这将永远保持循环(这是break关键字用于阻止其无限循环的地方)。 System.out.print
在同一行中打印文本,使用System.out.println()
打印文本并移至下一行。 最后,您应该在读取code
值之后移动条件语句,并将break
替换为count = false
。
作为最后一个提示,我建议您在有if else
语句时使用大括号。 当您需要添加一条额外的语句而忘记花括号或太累而无法注意到时,这可以在以后的开发中帮助解决问题。
所以基本上:
import java.util.Scanner;
class WHY {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while(true) {
System.out.print("CODE: (X to terminate)");
String code = in.nextLine();
System.out.println("QUANTITY: ");
int quantity = in.nextInt();
if (code.equals("X"))
break;
}
}
}
**品味问题
把事情简单化:
Scanner in = new Scanner(System.in);
int total = 0;
while (true) {
System.out.print("CODE: (X to terminate)");
String code = in.nextLine();
if (code.equalsIgnoreCase("x")) {
break;
}
System.out.print("QUANTITY: ");
int quantity = in.nextInt();
total += quantity;
}
System.out.print("The total is: " + total);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.