How to read data from System.in to solve the task? - java

I'm working on this item. I did the spell checking algorithm but I have no idea how to read data correctly. When I use this:
StringBuilder text = new StringBuilder();
Scanner sc = new Scanner(System.in);
String temp;
while ((temp = sc.nextLine()).length() > 0){
text.append(temp);
}
/*spell checking algorithm*/
It waits for the empty string.
In this case:
while (sc.hasNext()){
text.append(temp);
}
it doesn't continue to execute the code at all. If I try to read 10000 signs I should type it all.
How could I read data correctly for this task?

Read them from file:
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
//do what you want
}

Related

BufferedReader multiple lines as one String

I am trying to read multiple lines from a file into an ArrayList as a String.
What I aim to do is to make it so the program reads from a file line by line until the reader sees a specific symbol (- in this case) and saves those rows as one single String. the code below makes every row a new string that it later adds to the list instead.
BufferedReader br = null;
br = new BufferedReader(new FileReader(file));
String read;
while ((read = br.readLine()) != null) {
String[] splited = read.split("-");
carList.add(Arrays.toString(splited));
}
for (String carList2 : carList) {
System.out.println(carList2);
System.out.println("x");
}
First, you need to check if the read line contains "-".
If it doesn't, concatenate the line with the previous ones.
If it does, concatenate only the first part of the line with the previous line.
This is a quick implementation:
BufferedReader br = null;
br = new BufferedReader(new FileReader(file));
String read;
String concatenatedLine = "";
while ((read = br.readLine()) != null) {
String[] splited = read.split("-");
// if line doesn't contains "-", splited[0] and read are equals
concatenatedLine += splited[0];
if (splited.length > 1) {
// if read line contains "-", there will be more than 1 element
carList.add(Arrays.toString(splited)); // add to the list
// store the second part of the line, in order to add it to the next ones
concatenatedLine = splited[1];
}
}
Note the output could not be what is expected if a line contains more than one -.
Also, concatenating String using + is not the best way to do it, but I let you find out more about that.
It's not very clear for me what is the output you desire.
If you would like to have each customer on one string without "-"
then you could try the following code:
while ((read = br.readLine()) != null) {
String splited = read.replace("-", " ");
carList.add(splited);
}

Reading CSV file with different row length in java

I try to read all the lines from a CSV file, but not all the lines are the same length. I used this code:
BufferedReader reader = new BufferedReader(new FileReader("C://Users/Balazs/Downloads/numbers.csv"));
String line = "";
while ((line = reader.readLine()) != null) {
String[] szamok = line.split(";");
But if some rows are longer than the ones before, it gives me error.
Any ideas how to solve this in java?
Thanks!
if (szamok.length > 19) {
Integer hetedikSzam = Integer.parseInt(szamok[19]);
hetedikSzam = Integer.parseInt(szamok[19]);
}

Read only ints with BufferedReader from text file - Java

So if I have a txt file like this:
scissors 3
papers 5
staplers 2
How do I only read the integers with a bufferedreader and not using scan.
try {
BufferedReader reader = new BufferedReader(new FileReader("Supplies.txt"));
String line = "";
while((line=reader.readLine())!=null){
System.out.println(line);
}
} catch (IOException ex) {
JOptionPane.showMessageDialog(null, ex);
}
How do I only read the integers with a bufferedreader and not using scan.
Assuming I understand your question, you could use your current code, and add a regular expression to remove everything that isn't a digit before parsing the int value. Like,
while ((line = reader.readLine()) != null) {
int i = Integer.parseInt(line.replaceAll("\\D+", ""));
System.out.println(i);
}
You should close() your reader when you finish with it, otherwise you leak a file handle. I believe the best solution is a try-with-resources. Like,
try (BufferedReader reader = new BufferedReader(new FileReader("Supplies.txt"))) {
// BufferedReader reader = new BufferedReader(new FileReader("Supplies.txt"));

Read all lines with BufferedReader

I want to type a multiple line text into the console using a BufferedReader and when I hit "Enter" to find the sum of the length of the whole text. The problem is that it seems I'm getting into an infinite loop and when I press "Enter" the program does not come to an end. My code is below:
InputStreamReader instream = new InputStreamReader(System.in);
BufferedReader buffer = new BufferedReader(instream);
line= buffer.readLine();
while (line!=null){
length = length + line.length();
line= buffer.readLine();
}
Could you please tell me what I'm doing wrong?
One line of code using Java 8:
line = buffer.lines().collect(Collectors.joining());
The idiomatic way to read all of the lines is while ((line = buffer.readLine()) != null). Also, I would suggest a try-with-resources statement. Something like
try (InputStreamReader instream = new InputStreamReader(System.in);
BufferedReader buffer = new BufferedReader(instream)) {
long length = 0;
String line;
while ((line = buffer.readLine()) != null) {
length += line.length();
}
System.out.println("Read length: " + length);
} catch (Exception e) {
e.printStackTrace();
}
If you want to end the loop when you receive an empty line, add a test for that in the while loop
while ((line = buffer.readLine()) != null) {
if (line.isEmpty()) {
break;
}
length += line.length();
}
JLS-14.15. The break Statement says
A break statement transfers control out of an enclosing statement.
line will not be null when you press enter; it will be an empty string.
Take note of what the BufferedReader JavaDoc says about readLine():
Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.
And readLine() returns:
A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached
So when you press [Enter], you are giving the BufferedReader a new line containing only \n, \r, or \r\n. This means that readLine() will return an empty string.
So try something like this instead:
InputStreamReader instream = new InputStreamReader(System.in);
BufferedReader buffer = new BufferedReader(instream);
line = buffer.readLine();
while( (line != null) && (!line.isEmpty()) ){
length = length + line.length();
line = buffer.readLine();
}
When you only press Enter the return from buffer.readLine(); isn't null it is an empty String.
Therefore you should change line != null to !line.equals("") (You could also change it to line.length() > 0)
Now your code will look something like this:
InputStreamReader instream = new InputStreamReader(System.in);
BufferedReader buffer = new BufferedReader(instream);
line = buffer.readLine();
while (!line.equals("")){
length = length + line.length();
line = buffer.readLine();
}
This should solve your problem. Hope this helped! :)
Since Java 8 you can use BufferedReader#lines method directly on buffered reader.
try (InputStreamReader in = new InputStreamReader(System.in);
BufferedReader buffer = new BufferedReader(in)) {
final int length = buffer.lines().mapToInt(String::length).sum();
System.out.println("Read length: " + length);
} catch (Exception e) {
e.printStackTrace();
}
Snarky answer: what you're doing wrong is only creating 2 objects in Java to do something... if you search, you can probably find a few more classes that extend BufferedReader or ExtendedBufferReader etc., and then it can be real Enterprise Java.
Now that i've gotten that out of my system: more useful answer. System.in is closed when you input EOF, which is Control-D under Linux and I think MacOS, and I think Control-Z plus enter under Windows. If you want to check for enter (or more specifically, two enters... one to finish the last line and one to indicate that you're done, which is essentially how http handles determining when the http headers are finished and it's time for the http body, then #dbank 's solution should be a viable option with a minor fix I'm going to try to make to move the ! inside the while predicate instead of !while.
(Edit #2: realized readLine strips the newline, so an empty line would "" instead of the newline, so now my code devolves to another answer with the EOF bit as an answer instead of comment)
Edit... that's weird, #dbank had answered while I was typing my answer, and I would have stopped had I not though mentioning the EOF alternative. To repeat his code from memory with the edit I was going to make:
InputStreamReader instream = new InputStreamReader(System.in);
BufferedReader buffer = new BufferedReader(instream);
line= buffer.readLine();
while (line != null && !line.equals("")){
length = length + line.length();
line= buffer.readLine();
}
Put every lines into String[] array. and second method get the number of lines contains in text file. I hope this might be useful to anyone..
public static void main(String... args) throws IOException {
String[] data = getLines();
for(String v : data) {
out.println(v);
}
}
public static String[] getLines() throws IOException {
BufferedReader bufferReader = new BufferedReader(new FileReader("C:\\testing.txt"));
String line = bufferReader.readLine();
String[] data = new String[getLinesLength()];
int i = 0;
while(line != null) {
data[i] = line;
line = bufferReader.readLine();
i++;
}
bufferReader.close();
return data;
}
public static int getLinesLength() throws IOException {
BufferedReader bufferReader = new BufferedReader(new FileReader("C:\\testing.txt"));
String line = bufferReader.readLine();
int size = 0;
while(line != null) {
size += 1;
line = bufferReader.readLine();
}
bufferReader.close();
return size;
}
Good example from #Russel Yang (https://stackoverflow.com/a/40412945/11079418).
Use this code, to add also a new line character after each line.
String lines = bufferedReader.lines().map(line -> line + "\n").collect(Collectors.joining());

Using Java scanner get line number

I'm using the code below to compare two file input streams and compare them:
java.util.Scanner scInput1 = new java.util.Scanner(InputStream1);
java.util.Scanner scInput2 = new java.util.Scanner(InputStream2);
while (scInput1 .hasNext() && scInput2.hasNext())
{
// do some stuff
// output line number of InputStream1
}
scInput1.close();
scInput2.close();
How can I output the line number inside the while loop?
Use LineNumberReader on an InputStreamReader. As it is precisely made for that sole purpose.
try (LineNumberReader scInput1 = new LineNumberReader(new InputStreamReader(
inputStream1, StandardCharsets.UTF_8));
LineNumberReader scInput2 = new LineNumberReader(new InputStreamReader(
inputStream2, StandardCharsets.UTF_8))) {
String line1 = scInput1.readLine();
String lien2 = scInput2.readLine();
while (line1 != null && line2 != null) {
...
scInput1.getLineNumber();
line1 = scInput1.readLine();
line2 = scInput2.readLine();
}
}
Here I have added the optional CharSet parameter.
A Scanner has additional tokenizing capabilities not needed.

Categories