java - n 个整数扫描器的总和
问题描述
我必须使用扫描仪输入未知数量的数字。一旦用户输入-1,程序需要打印所有输入数字的总和,然后结束程序。-1 需要包含在总和中。
Scanner scanner = new Scanner(System.in);
int sum = 0;
while (true) {
int read = scanner.nextInt();
if (read == -1) {
break;
}
read = scanner.nextInt();
sum += read;
}
System.out.println(sum);
我无法得到正确的金额。有人可以帮忙吗?
解决方案
在您的 while 循环中,您分配read
了两次使用scanner.nexInt()
,这打破了您的逻辑。
Scanner scanner = new Scanner(System.in);
int sum = 0;
while (true) {
int read = scanner.nextInt();
if (read == -1) {
sum += read; //have to include -1 to sum
break;
}
//read = scanner.nextInt(); you have to delete this line
sum += read;
}
System.out.println(sum);
}
推荐阅读
- android - MotionLayout:重新启动 onCreate() 时布局中包含的视图不可见
- scala - 在 Spark DataFrame 的列中搜索字符串的最佳方法
- winapi - WinAPI 访问 Windows 控制台上的 24 位颜色
- sql - SQL Server 包含案例
- vb.net - vb.net 有可能抛出一般异常吗?
- javascript - LINQ Group by & Select FirstOrDefault() 的 Lodash 或 JavaScript 等效项
- ruby - 安装某些软件时如何导入已下载的gem?
- twitter-bootstrap - 如何使用引导程序制作与休息兼容的多选列表?
- php - 如何设置回声输出的样式以显示网格?
- c# - 使用高级选项创建 Hive ODBC 驱动程序