所以我现在正在处理一个项目,这一步要求我写一个程序,询问数字以及何时" -1"输入后,它将计算除-1之外输入的所有数字的总和。我只是通过在循环后添加+1来修复此问题,但我确定还有另一个"正确的"这样做的方式,我想学习如何。
感谢任何帮助。 (注意:我只在大约一周学习Java,所以请ELI5)
public static void main(String[] args) {
// program in this project exercises 36.1-36.5
// actually this is just one program that is split in many parts
Scanner reader = new Scanner(System.in);
int numbertyped = 0;
int sum = 0;
System.out.println("Type numbers: ");
while (numbertyped != -1) {
numbertyped = Integer.parseInt(reader.nextLine());
sum = sum + numbertyped;
}
sum++;
System.out.println("Thank you and see you later!");
System.out.println("The sum is " + sum);
编辑:我的程序现已完成。我使用了在while循环中添加break的解决方案,并在添加了我想要的其余功能之后,这是最终产品:(如果有人有关于如何改进我的代码或使其更有效的提示请注释!)< / p>
import java.util.Scanner;
public class LoopsEndingRemembering {
public static void main(String[] args) {
// program in this project exercises 36.1-3
// actually this is just one program that is split in many parts
Scanner reader = new Scanner(System.in);
int numbertyped = 0;
int sum = 0;
int howmany = 0;
int evencounter = 0;
int oddcounter = 0;
System.out.println("Type numbers: ");
while (true) {
numbertyped = Integer.parseInt(reader.nextLine());
if (numbertyped == -1)
{
break;
}
if (numbertyped % 2 == 0)
{
evencounter++;
}
else
{
oddcounter++;
}
sum = sum + numbertyped;
howmany++;
}
double average = (double) sum / howmany;
System.out.println("Thank you and see you later!");
System.out.println("The sum is " + sum);
System.out.println("How many numbers: " + howmany);
System.out.println("Average: " + average);
System.out.println("Even numbers: " + evencounter);
System.out.println("Odd numbers: " + oddcounter);
}
}
答案 0 :(得分:8)
您可以在输入-1
后立即终止循环,更改
while (numbertyped != -1) {
numbertyped = Integer.parseInt(reader.nextLine());
类似
while ((numbertyped = Integer.parseInt(reader.nextLine())) != -1) {
// ...
,-1
分配给numbertyped
时,系统不会输入循环体。
根据您的修改,我建议您可以将sum = sum + numbertyped;
缩短为sum += numbertyped;
,并且可以通过汇总howmany
和evencounter
来计算oddcounter
。像,
System.out.println("Type numbers: ");
while (true) {
numbertyped = Integer.parseInt(reader.nextLine());
if (numbertyped == -1) {
break;
}
if (numbertyped % 2 == 0) {
evencounter++;
} else {
oddcounter++;
}
sum += numbertyped;
}
int howmany = evencounter + oddcounter;
double average = (double) sum / howmany;
答案 1 :(得分:4)
在类似的情况下,类似C语言的用户通常不会使用“退出循环”(break
)。你需要这样的东西:
while (true)
{
numbertyped = Integer.parseInt(reader.nextLine());
if(numbertyped == -1)
{
break;
}
sum = sum + numbertyped;
}
作为旁注,“永久循环”可以用for(;;)
编写,有些人说这比while(true)
好。但是,大多数人认为while(true)
更容易阅读。我个人使用for(;;)
。无论哪种方式都可以正确优化,因此您将无法获得运行时差异。
关于for(;;)
的参考:
while (1) Vs. for (;;) Is there a speed difference?
答案 2 :(得分:0)
我认为在这种情况下,你可以颠倒while循环中语句的顺序。
int numbertyped = 0;
int sum = 0;
System.out.println("Type numbers: ");
while (numbertyped != -1) {
sum = sum + numbertyped;
numbertyped = Integer.parseInt(reader.nextLine());
}
第一次循环,numberTyped为0,这是完美的 - 它不会退出循环,并且它实际上不会向总和添加任何东西。在那之后,它不会改变总和,直到你检查它是否为-1。