Reading input from a file, Scanner.nextLine() produces blank result - java

So, my end goal is to use an input file to instantiate an ArrayList of Letter objects. The file contains multiple cases of the following format:
from-to
line 1
...
line n
(*** is used as an indicator of a new letter. There are no blank lines between input lines, in other words, each line is followed immediately by a return and then the next line.)
Yet before I even attempt to instantiate multiple Letter objects, I am just trying to get the first one to work.
Scanner in = new Scanner(_file).useDelimiter("\\s+?|-");
ArrayList<Letter> letters = new ArrayList();
String from = in.next();
String to = in.next();
Letter temp = new Letter(from,to);
String s = in.next();
temp.addLine(s);
Where a Letter object takes two strings for the recipient and writer and can then have lines added to it. So my output should be:
Dear Recipient:
Line 1
...
Line n
Sincerely,
Writer
But when I use this my output is:
Dear Recipient:
Sincerely,
Writer

The documentation Scanner.nextLine() says this:
Advances this scanner past the current line and returns the input that
was skipped. This method returns the rest of the current line,
excluding any line separator at the end. The position is set to the
beginning of the next line.
So what the method actually does is give you whats left on that line only
So, you need to do this:
Scanner in = new Scanner(_file).useDelimiter("\\s+?|-");
ArrayList<Letter> letters = new ArrayList();
String from = in.next();
String to = in.next();
Letter temp = new Letter(from,to);
in.nextLine(); // <-- this is extra
// now we're ready to read the rest of the stuff
String s = in.nextLine();
temp.addLine(s);

Related

Java how to make the given piece display the whole row, not just the last word where it remained

This code finds the first word "horror", but does not show me the whole line, only the word found.
File f = new File("MyFile.txt");
Scanner scan = new Scanner(f);
while (scan.hasNextLine()) {
String str = scan.next();
if (str.contains("horror")) {
System.out.println(str + " este horror");
}
}
Why is that?
The Scanner class has many methods for reading different types, and each has a corresponding hasNext...() method, for example nextInt() and hasNextInt(). You checked hasNextLine(), but used next() which returns the next word instead of nextLine() which returns the next line.
Change your code from:
String str = scan.next(); // read next word ❌
to:
String str = scan.nextLine(); // read next line ✅

How does removing the first word out of a scanned string sentence work with the Scanner class?

The assignment is:
Write a Java program that reads a sentence in one go as a String, and
writes this sentence back to the screen without the first word. For
instance:
Give Your Sentence: The Great Gonzo
Great Gonzo
Underneath is the code. But how does the scanner class remove the first word? I don't quite understand. If could give an explanation, or provide some resources as to how this code removes the first word, that'd be great. Thx a lot. Here's the code:
Scanner scan = new Scanner(System.in);
System.out.print("Geef je zin : ");
String input = scan.nextLine(); //Input contains entire sentence
System.out.println("\n" + input);
scan.close();
//butfirst
Scanner scan2 = new Scanner(input);
String word = scan2.next();
String rest = scan2.nextLine();
System.out.println("-> " + rest);
scan2.close();
//butsecond
Scanner scan3 = new Scanner(input);
word = scan3.next();
String word2 = scan3.next();
rest = scan3.nextLine();
System.out.println("-> " + word + rest);
scan3.close();
well, key is
String word = scan2.next();
it consumes the first word so next call scan2.nextLine() return everything except first word. Output from scan2.next() (first word) is actually useless, it is not used anywhere, it is called only to move "scanner internal pointer" by one word.
However there are, of course, much better solutions.
next() reads input until it encounters the delimiter which is space ("") (by default, but I believe it can be changed)
nextLine() reads input until it encounters a new line (\n) or a 'ENTER'
and when your input is read the cursor is now at a new line
Ex:
input = "Geef je zin";
next() = "Geef" and the cursor would be at j, so calling nextLine() would give you "je zin" and the cursor would be at a new line
input = "Geef je zin";
nextLine() = "Geef je zin" reads the whole line
I'm not very good with explanations but there's a well written article on geeksforgeeks:
www. geeksforgeeks. org/ difference-between-next-and-nextline-methods-in-java
scan2.next() moves the Scanner's internal "pointer" forward by one word up to the first space, and returns the word. scan2.nextLine() returns the rest of the line and moves the pointer to the next line. In the example, | represents the pointer:
scan.next(): The|Great Gonzo
returns first word
scan.nextLine(): The Great Gonzo
|
returns the rest of the line starting from the previous pointer position

Is there a way around not advancing a line with Scanner (Java)

Okay so I'm having a slight problem with scanner advancing an extra line. I have a file that has many lines containing integers each separated by one space. Somewhere in the file there is a line with no integers and just the word "done".
When done is found we exit the loop and print out the largest prime integer that is less than each given integer in each line(if integer is already prime do nothing to it). We do this all the way up until the line with "done".
My problem: lets say the file contains 6 lines and on the 6th line is the word done. My output would skip lines 1, 3 and 5. It would only return the correct values for line 2 and 4.
Here's a snippet of code where I read the values in:
Scanner in = new Scanner(
new InputStreamReader(socket.getInputStream()));
PrintStream out = new PrintStream(socket.getOutputStream());
while(in.nextLine() != "done"){
String[] arr = in.nextLine().split(" ");
Now I sense the problem is that the nextLine call in my loop advances the line and then the nextline.split call also advances the line. Thus, all odd number lines will be lost. Would there be another way to check for "done" without advancing a line or is there a possible command I could call to somehow reset the scanner back to the start of the loop?
The problem is you have 2 calls to nextLine() try something like this
String line = in.nextLine();
while (!"done".equals(line)) {
String[] arr = line.split(" ");
// Process the line
if (!in.hasNextLine()) {
// Error reached end of file without finding done
}
line = in.nextLine();
}
Also note I fixed the check for "done" you should be using equals().
I think you are looking for this
while(in.hasNextLine()){
String str = in.nextLine();
if(str.trim().equals("done"){
break;
}else{
String[] arr = str.split("\\s+");
//then do whatever you want to do
}
}

Parsing a text file string by string in java

So I'm having a problem with parsing a text file. Let's say I have a text file with contents like this(all strings are separated by a space and all lines after line 1 only contain 2 strings):
a b c d e
a b
c d
I need to process the first line one string at a time. That is "a"(then use a for a method) then "b"(use b for a method) and so on.
After this, I need to process lines 2 and 3 in a different way. Read line 2, store "a" in a variable as e1, then process "b" and store b in a variable e2. Then I need to use e1 and e2 for a separate method. All lines after line 1 do the same thing as I just described.
My problem is that my code is just reading the whole line and storing that as the variables. Thus, I'm not reading each individual string. Also, I don't understand how to tell when I'm done processing line 1(this is important because I use a different method for all lines after line 1). Here's what I have:
Scanner scan = new Scanner(new File(args[0]));
while(scan.hasNext()){
String input = scan.nextLine();
t.addV(input);
}
while(scan.hasNext()){
String e1 = scan.next();
String e2 = scan.next();
t.addE(e1, e2);
}
I know this is very wrong but I'm just looking to understand how I would know when I'm done reading line 1 and how I would just read each individual string.
You are really close, just a couple things off.
Step 1: getting the first line and calling a method for each individual letter
String firstLine = scan.nextLine();
// splits the line into a letter array
String[] letters = firstLine.split("\\s");
for(String letter: letters){
// do your method
}
Step 2: Getting the two individual letters and calling methods depending on the letter:
while(scan.hasNextLine()){
String line = scan.nextLine();
String[] lets = line.split("\\s");
String e1 = lets[0];
String e2 = lets[1];
// do your methods with the individual letters
}
You could of course use scan.next() to retrieve one letter at a time, but it seems by the way you worded your question that the line that the letters are on is needed knowledge to the method call. Which is why I've also assumed that there are a maximum of two letters per line on subsequent lines.
I recommend you using an BufferedReader, to read a file line by line
try (BufferedReader reader = new BufferedReader(new FileReader(args[0]))) {
String firstLine = reader.readLine();
//Process with the first line
String secondLine = reader.readLine();
//Process with the second line
} catch (Exception ex) {
}
Edit
To get the elements within a line, use the String.split(String delimiter) method.
Like this:
String[] splittedElements = line.Split(" ");

Java console read input line by line and store in String array

I have a question regarding reading strings from java console. When I give input of words each line until I stop with "stop" All those words should be stored in one array of string.
My input will be:
apple
Mango
grapes
stop -----> on stop the string ends here
All the 3 fruit names will be stored in temp.
But when I type one word and want to type another by clicking enter to go to next line, it prints the output.
How should I modify this?
Scanner scanner=new Scanner(System.in);
System.out.println("Enter the words");
String temp=scanner.nextLine();
Your problem is that you're reading one line from console and print it.
What you should do is keep reading lines until "stop", and that could be done by having a while loop.
This code should work well for you:
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the words");
String input = scanner.nextLine(); // variable to store every input line
String fruits = ""; // this should store all the inputs in one string
while(! input.equals("stop")) {
fruits += input + ","; // using comma to separate the inputs
input = scanner.nextLine();
}
String[] res = fruits.split(","); // splitting the string to have its content in an array

Categories

Resources