繁体   English   中英

如何更好地编写以下Java代码?

[英]How can I write the following Java code better?

我已经以多种方式尝试了以下代码,但是它根本无法正常工作。 我有两个问题。

  1. 当我按X时,我需要它不继续QUANTITY。
  2. 如果我想继续,也就是说,我不按X但是输入我应该按的代码,它会正确地输入第一个输入,但是当它绕过第二个类型的循环时,它会输出类似“CODE:QUANTITY:在同一行上。

我真的很感激这里的帮助,因为我被困住了谷歌并没有帮助。 我是编程的新手,以前没有任何语言的经验,所以我非常感谢详细的帮助。

这是代码:

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语句时使用大括号。 当您需要添加一条额外的语句而忘记花括号或太累而无法注意到时,这可以在以后的开发中帮助解决问题。

  • 将while循环用于布尔条件,特别是如果您不在任何地方使用索引的话。 用于循环以迭代序列元素。
  • 使用break语句退出循环,而不是使用布尔条件**
  • 使用java编码风格
  • 使用System.out.println输出一行文本。

所以基本上:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM