在索引

时间:2019-05-10 02:29:58

标签: java string substring indexof populate

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.

2 个答案:

答案 0 :(得分:0)

看来您的问题是您的计数变量和while循环条件。您永远不会在main中分配要计数的值,然后再为j分配值0,然后仅在count时执行while循环

答案 1 :(得分:0)

在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]);
    }
}