简体   繁体   中英

storing a sentence from a file to a string java

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);

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM