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,272
  • 4
  • 28
  • 49
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,483
  • 1
  • 20
  • 33
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
  • 972
  • 12
  • 23