读取输入,直到输入特定数字

Read input until a certain number is typed(读取输入,直到输入特定数字)
本文介绍了读取输入,直到输入特定数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

当输入零并立即开始求和时,我需要停止询问整数输入.当我输入零时,我的程序不会停止.我需要它停止并开始总结它收集的所有输入.

I need to stop asking for integer inputs when zero is typed as an input and start summation immediately. My program doesn't stop when I type zero. I need it to stop and start summing up all the inputs it has gathered.

这是我所拥有的:

public class Inttosum {

    public static void main(String[] args) {
        System.out.println("Enter an integer");
        Scanner kb = new Scanner(System.in);
        int askool = kb.nextInt();
        int sum = 0;
        int score = 0;


        while(askool != 0){
          score = kb.nextInt();
          sum += score;
        }
    }
}

///////////////最终代码有效..谢谢!公共类 Inttosum {

/////////////////The final code which worked..Thank you! public class Inttosum {

    public static void main(String[] args) {
        System.out.println("Enter an integer");

    Scanner kb = new Scanner(System.in);
    int sum = 0;
    int score = 0;
    do {
        score = kb.nextInt();
        sum += score;

    }while(score != 0);
    System.out.print(sum); 
 }
}

推荐答案

do-while

您正在使用称为 askool 的东西作为循环条件,但在循环中更新变量 score.您可以使用 do-while 循环.改变

do-while

You are using something called askool as a loop condition, but updating the variable score in your loop. You could use a do-while loop. Change

while(askool != 0){
    score = kb.nextInt();
    sum += score;
}

类似

do {
    score = kb.nextInt();
    sum += score;
}while(score != 0);

使用 break

我还建议调用 Scanner.hasNextInt() 在调用 nextInt 之前.而且,由于你不使用 score(只是 sum)你可以这样写,

Using break

I also suggest calling Scanner.hasNextInt() before calling nextInt. And, since you don't use the score (just the sum) you could write it like,

int sum = 0;
while (kb.hasNextInt()) {
    int score = kb.nextInt();
    if (score == 0) {
        break;
    }
    sum += score;
}
System.out.print(sum);

如果用户输入文本,它也会停止(并且仍然 sum 所有 ints).

Which will also stop (and still sum all ints) if the user enters text.

这篇关于读取输入,直到输入特定数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

java8 stream sum multiple(java8流总和倍数)
How to output the decimal in average?(如何平均输出小数?)
Java sum 2 negative numbers(Java求和2个负数)
How to get sum of char values produced in a loop?(如何获得循环中产生的 char 值的总和?)
How can I sum the values associated with a reoccurring key in a hashmap(如何将与哈希图中重复出现的键关联的值相加)
subset sum find all subsets that add up to a number(子集和找到所有加起来为一个数字的子集)