gpt4 book ai didi

java - 打印 0 代替键盘输入

转载 作者:行者123 更新时间:2023-12-01 14:38:35 27 4
gpt4 key购买 nike

因此,程序应该允许用户输入 10 个分数,并在下一行按升序打印这些分数。由于某种原因,它允许我输入分数,但下面的行只是用 0 填充,而不是按升序对输入进行排序。我不确定为什么,但任何输入都会有帮助。

public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);

System.out
.println("Enter up to 35 scores between 0 and 100, -1 to stop:");

int[] score = new int[35];
int count = 0;
int sum = 0;
String scores = "";

for (int i = 0; i < score.length; i++) {
score[i] = keyboard.nextInt();
if (score[i] >= 0) {

scores = scores + score[i] + " ";
count++;
sum = sum + score[i];
} else
i = score.length + 1;

}

for (int i = 1; i < score.length; i++) {
int x;
int temp;

x = score[i];
temp = score[i];
for (x = i - 1; x >= 0 && score[x] > temp; x--) {
score[x + 1] = score[x];
}
score[x + 1] = temp;
}

System.out.printf("The %d scores you entered are: \n%s", count, scores);
System.out.println();
System.out.printf("The %d scored sorted in nondecreasing order are:\n",
count);
int k=1;
for (k=1; k <= count; k++) {
if (k % 11 == 0) {
System.out.println();
} else {
System.out.printf("%5d", score[k]);
}
}

for (int i = 1; i <= count; i++) {
if (i % 11 == 0) {
System.out.println();
} else {
System.out.printf("%5d", score[i]);
}

for (int j = 1; j < count; j++) {
if (Integer.compare(score[i], score[j]) < 0) {
int temp = score[i];
score[i] = score[j];
score[j] = temp;
}
}
}

最佳答案

我同意关于学习调试的评论。从您编写代码的方式来看,显然您是非常初学者,因此这里的答案可以帮助您。为了回答你的问题,你的程序中有几个逻辑错误。

您可以简单地使用break退出第一个for循环。所以在else语句中只写break;而不是 i = Score.length + 1;

下一步...错误是您正在对整个数组进行排序...但是,由于您在输入 -1 之前可能只输入了 5 或 6 个元素,因此前 5 或 6 个元素将具有值以及该分数中的所有其他值数组为 0。如果对整个数组进行排序,显然会将 0 放在数组的前面,将实际分数放在数组的后面。这就是你的问题的答案。从 i = 0 到 i < count 排序。这将解决您的一些问题,但您还有更多问题。

还有其他几个问题。我希望您能够调试并找出答案。

关于java - 打印 0 代替键盘输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16227242/

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