程序在比较时输出一堆空值。我想我没有正确比较,虽然我已经尝试了==并且没有输出任何东西。下面是代码,下面是NameAgeOcc.txt
import java.util.Scanner;
import java.io.*;
public class MoreSelectionSortAndParallelArrays
{
public static void main(String[] args)
{
Scanner inputStream = null;
try
{
inputStream = new Scanner(new FileInputStream("NameAgeOcc.txt"));
}
catch(FileNotFoundException error)
{
System.out.println("Unable to open input file.");
System.exit(0);
}
int length=inputStream.nextInt();
int ages [] = new int[length];
String names [] = new String[length];
String occupations [] = new String[length];
String junk= inputStream.nextLine() ;
int i;
for(i=0;i<length;i++)
{
names[i]=inputStream.nextLine();
ages[i]=inputStream.nextInt();
junk=inputStream.nextLine();
occupations[i]=inputStream.nextLine();
}
System.out.printf("%-25s%-8s%24s%n","Names"," Ages","Occupations");
for(i=0;i<length;i++)
{
System.out.printf("%-25s%6d%24s%n",names[i],ages[i],occupations[i]);
}
String Temp, Temp3;
int minVal,minPos,y,Temp2;
for(i=0;i<length;i++)
{
minVal=ages[i];
minPos=i;
for(y=i+1;y<length;y++)
{
if(ages[y]<minVal)
{
minVal=ages[y];
minPos=y;
}
}
Temp2 = ages[minPos];
ages[minPos] = ages[i];
ages[i] = Temp2;
Temp = names[minPos];
names[minPos] = names[i];
names[i] = Temp;
Temp3 = occupations[minPos];
occupations[minPos] = occupations[i];
occupations[i] = Temp3;
}
System.out.println();
System.out.printf("%-25s%-8s%24s%n","Names"," Ages","Occupations");
for(i=0;i<length;i++)
{
System.out.printf("%-25s%6d%24s%n",names[i],ages[i],occupations[i]);
}
int studentCount=0;
for (i=0;i<length;i++)
{
if(occupations[i].equalsIgnoreCase("student"));
studentCount++;
}
int studentAges [] = new int[studentCount];
String studentNames [] = new String[studentCount];
System.out.printf("%-25s%-8s%n","Names"," Ages");
for (i=0;i<studentCount;i++)
{
System.out.printf("%-25s%6d%n",studentNames[i],studentAges[i]);
}
inputStream.close();
}
}
.txt
15
Smith, John
26
Baker
Jones, Susan
15
Student
Mouse, Mickey
31
Theme park employee
Mouse, Mighty
48
Cartoon super hero
Anderson, William
35
Computer Programmer
Parker, Cindy
18
Author
McCain, John
20
Student
Armstrong, Michelle
17
Student
Thompson, Anne
29
Doctor
Li, Steve
15
Student
James, Tanya
20
Student
Moore, James
32
Teacher
Andrews, Julie
75
Actress
Obama, Michelle
46
Lawyer
Michaels, Todd
51
Student
确保复制.txt末尾的空行(点击输入或返回)
答案 0 :(得分:0)
我已经简要检查了你的代码,我发现了这个:
if(occupations[i].equalsIgnoreCase("student"));
studentCount++;
“;”在“if”结尾处导致studentCount总是递增。
当然,您的代码可能会出现更多错误。如果您希望别人帮助您,您应该解释您的计划正在做什么。
答案 1 :(得分:0)
程序会输出一堆空值,因为您正在创建studentAges
和studentNames
,但您没有在其中添加内容。
@PawełAdamski的回答不正确
if(occupations[i].equalsIgnoreCase("student"));
studentCount++;
表示您总是在增加studentCount
。
我建议你使用一些内部类,而不是使用Arrays.sort()
进行排序(你必须实现Comparable接口或实现Comparator接口进行排序)。