0

Code

public class Login {

    private String nickname;
    private static String line;

    public Login(String nickname) throws IOException {
        this.nickname = nickname;

        try {
            Scanner input = new Scanner(new File(nickname + ".acc"));
            while (input.hasNextLine()) {
                line = input.nextLine();
            }
            input.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[]args) throws IOException {
        new Login("example");
        System.out.println(line);
    }
}

I have a problem. If I use this code, my output will only say 34567. But my text file contains:

example
34567

How do I fix it, and is it possible that the scanner outputs both lines of text from the textfile to separate strings?

Community
  • 1
  • 1
  • You could also use **[InputStream](http://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html)** for reading the file, instead of `Scanner` – Ramiz Wachtler Oct 28 '15 at 20:21

4 Answers4

3

Your problem lies in this bit of code:

// loop until the input has no more lines
while (input.hasNextLine()) {
    // PLACE the current line from the file into the line variable
    line = input.nextLine();
}

You will always be overwriting the line variable with the last line read. This leads to your program only storing the last line of the file.

The simplest fix is to just append the line to the existing variable.

// loop until the input has no more lines
while (input.hasNextLine()) {
    // APPEND the current line from the file into the line variable
    line += input.nextLine() + "\n"; // append a newline...
}

You also will need to initialize the line variable, Above your while loop you can just initialize it to an empty string

line = "";
while(...) ...

This will lead to 1 extra new line in your line variable however. A better way would be to just read the file contents instead of using a scanner, see this question for more information How do I create a Java string from the contents of a file?

Community
  • 1
  • 1
ug_
  • 11,267
  • 2
  • 35
  • 52
  • This works but my output is nullexample 34567 . How do I remove the null? And can I store both lines in to two strings. – Ruben de groot Oct 28 '15 at 20:16
  • Thanks alot, but can I store both lines of my string 'line', into two strings? (I am not so old yet, and not really an advanced Java coder) – Ruben de groot Oct 28 '15 at 20:49
  • @Rubendegroot use a String array – Frakcool Oct 28 '15 at 22:24
  • @Frakcool I don't now which code to use (I am not so good in Java yet) – Ruben de groot Oct 29 '15 at 15:25
  • @Rubendegroot use a `List`, look up "How to use lists in Java" in your favorite search engine and start reading. One of the most valuable skills in programming (and many other aspects of life) is how to use the tools available to help yourself learn. In this day and age that generally means using the internet to research. It will take time but honestly the more time it takes the more you will remember it. Most people will tell you the problems they spent the most time trying to solve are the ones they most remember. – ug_ Oct 29 '15 at 15:31
  • @Rubendegroot see my answer, there's the code you were asking for. 1 variable for each line (not actually 1 variable for each line, but 1 element of the array for each line). – Frakcool Oct 29 '15 at 15:57
2
line = input.nextLine();

Here you are overriding the line you read before. You could just add the new line to your line variable like this:

line += input.nextLine();

If you want a line break after each line you read, you can add the newline character at the end of each line:

line += input.nextLine() + "\n";
JNK
  • 796
  • 6
  • 12
0

The problem here is with your while loop. while (input.hasNextLine()) tells the program to run the loop until the Scanner reaches the last line in the file. Since the only line of code within the loop sets the value of line to equal the next line of text in the file, it will simply keep changing the value of line until it reaches the last line. The simplest solution to fix this would be to move System.out.println(line) to be inside of the while loop, following line = input.nextLine().

Alternatively, if you wish to keep the println() method within your main method, you could have your while loop store each line of text into an ArrayList<String> and then have a for loop in the main method to iterate through it and print each element, but that would require making the code more complex than simply moving one line of code and would result in the exact same output anyway.

Bethany Louise
  • 646
  • 7
  • 13
0

From your comment:

can I store both lines of my string 'line', into two strings?

I made this, using a String array. You should use a List because of performance, as @ug_ suggested

The following example shows how to use the String array. I'll suggest you to try using a List yourself, so you learn something new.

The last part is commented, since, as you said you're a Java starter you're maybe be more familiar with a for-loop instead a for-each loop, both for loops in the code work exactly the same way. I recommend you to learn about both them too.

Edit

As of @ug_ comment I made a new approach which ended being an edit to his own answer. (So his answer is actually the correct one). It adds a new line \n after it reads each line on the file, then it splits by this line break and stores it into an array, after that it just prints it out:

import java.util.Scanner;
import java.io.*;
public class Login {

    private String nickname;
    private static String lines[];

    public Login(String nickname) throws IOException {
        this.nickname = nickname;

        try {
            Scanner input = new Scanner(new File(nickname + ".acc"));
            String line = "";
            while (input.hasNextLine()) {
                line += input.nextLine() + "\n"; //Add a new line to our string
            }
            lines = line.split("\n"); //Split the string and store it into the array
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[]args) throws IOException {
        new Login("example");
        for (String s : lines) { //print each element of the array.
            System.out.println(s);
        }
        /*for (int i = 0; i < lines.length; i++) {
            System.out.println(lines[i]);
        }*/
    }
}

The output is:

example
34567
Community
  • 1
  • 1
Frakcool
  • 10,915
  • 9
  • 50
  • 89
  • I love the thought but do we really need to show OP that its okay to read the file in 2 times just so you can get the size of the array you need? We have a great tool for that.... They are called Lists, their size dynamically changes as you add and remove items. If you dont wanna go the List route just use the `String.split` method and split it on new lines. Reading the file in 2x is really unacceptable. – ug_ Oct 29 '15 at 16:00
  • @ug_ hmm you're right! Never thought about `String.split`. I wanted to use arrays since (imo) it's easier to understand than Lists for a Java beginner. I'll update my code asap with `String.split`. However I'm still recommending the use of Lists on my answer and I'll update it too so I suggest OP that it's the most efficient way to go through his problem. Thanks for your comment – Frakcool Oct 29 '15 at 17:24
  • @ug_ See edit. I guess it's better now. However Lists are still the best approach. – Frakcool Oct 29 '15 at 17:39