英文:
Avg/Max from ArrayList
问题
public class LabProgram {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int count = 0, max = 0, total = 0;
int num = scnr.nextInt();
if (num >= 0) {
count++;
total += num;
max = Math.max(max, num);
num = scnr.nextInt();
}
int avg = count == 0 ? 0 : total / count;
System.out.println(avg + " " + max);
}
}
英文:
I've had a ton of issues with this program, added a while hasNextInt, multiple other things and i've finally got the code working, but my output is just the first input, instead of max/avg of the inputs. Could somebody let me know where i'm messing up?
public class LabProgram {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int count = 0, max = 0, total = 0;
int num = scnr.nextInt();
if (num >= 0) {
count++;
total += num;
max = Math.max(max, num);
num = scnr.nextInt();
}
int avg = count == 0 ? 0 : total/count;
System.out.println(avg + " " + max);
}
}
</details>
# 答案1
**得分**: 1
你没有使用循环从控制台获取数字。此外,计算平均值的逻辑可能会得出错误的答案。请查看下面的解决方案。
```java
Scanner scnr = new Scanner(System.in);
int count = 0, max = 0, total = 0;
System.out.println("输入任何非数字字符以终止输入:");
while(scnr.hasNextInt()) {
int num = scnr.nextInt();
if (num >= 0) {
count++;
total += num;
max = Math.max(max, num);
}
}
double avg = count == 0 ? 0 : (double)total/(double)count; // 为了正确输出平均值
System.out.println(avg + " " + max);
示例输出:
输入任何非数字字符以终止输入:
3
3
34
a
13.333333333333334 34
英文:
you are not using a loop to get numbers from the console. Also, logic for avg may result in the wrong answer. find below solution.
Scanner scnr = new Scanner(System.in);
int count = 0, max = 0, total = 0;
System.out.println("Enter any other characters expect numbers to terminate:");
while(scnr.hasNextInt()) {
int num = scnr.nextInt();
if (num >= 0) {
count++;
total += num;
max = Math.max(max, num);
}
}
double avg = count == 0 ? 0 : (double)total/(double)count; // to print correct avg
System.out.println(avg + " " + max);
sample Output:
Enter any other characters expect numbers to terminate:
3
3
34
a
13.333333333333334 34
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论