Reading lines from System.In without an endline character - java

I'm reading from System.in, and I'm using the Scanner class. My problem is when I use redirection the last line in the file is not being read. I read the documentation for Scanner.readLine, and I'm guessing it's because it does not have a "end of line" character. Any idea what I can use instead to get this last line?
In my code input is "".
Scanner scanner = new Scanner(System.in);
int sizeOfList = scanner.nextInt();
ArrayList<Integer> arrayList = new ArrayList<Integer>();
String input = scanner.nextLine();
System.out.println(input);
String[] splitInput = input.split(" |\\n");
for(int i = 0; i < splitInput.length; i++)
{
System.out.println(splitInput[i]);
arrayList.add(new Integer(Integer.parseInt(splitInput[i])));
}

instead of scanner.nextLine(), you could use scanner.next() .... This will get a string from the scanner when it does not have an end of line character.
You can also call scanner.hasNextLine() to check if you have reached the line at the end that you are worried about!

Related

Why is the file reading the last line of a row and the first one of the second row

While reading a Excel CSV file using a scanner with a comma delimiter, its reading the last node in the first row but also reading the first node of the next row at the same time.
int counter = 0;
String[] u = new String[3];
for (int j = 1; j <= 3; j++) {
String a = in.next();
u[counter] = a;
counter++;
}
}
After using Debugger, I noticed when it reached to the last element it combined them making something like -14256\r\n-14323
-14256 = Last element of first row
-14323 = First element of next row
The scanner took only the comma as the delimiter. But you want it to accept also the end of a line as another delimiter.
I assume that you instantiate the Scanner like this, using Scanner::useDelimiter:
Scanner s = new Scanner( inputStream ).useDelimiter( "," );
If I get the Pattern definition right, it should be:
Scanner s = new Scanner( inputStream ).useDelimiter( ",|\\R" );
The \R stands for
Linebreak matcher: Any Unicode linebreak sequence, is equivalent to \u000D\u000A|[\u000A\u000B\u000C\u000D\u0085\u2028\u2029]
Refer to the documentation for java.util.regex.Pattern for the details.
A CSV file contains lines of text where each line contains values separated by commas. Hence I suggest that you read the file line by line and then split each line on the commas. Something like...
java.io.FileReader fr = new java.io.FileReader("path to file");
java.io.BufferedReader br = new java.io.BufferedReader(fr);
String line = br.readLine();
while (line != null) {
String[] fields = line.split(",");
// Add code here to handle the "fields".
line = br.readLine();
}
Note that the above code is not a complete solution but a starting point. For instance, I haven't closed the BufferedReader.

java.util.Scanner doesn't read empty line

I wrote a .txt file in which each line has a meaning - even an empty one. Scanner's methods next() and nextLine() do not recognize the empty line and jump right to the line with text. I'm wondering if there is a way for the scanner to consider all lines of text regardless the content.
I don't want to use BufferedReader because I'm working with very small tokens each time.
static final String fileName = "temp.txt";
try {
//System.out.println(Jsoup.connect(url).get());
Document document = Jsoup.connect(url).get();
FileWriter fileWriter = new FileWriter(fileName);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
Elements names = document.select("[id^=CZ]");
for (Element name : names) {
bufferedWriter.write(name.text());
bufferedWriter.write(System.lineSeparator() + System.lineSeparator());
System.out.println(name.text() + '\n');
}
bufferedWriter.close();
Scanner in = new Scanner(new File(fileName));
in.next();
String s = names.first().text();
String h = in.next();
...
At this point Strings s & h should be equal.
The document the scanner is reading starts with an empty line and goes like this:
asdkjasjkdajkdahkdjahdjadhkahdajkdajkdsasdkjasjkdajkdahkdjahdjadhkahdajkdajkdsasdkjasjkdajkdahkdjahdjadhkahdajkdajkdsasdkjasjkdajkdahkdjahdjadhkahdajkdajkdsasdkjasjkdajkdahkdjahdjadhkahdajkdajkdsasdkjasjkdajkdahkdjahdjadhkahdajkdajkdsasdkjasjkdajkdahkdjahdjadhkahdajkdajkdsasdkjasjkdajkdahkdjahdjadhkahdajkdajkdsasdkjasjkdajkdahkdjahdjadhkahdajkdajkdsasdkjasjkdajkdahkdjahdjadhkahdajkdajkdsasdkjasjkdajkdahkdjahdjadhkahdajkdajkdsasdkjasjkdajkdahkdjahdjadhkahdajkdajkds
Again, I have a dynamic file that might have first line empty and when I compare String s with String h they DO NOT equal. nextLine() and next() skip over the first line while it is still a valid element.
nextLine() is the method that you need. Unlinke next(), it does not skip ahead through newlines and white space.
Run this example (demo)
Scanner sc = new Scanner(System.in);
while (sc.hasNextLine()) {
String s = sc.nextLine();
System.out.println("'"+s+"'");
}
on input with empty lines to see that these lines are preserved:
'quick brown'
''
'fox jumps'
'over'
''
'the'
''
'lazy dog'
next() method reads tokens seperated by whitespaces or newline characters on other hand nextLine() reads lines seperated by newline charater.
You can try this:
Scanner scan = new Scanner(file);
while(scan.hasNextLine()){
System.out.println(scan.nextLine());
}

java input string with spaces

I am trying to read some data for a "Question" type, which has an id(int), statement(string) and answer(string). I'am using the code below:
Scanner scanner = new Scanner(System.in);
System.out.print("Id (uniquely!): ");
int id = scanner.nextInt();
System.out.print("Statement : ");
String statement = scanner.next();
System.out.print("Answer: ");
String answer = scanner.next();
If I enter sth like this "Who are you?" for "statement", it doesn't wait to type anything else for "answer" too. But if I do not use spaces in my statement it will work just fine. Also, if I use scanner.nextLine(), instead of scanner.next(), it doesn't work properly; it will allow me to introduce only one string for both statement and answer.
Does anyone have any idea?
try add scanner.nextLine(). It happens because scanner.nextInt() read only that number and not whole line, so rest of that line is still there. And you want to get rid of it so use nextLine() to get on next line.
It may look like this:
Scanner scanner = new Scanner(System.in);
System.out.print("Id (unic!): ");
int id = scanner.nextInt();
//Consume rest of the line
scanner.nextLine();
System.out.print("Enunt : ");
String stat = scanner.next();
System.out.print("Raspuns: ");
String ras = scanner.next();
Change to :
String statement = scanner.nextLine();
String answer = scanner.nextLine();
instead of using scanner.next();
Basically when you want trying to input string with spaces then try to use scanner.nextLine() instead of using scanner.next()
next() can read the input only till the space. It can't read two words separated by space. Also, next() places the cursor in the same line after reading the input.
nextLine() reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine() positions the cursor in the next line.
Here scanner.next() takes token without space. You may try scanner.nextLine()
The reason your code was not working is :that nextInt() reads integer tokens; because of this, the last newline character for that line of integer input is still queued in the input buffer and the next nextLine() will be reading the remainder of the integer line (which is empty).
So you have to implement a nextLine() twice to get your output. As showed below.
Scanner scanner = new Scanner(System.in);
System.out.print("Id (uniquely!): ");
int id = scanner.nextInt();
System.out.print("Statement : ");
scanner.nextLine();
String statement = scanner.nextLine();
System.out.print("Answer: ");
String answer = scanner.nextLine();
or You can Scan a dummy String variable before scanning the original String Variable as shown below:
Scanner scanner = new Scanner(System.in);
System.out.print("Id (uniquely!): ");
String k = ""; //Dummy String Variable
int id = scanner.nextInt();
System.out.print("Statement : ");
k = scanner.nextLine(); // scanning of Dummy variable
String statement = scanner.nextLine();
System.out.print("Answer: ");
String answer = scanner.nextLine();

Jump of Line while Reading words in a txt File with Scanner

I'm reading words in a Scanner, but i need to know if the Scanner changes to the following line. this is for a Progress Bar(counting Lines).
Can you help me? Here is my code:
Pattern pattern = Pattern.compile("[^\\p{Alpha}]+");
try (Scanner sc = new Scanner(file)) {
while (sc.hasNext()) {
sc.useDelimiter(pattern);
long totalLines = countLines(f);//Method that count Lines
System.out.println("Reading " + totalLines + "Lines...");
word = sc.next();//here i need to know if the scanner jumps to next Line or not.
Use hasNextLine() and nextLine() methods available in Scanner class.
iterate over lines.For each line,split that using space and count number of words in that.

How to input a character array at run time, with spaces being read

I want to enter characters in a character array, dynamically, at run time, using java. But I am not able to find any scanner function for it. If i give input as a string and then extract characters from it, then also the spaces are not being read.
Scanner sm=new Scanner(System.in);
String sl=sm.next();
int i;
char ch[]=new char[sl.length()];
ch=sl.toCharArray();
for(i=0;i<sl.length();i++)
{
System.out.print(ch[i]);
}//This gives output Hello for input Hello world
Use .nextLine() instead of .next(), and it should include spaces. The default delimiter for Scanner is whitespace, so if you use .nextLine() instead, it will use the \n for a delimiter, and it will take all the input up until you pressed enter.
Scanner sm = new Scanner(System.in);
String sl = sm.nextLine();
int i;
char ch[] = new char[sl.length()];
ch = sl.toCharArray();
for (i = 0; i < sl.length(); i++) {
System.out.print(ch[i]);
}//This gives output Hello world for input Hello world
try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
char[] line = reader.readLine().toCharArray();
for (char c : line)
System.out.print(c);
} catch (IOException ioe) {
ioe.printStackTrace();
}
May I ask what drove you to use Scanner? It's almost never the right answer.

Categories

Resources