【发布时间】:2020-08-30 20:58:54
【问题描述】:
我有 3 个数组。一个计算人口,一个使用 arrays.sort 对人口进行排序,另一个存储字符串。我想基本上将字符串从最低到最高排序。知道一个群体的存储位置与一个字符串的存储位置相同,我尝试将排序后的值与这样的群体相匹配,它似乎按照我编写它们的顺序输出字符串。我哪里做错了?
import java.util.Arrays;
public class test {
public static void main(String [] args){
Scanner input = new Scanner(System.in);
int Lvalue = 0;
int max = 0;
int min = 0;
int Svalue = 0;
System.out.println("How many countries will be entered");
int num = input.nextInt();
String[] country = new String[num];
int[] population = new int[num];
int[] popsort = new int[num];
String[] capital = new String[num];
for(int i = 0; i < num; i++)
{
System.out.println("Please enter the name of the country");
country[i] = input.next();
System.out.println("Please enter the country population");
population[i] = input.nextInt();
popsort[i] = population[i];
System.out.println("Please enter the country capital");
capital[i] = input.next();
}
for (int i = 0; i < num; i++)
{
if (population[i] > max)
{
max = population[i];
Lvalue = i;
}
}
for (int i = 0; i < num; i++)
{
if (population[i] < max)
{
min = population[i];
Svalue = i;
}
}
System.out.println("The country with largest pop is : " + country[Lvalue] + " ");
System.out.println("The country with smallest pop is : " + country[Svalue] + " ");
Arrays.sort(popsort);
for(int i = 0; i < num; i++)
{
for (int j = 0; j < num; j++)
{
if (popsort[j] == population[i])
{
System.out.println(country[i]);
}
}
}
}
}
【问题讨论】:
-
请正确格式化您的代码。空白行使您的代码难以阅读。
-
是的,我现在就这样做
-
您的
min计算不正确。仅仅因为一个值小于最大值并不意味着它是最小值。例如,输入人口为 10、20 和 30 的 3 个国家。结果将告诉您第二个国家(人口 20)是最小值。如果您愿意,您实际上可以删除最小/最大循环并在输入期间跟踪这些值。 -
另一个附注 - 您的文本条目只允许一个单词。使用,例如
country[i] = input.next(); country[i] += input.nextLine();允许多个单词(大写相同)