我正在创建一个程序,我必须从多个用户那里获取分数,然后打印最高和最低分数。我尝试通过创建循环并询问分数和名称,然后为循环内和循环外尝试的高点和低点创建新变量来做到这一点,但它没有起作用,任何帮助将不胜感激!
/* 姓名:阿曼和肯尼 * 日期: * 类(class): * 描述: */
import hsa.Console;
import java.awt.*;
public class testPilo
{
static Console c;
public static void main(String[] args)
{
c = new Console();
int i = 0;
int a = 0;
int y = 0;
String x = "";
String bigBoy = "";
String lilBoy = "";
int highest = 0;
int lowest = 0;
c.println("How man players do you want?");
a = c.readInt();
while(true){
if(y >= highest){
bigBoy = x;
highest = y;
}
i++;
c.println("enter the name of gamer #"+i);
x = c.readString();
c.println("What is your score "+x+"?");
y = c.readInt();
highest = y;
lowest = y;
if(y <= lowest){
lilBoy = x;
lowest = y;
}
if(i == a) break;
}
c.println("The highest is "+lilBoy);
c.println("The lowest is "+bigBoy);
}
}
最佳答案
您已经非常接近并且处于正确的轨道上了。您应将 highest
初始化为 Integer.MIN_VALUE
,将 lowest
初始化为 Integer.MAX_VALUE
。然后,当您发现更低或更高的值时,将这些值重置为较新的值并继续,直到不再有输入。
继续读取值和名称,设置适当的值,直到完成。然后打印结果。
这是一个示例。
if (val > highest) {
highest = val;
highname = currentName;
}
此外,您可以执行以下操作,而不是使用单独的变量 i
来确定何时停止:
while (a-- > 0) {
// rest of your code here.
}
关于java - 如何获取多项参赛作品的最高分和最低分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59036243/