gpt4 book ai didi

Java n 数组中最年轻和最老的

转载 作者:行者123 更新时间:2023-12-02 12:17:44 26 4
gpt4 key购买 nike

我编写了一个程序,根据我输入的年龄和姓名查找最年长和最年轻的人。问题是,程序只给了我最年长的人,最小的人的 else if 语句不执行。

public class Boo {

public static void main(String[] strings) {

int[] age = new int[10];
String[] name = new String[10];
int count = 0;

Scanner in = new Scanner(System.in);

boolean notDone = true;

int smallest = age[0];
int largest = age[0];

String smalName = "";
String larName = "";


do {


System.out.println("Enter name");
name[count] = in.next();



if (!name[count].equalsIgnoreCase("done")) {
System.out.println("Enter age");
age[count] = in.nextInt();

if (age[count] > largest) {
largest = age[count];
larName = name[count];
}
else if (age[count] < smallest) {
smallest = age[count];
smalName = name[count];
}

}
else if (name[count].equalsIgnoreCase("done")) {
notDone = false;
}

count++;

}while(notDone && count < 3);

最佳答案

您的 smallest 变量将被实例化为 0,因为您将其设置为 age[0],它是一个整数数组已经被初始化为默认值 0。

在您首次将年龄作为输入后,尝试将其设置为 age[0],然后进行比较。

int smallest = age[0];
int largest = age[0];
do
{
System.out.println("Enter name");
name[count] = in.next();
if (!name[count].equalsIgnoreCase("done"))
{
System.out.println("Enter age");
age[count] = in.nextInt();

if (count == 0)
{
smallest = age[0];
largest = age[0];
larName = name[0];
smalName = name[0];
}
else
{
if (age[count] > largest)
{
largest = age[count];
larName = name[count];
}
if (age[count] < smallest)
{
smallest = age[count];
smalName = name[count];
}
}
}
else if (name[count].equalsIgnoreCase("done"))
{
notDone = false;
}

count++;

} while (notDone && count < 3);

关于Java n 数组中最年轻和最老的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46037784/

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