import java.io.*;
public class Input {
public static void main(String[] args) {
BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));
String input = null;
try {
while((input = in.readLine())!=null) {
System.out.println("Your input is : " + input );
}
} catch (IOException ex) {
System.out.println("Error in I/O");
System.exit(-1);
}
}
}
|
C:>java Input Hi Your input is : Hi Hello Your input is : Hello Who are you? Your input is : Who are you? |
BufferedReader in = ..... : creates a BufferedReader from System.in. in.readLine(): read a line from user input. Returns null if there is no more input. IOException.
while loop processes the user input. doubles in several lines. The doubles are seperated by a comman (,) and then a space.
I want to find out the average of the numbers on each line and print out the average.data.txt):
1.5, 3.78, 9.2, 2.4 1.56, 1.56, 1.59, 3.1, 4.5 1.5, 2.9, 1.5, 1.1 1, 2, 30 5.5, 5.9 |
import java.io.*;
public class Average {
public static void main(String[] args) {
BufferedReader in = null;
String inputFileName = "data.txt";
try {
in = new BufferedReader(new FileReader(inputFileName));
} catch (FileNotFoundException ex) {
// print out the line number that causes the exception
ex.printStackTrace();
System.exit(-1); // exit
}
String line = null; // one line for the file
String[] data;
try {
double sum = 0;
int num;
while((line = in.readLine()) != null) {
data = line.split(", "); // split the line by comma-space
sum=0;
num = data.length;
for(int i = 0; i < num; i++) {
sum+=Double.parseDouble(data[i]);
}
System.out.println(sum/num);
}
} catch (IOException ex) {
ex.printStackTrace();
System.exit(-1);
}
try {
in.close();
} catch (IOException ex) {
}
}
}
|
4.22 2.462 1.75 11.0 5.7 |
split(String exp) method in String class splits the string by exp.
import java.io.*;
public class Average {
public static void main(String[] args) {
BufferedReader in = null;
String inputFileName = "data.txt";
try {
in = new BufferedReader(new FileReader(inputFileName));
} catch (FileNotFoundException ex) {
// print out the line number that causes the exception
ex.printStackTrace();
System.exit(-1); // exit
}
String line = null; // one line for the file
String[] data;
try {
double sum = 0;
int num;
while((line = in.readLine()) != null) {
data = line.split(","); // split the line by comma
sum=0;
num = data.length;
for(int i = 0; i < num; i++) {
sum+=Double.parseDouble(data[i].trim());// trim method remove the white spaces
// in front and after the string
}
System.out.println(sum/num);
}
} catch (IOException ex) {
ex.printStackTrace();
System.exit(-1);
}
try {
in.close();
} catch (IOException ex) {
}
}
}
|