/** InputExample - demonstrate interpreting numeric values from
** input from console (System.in)
**/
import java.io.IOException;
public class InputExample {
public static void main( String[] args) {
InputExample example = new InputExample();
System.out.print("enter int values, end with end of file character:");
System.out.flush();
int sum = example.sumIntValues();
System.out.println("Sum is " + sum);
}
public int sumIntValues() {
byte input[] = new byte[80];
int bytesRead ;
String inputString = null;
String trimmedString = null;
int intValue = 0;
int sum = 0;
try {
while (true) {
// Read input bytes and create a String object from them
bytesRead = System.in.read(input);
if (bytesRead < 0) // read returns -1 of no more is available
break;
inputString = new String(input, 0, bytesRead);
// Remove any whitespace from either end
trimmedString = inputString.trim();
// After removing whitespace check if the string has zero length
if (trimmedString.length() == 0)
continue; // try again
// Try to convert what is left to an integer value
// Note that this doesn't check for non-digits
intValue = Integer.parseInt(trimmedString);
sum += intValue;
}
}
catch (IOException e) {
System.out.println("whoops, caught IO Exception");
}
return sum;
}
}
|