Round 1
第一种:使用System.in.read(),较为麻烦
package com.first.test;
import java.io.IOException;
public class Accept {
public static void main(String[] args) {
int c= 0;
String s = "";
System.out.println("输入摄氏度:0<数值<100");
System.out.print(">");
while(c!=13) {
try {
c = System.in.read();
} catch (IOException e) {
e.printStackTrace();
}
s = s + (char)c;
}
int celsius = Integer.parseInt(s.trim());
double fahre = 1.8 * celsius + 32;
System.out.println("转化为华氏度为:"+fahre);
}
}
对以上代码说明:
- System.in.read() 一次只能接收一个字符,返回一个ASCII码
- ASCII码13对应的值为 ‘\r’ 回车
- 以上代码看起来匪夷所思,让我们对代码进行修改,做个测试,在每次循环时输出c与s的值
package com.first.test;
import java.io.IOException;
public class Accept {
public static void main(String[] args) {
int c= 0;
String s = "";
System.out.println("输入摄氏度:0<数值<100");
System.out.print(">");
while(c!=13) { //13对应的ASCII为'/r'回车
try {
c = System.in.read();
} catch (IOException e) {
e.printStackTrace();
} //返回一个ASCII值,如c=13,先返回1的ASCII再返回3的ASCII
System.out.println(c);
s = s + (char)c;
System.out.println(s);
System.out.println("*****************");
}
int celsius = Integer.parseInt(s.trim());
double fahre = 1.8 * celsius + 32;
System.out.println("转化为华氏度为:"+fahre);
}
}
结果:
输入摄氏度:0<数值<100
>13
49 //1对应的ASCII
1
*****************
51 //3对应的ASCII
13
*****************
13 //'\r'对应的ASCII
13
*****************
转化为华氏度为:55.400000000000006
结合代码中的注释与说明,这个应该不难理解。
Round 2
使用BufferedReader
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Accept1 {
public static void main(String[] args) {
String s="";
System.out.println("输入摄氏度:0<数值<100");
System.out.print(">");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
s = br.readLine();
}catch(Exception e) {
}
int celsius = Integer.parseInt(s.trim());
double fahre = 1.8 * celsius + 32;
System.out.println("转化为华氏度为:"+fahre);
}
}
Round 3
使用Scanner类,较为方便
import java.util.Scanner;
public class Accept2 {
public static void main(String[] args) {
int c= 0;
System.out.println("输入摄氏度:0<数值<100");
System.out.print(">");
Scanner scr = new Scanner(System.in);
c = scr.nextInt();
double fahre = 1.8 * c + 32;
System.out.println("转化为华氏度为:"+fahre);
}
}