gpt4 book ai didi

java - 查找 String 数组中索引处元素的子字符串

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

main 应该分解名字和姓氏,并将姓氏存储在一个新数组中。我的代码中有一个逻辑错误,因为这部分不打印。

package names;
import java.io.*;
import java.util.*;
public class names {

public static void main(String[] args) throws FileNotFoundException {
final int TOTALNAMES=15;
String [] names = new String[TOTALNAMES];
String [] firstname = new String[TOTALNAMES];

//String
File file = new File ("Names12.txt");
Scanner read = new Scanner (file);
printHeading();

int i, cntr=0;
while(read.hasNext()&&cntr<TOTALNAMES){
cntr++;
read.nextLine();
}
String[] name = new String[cntr];
Scanner read1 = new Scanner(file);
for( i = 0; i<name.length; i++) {
name[i] = read1.next();

//System.out.println(name[i]);
}
//creating new string array to hold last name values
int j;
String[] lastname = new String[name.length];
for(j = 0; j < lastname.length; j++){
lastname[j]=names[i].substring(name[i].indexOf(" "+1));
System.out.println(lastname[j]);
}
}

//This method prints the heading centered
public static void printHeading () {
System.out.println("\t\t\t\tTable of Names");
}
//This method reads in the names from the file into an array
public static int readNames(Scanner keyboard, String[]names) throws FileNotFoundException {
int count = 0;
names = new String[15];
for (int i = 0; i < names.length; i++) {
names [i] = keyboard.nextLine();
System.out.println(names[i]);
count++;
}
return count;
}


}


My methods print, but the while loop is silent.

最佳答案

在 while 循环内这一行:

read.nextLine();

执行行读取,但不将其存储在任何地方。
我还看到不需要循环并创建第二个 Scanner 对象,为什么?您需要读取数组 names 中的所有行,然后循环遍历该数组以提取姓氏。
这可以在读取文件时在单个循环中完成,但为了便于阅读,我使用了 2 个循环:

public static void main(String[] args) throws FileNotFoundException {
final int TOTALNAMES = 15;
int cntr = 0;
String [] names = new String[TOTALNAMES];
String [] firstname = new String[TOTALNAMES];
String [] lastname = new String[TOTALNAMES];

File file = new File("Names12.txt");
Scanner read = new Scanner(file);
printHeading();

while(read.hasNext() && cntr < TOTALNAMES){
cntr++;
names[cntr - 1] = read.nextLine();
}

read.close();

for(int i = 0; i < cntr; i++){
//firstname[i] = names[i].substring(0, names[i].indexOf(" "));
lastname[i] = names[i].substring(names[i].indexOf(" ") + 1);
System.out.println(lastname[i]);
}
}

关于java - 查找 String 数组中索引处元素的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56069923/

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