如何正确格式化和代码?

时间:2015-12-27 06:27:08

标签: java sum

double SP = 0;
double SP = 0;
double sum = 0;
String name = "done";
System.out.print("Enter Stock Price of Last 5 days, then enter 'done' when finished: ");
while (name.equals("done")) {
    sum =+ SP;
    SP = input.nextDouble();
}
System.out.println(sum);

我试图获取这段代码来查找用户输入数字的总和,但我似乎无法弄清楚如何显示总和。任何人都能看出它的错误吗?

4 个答案:

答案 0 :(得分:3)

问题在于你的代码会在无限循环中进行,因为你从未重置name变量:

 while (name.equals("done")) {
    sum =+ SP;
    SP = input.nextDouble();
    }

要解决的一种方法是,你可以要求输入字符串,然后决定是否要继续:

while(true) {
    name = input.nextLine();
    if ("done".equals(name)) {
       break;
    }
    SP = Double.valueOf(name);
    sum += SP;
 }

答案 1 :(得分:2)

您可以尝试以下方式,

String stock = "";
double sum = 0.0;
System.out.println("Enter Stock Price of Last 5 days, then enter 'done' when finished: ");

while(!(stock = input.nextLine()).equalsIgnoreCase("done")) {
    double stockValue = Double.parseDouble(stock );
    sum += stockValue;
}

请注意,要+=而不是sum添加=+。 目前,您的代码处于无限循环中,因为name.equals("done")将始终为true。此外,nextDouble无法阅读String done,因此您应该使用nextLine。樱桃在顶部,最好使用equalsIgnoreCase来匹配用户的输入,无论情况如何。

答案 2 :(得分:0)

由于name的值永远不会改变且始终为done,因此循环永远不会终止。将代码更改为类似于以下内容:

        double sum = 0;
        System.out.print("Enter Stock Price of Last 5 days, then enter 'done' when finished: ");
        // As suggested in comments if input is a scanner 
        // then it does not have method nextString instead 
        // it should be just next
        String name = input.nextString();
        while (!name.equals("done")) {
            sum =+ Integer.parseInt(name);
            name = input.nextString();
        }
        System.out.println(sum);

答案 3 :(得分:0)

stop condition infinitive添加while loop