1

How can I store a sentence from a file to a string, and then store the next line, which is made up of numbers, to a string?

When I use hasNextline or nextLine, none of it works. I am so confused.

     Scanner kb = new Scanner(System.in);
     String secretMessage = null;
     String message, number = null;
     File file = new File(System.in);
     Scanner inputFile = new Scanner(file);

     while(inputFile.hasNext())
     {
           message = inputFile.nextLine();
           number = inputFile.nextLine();
     }


     System.out.println(number + "and " + message);
Joshua Dwire
  • 5,415
  • 5
  • 29
  • 50
John smith
  • 11
  • 3

2 Answers2

0

You're looping over the entire file, overwriting your message and number variables, and then just printing them once at the end. Move your print statement inside the loop like this so it will print every line.

       while(inputFile.hasNext())
       {
           message = inputFile.nextLine();
           number = inputFile.nextLine();
           System.out.println(number + "and " + message);
       }
alexroussos
  • 2,671
  • 1
  • 25
  • 38
  • okay, but how do i do the filereader, its not working for me i have to do it like this in the command prompt message < message.txt, – John smith Oct 07 '13 at 01:20
  • Using input redirection (the '<') is not how I would typically read from a file in Java. Generally, you would take the filename as an argument, open it, read from it, then close the file. Run your program as "java MyProgram filename.txt" and then inside your program, access "filename.txt" as args[0] in your main. Here's an example: http://stackoverflow.com/questions/4716503/best-way-to-read-a-text-file . – alexroussos Oct 08 '13 at 02:04
  • If you're hellbent on reading the file with '<' for whatever reason, you can try the code in this question which definitely works and BufferedReader instead of a Scanner. http://stackoverflow.com/questions/5918525/piping-input-using-java-using-command-line – alexroussos Oct 08 '13 at 02:15
0

One suggestion I would have for reading lines from a file would be to use the Files.readAllLines() method.

import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

public class Display_Summary_Text {

public static void main(String[] args)
{
    String fileName = "//file_path/TestFile.txt";

    try
    {
        List<String> lines = Files.readAllLines(Paths.get(fileName), Charset.defaultCharset());
        String eol = System.getProperty("line.separator");
        for (int i = 0; i <lines.size(); i+=2)
        {
            System.out.println(lines.get(i).toString() + "and" + lines.get(i+1) + eol);
        }
    }catch(IOException io)
    {
        io.printStackTrace();
    }
}
}

Using this set up, you can also create a stringBuilder and Writer to save the output to a file very simply if needed.

Swagin9
  • 1,002
  • 13
  • 24