Frage

At school we are learning to code a program that will read a persons full name out of a text document named "Names.txt" . We have to make the name in the folder output the first letter of the first name and then the full surname. All this must be under our basic knowledge of while loops, for loops, if else statements and booleans. I am having trouble with my code:

Scanner scFile = new Scanner (new File ("Names.txt"));

    String line =  "", name = "";

    int num, sum = 0;
    while (scFile.hasNext())
    {
        Scanner scLine = new Scanner (line).useDelimiter("#");
        name = scLine.next();
        num = scLine.nextInt();

        scLine.close();


        System.out.println(name.substring(0,1) + "\t" + num);
        sum = sum+ num;
    }
    scFile.close();

    System.out.println("The sum is " + sum);
War es hilfreich?

Lösung

This is simple can get it from google, As you consider as school student given below code to try with your work. It will work as per your requirement..

    BufferedReader reader = new BufferedReader(new FileReader("D:/Names.txt"));
    String line = null;

    while ((line = reader.readLine()) != null)
    {
        System.out.println(line);
        String[] lastName = line.split("\\s");

        String firtLetterOfFirstName = lastName[0].substring(0, 1);
        System.out.println("Folder Name : "+firtLetterOfFirstName + lastName[1]);
        File file = new File("D:\\"+firtLetterOfFirstName + lastName[1]);
        if(false== file.exists())
        {
            file.mkdir();
        }

    }

Andere Tipps

\\s

is the space delimiter. So try this:

    Scanner scLine = new Scanner (line).useDelimiter("\\s");
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top