Reading NumbersOften strings aren't enough. A lot of times you'll want to ask the user for a number as input. All user input comes in as strings so we need to convert the string into a number.Next we promised to write a getNextInteger() method that will accept an integer from the user. Here it is: static int getNextInteger() { String line; DataInputStream in = new DataInputStream(System.in); try { line = in.readLine(); int i = Integer.valueOf(line).intValue(); return i; } catch (Exception e) { return -1; } } // getNextInteger ends here Reading Formatted DataIt's often the case that you want to read not just one number but multiple numbers. Sometimes you may need to read text and numbers on the same line. For this purpose Java provides the StreamTokenizer class.
Writing a text fileSometimes you want to save your output for posterity rather merely scrolling it across a screen. To do this we'll need to learn how to write data to a file. rather than create a completely new program we'll modify the Fahrenheit to Celsius conversion program to output to a file:// Write the Fahrenheit to Celsius table in a file import java.io.*; class FahrToCelsius { public static void main (String args[]) { double fahr, celsius; double lower, upper, step; lower = 0.0; // lower limit of temperature table upper = 300.0; // upper limit of temperature table step = 20.0; // step size fahr = lower; try { FileOutputStream fout = new FileOutputStream("test.out); // now to the FileOutputStream into a PrintStream PrintStream myOutput = new PrintStream(fout); while (fahr <= upper) { // while loop begins here celsius = 5.0 * (fahr-32.0) / 9.0; myOutput.println(fahr + + celsius); fahr = fahr + step; } // while loop ends here } // try ends here catch (IOException e) { System.out.println("Error: + e); System.exit(1); } } // main ends here } There are only three things necessary to write formatted output to a file rather than to the standard output:
|
Bhopal news
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100