Using Bufferedreader.Readline() in a While Loop Properly

Using BufferedReader.readLine() in a while loop properly

You're calling br.readLine() a second time inside the loop.

Therefore, you end up reading two lines each time you go around.

BufferedReader readLine used in while loop

I hope I get your question right. You would like to know how BufferedReader determines where to continue reading within the loop without a counting variable?

If you take a look inside BufferedReader.class you will see a private int pos; counter that is incremented every time a char is read from the stream, e.g. in public int read(). Same is happening in readLine() with the difference that pos is incremented until the end of the line is reached.

You can reset the internal counter using reset() function (this is to the last mark location, see here for details).

While loop & BufferedReader

It isn't exactly clear what you're trying to do, as you seem to be reading in from the console multiple times inside the while loop. However, this will allow the loop to terminate when a q or Q has been entered in by the user via the console:

String inputString = "";

//assign the trimmed user input line to inputString and check if it equals q ignoring case
while ((inputString = BR.readLine()) != null && (!inputString.equalsIgnoreCase("q"))) {
//do stuff with inputString in while loop
}

If you can add more details, I can add more to the answer.

Update

After your clarification in the comments about what you want, I changed only the loop to do what you want, and placed the variables (that you had inside the while loop) outside:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.NumberFormat;

public class CST200_Lab2 {

public static void main(String[] args) throws Exception {
String inputString = "";

double hullSpeed;
double displacementEqu;
double sailAreaEqu;
double capSize;
double comfortIndex;

// declare variables outside the loop to be preserved
// initialize at -1 because length and area can't be negative
// and because my compiler requires initialization
double lengthVesselDbl = -1;
double waterLineLengthDbl = -1;
double widthVesselDbl = -1;
double displacementDbl = -1;
double sailAreaDbl = -1;

InputStreamReader ISR = new InputStreamReader(System.in);
BufferedReader BR = new BufferedReader(ISR);

NumberFormat NF = NumberFormat.getNumberInstance();
NF.setMaximumFractionDigits(2);
NF.setMinimumFractionDigits(2);

System.out.println("Starting program!");

int i = 1;

// loop and read input, and assign to proper variable
while ((inputString = BR.readLine()) != null && (!inputString.equalsIgnoreCase("q"))) {
try {
switch (i) {
case 1:
lengthVesselDbl = Double.parseDouble(inputString);
break;

case 2:
waterLineLengthDbl = Double.parseDouble(inputString);
break;

case 3:
widthVesselDbl = Double.parseDouble(inputString);
break;

case 4:
displacementDbl = Double.parseDouble(inputString);
break;

case 5:
sailAreaDbl = Double.parseDouble(inputString);
break;

default:
System.out.println("Input is not being used. Press Q to exit!");
break;
}
i++;
} catch (NumberFormatException e) {
System.out.println("Please enter a number!");
}
}

// check if variables were assigned properly
if (lengthVesselDbl >= 0 && waterLineLengthDbl >= 0 && widthVesselDbl >= 0 && displacementDbl >= 0
&& sailAreaDbl >= 0) {

// Calculate the Hull Speed
hullSpeed = 1.34 * (Math.pow(waterLineLengthDbl, .5));

// Calculate Displacement to Waterline Length
displacementEqu = (displacementDbl / 2240.00) / Math.pow((.01 * waterLineLengthDbl), 3);

// Calculate Sail Area to Displacement
sailAreaEqu = sailAreaDbl / Math.pow((displacementDbl / 64.00), .67);

// Calculate the Capsize index.
capSize = widthVesselDbl / Math.pow((displacementDbl / 64.00), .33);

// Calculate the Comfort index
comfortIndex = (displacementDbl)
/ (.65 * (.7 * waterLineLengthDbl + .3 * lengthVesselDbl) * Math.pow((widthVesselDbl), 1.33));

// Print out the User input
System.out.println("LOA: " + NF.format(lengthVesselDbl));
System.out.println("LWL: " + NF.format(waterLineLengthDbl));
System.out.println("BEAM: " + NF.format(displacementDbl));
} else {
throw new Exception("Dimensions weren't initialized!");
}
}
}

Since you said it's assumed the user knows when to enter what dimension or value, I made switch statement so that based on the iteration of the loop, the user inputted value gets assigned to the proper variable, since each iteration the user input is read in. After the 5th iteration, nothing happens with the user provided inputs, and the loop terminates once the user enter a Q.

Why doesn't my BufferedReader that reads while readLine!=null work?

For each (successful) iteration of the loop, you're reading two lines - one in the while condition, and then another one in the loop's body. The line read in the loop's condition is discarded, and thus you see the missing line.

Instead, you can store the line in a variable in the loop's condition, and then use it in the loop's body:

String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}

Can't exit while loop in Java when extracting lines from BufferedReader

The problem appears to be that your Reader is wrapped around a blocking Socket, which will not indicate end-of-stream until the peer closes the connection (or your side closes the connection). You may have read all that's available, but when you try to read more, the underlying InputStream blocks trying to read more data from the socket.

When some data eventually becomes available, the InputStream will make that data available to the Reader, and, once the Reader has seen enough to constitute a complete line—or end-of-stream—you'll get your last line back out of the Reader. Trying to read the next line would finally return null.

java nested while loop using readline

it's the ; behind the if

if(temp2.equals(temp1));

But it wouldn't probably work anyway as expected, since you must reopen file 2 within the outer loop, otherwise it will only work correctly for the first line of file 1

How can I close BufferedReader in the while loop

How can I close BufferedReader in the while loop

You are closing it in the while loop, and that's the problem.

Open it before the loop, and don't close it at all, as it's wrapped around System.in, which can't be reopened.



Related Topics



Leave a reply



Submit