gpt4 book ai didi

java - 比较字符串数组输出 Null

转载 作者:行者123 更新时间:2023-12-01 05:24:02 25 4
gpt4 key购买 nike

程序在比较时输出一堆空值。我认为我没有正确比较,尽管我已经尝试过 == 并且没有输出任何内容。下面是代码,下面是 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 末尾的空行(按 Enter 或 Return)

最佳答案

程序输出一堆空值,因为您正在创建 studentAgesstudentNames ,但你没有往里面放东西。

@Paweł Adamski 的答案不正确

if(occupations[i].equalsIgnoreCase("student"));
studentCount++;

意味着你正在增加studentCount总是。

我建议您使用一些内部类,而不是使用 Arrays.sort()用于排序(您必须实现 Comparable 接口(interface)或实现 Comparator 接口(interface)进行排序)。

关于java - 比较字符串数组输出 Null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9938567/

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