gpt4 book ai didi

java - 如何计算列表中整数的出现次数并正确输出?

转载 作者:太空宇宙 更新时间:2023-11-04 09:20:12 25 4
gpt4 key购买 nike

首先,我是 Java 新手,大约一个月前才开始学习它。

我的硬件问题之一是“编写一个程序来提示用户积极的反馈”数字 N,后跟正数列表。用户指示结束列出-1。然后程序会输出N出现的次数就是列表”

目前,当我在列表中输入-1时,我的程序不会结束。我很困惑,因为我在网上看到的每个教程都涉及数组,而我还没有学过。

public class CountOccurence {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number");
int num1 = sc.nextInt();
System.out.println("Enter a list of positive numbers\nEnter -1 to indicate end:");
int count = 0;
int input;
while (num1 > 0) {
sc.nextInt();
input = sc.nextInt();
while (input == num1) {
int count2 = count + 1;
while (input == -1) {
System.out.println("Your number occurs" + count2 + "times");

}
}
}
}
}

最佳答案

鉴于您还没有了解数组,您的解决方案背后的想法非常巧妙,但是存在一些错误,可能会导致您的代码无法正常工作。

首先,有许多 while 循环要么不执行,要么无限循环。您似乎将 while 循环与 if 语句混淆了。您可以阅读更多有关差异的信息 here

正如 Andreas 和 Scary Wombat 所指出的,有一个分散的 sc.nextInt(); 没有分配给任何东西。删除它,因为它会无意中删除用户的输入。

考虑到这一点,这是我使用您的方法的解决方案。

import java.util.Scanner;

public class CountOccurence {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number");
int num1 = sc.nextInt();
System.out.println("Enter a list of positive numbers\nEnter -1 to indicate end:");
int count = 0;
int input = 0;
while (input != -1) {
input = sc.nextInt();
if (input == num1) {
count++;
}
}
System.out.println("Your number occurs " + count + " times");
}
}

我选择在最后打印出现的情况,因为那是在用户输入 -1 之后。

顺便说一句,欢迎来到 Stack Overflow 社区!

关于java - 如何计算列表中整数的出现次数并正确输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58404478/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com