Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Help with System.in.read() function

Status
Not open for further replies.

Wunderbar

Programmer
Aug 14, 2000
6
0
0
CA
Hi,
I'm writing a program with a do while loop..ending on the condition that the user doesn't enter 'c' or 'C' but after the second iteration, the program just ends after asking the user to enter c or C to continue. here's what I have:

import java.io.*;
import javax.swing.*;
import java.text.DecimalFormat;

public class CalculatingPI
{
public static void main ( String args[] ) throws IOException
{
int numberOfTerms, counter;
float denominator;
double calculation;
String inputValues;
char aLetter;

do {

counter =1;
calculation = 0;
denominator = 0;


inputValues = JOptionPane.showInputDialog(
"Please enter the number of terms to be calculated: " );
numberOfTerms = Integer.parseInt( inputValues );

System.out.println(numberOfTerms);
System.out.print ("Enter C to continue, any other key to end: ");
aLetter = (char)System.in.read();
}while (( aLetter == 'c') || (aLetter == 'C'));
System.exit(0); //terminate the program
} [sig][/sig]
 
The [tt]System.in.read()[/tt] command gets the entire input which will be a 'c' character and a 'return' character. Therefore, the next time round the loop it applies 'return' as your input and quits.

To prove this try entering 'ccc' for continue and it will works for three loops.

Right after [tt]aLetter = (char)System.in.read();[/tt] you could skip the input chars with...

System.in.skip(System.in.available());
[sig]<p> <br><a href=mailto: > </a><br><a href= home</a><br> [/sig]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top