如题
java中相当与c 中的getchar 的方法是什么?
import java.io.*;public class Main {
public static void main(String[] args) throws IOException {
DataInputStream in = new DataInputStream(System.in);
char ch = in.readChar();
System.out.println(ch);
}
}上面的代码为什么输入英文 读出来是中文, 如何解决
java中相当与c 中的getchar 的方法是什么?
import java.io.*;public class Main {
public static void main(String[] args) throws IOException {
DataInputStream in = new DataInputStream(System.in);
char ch = in.readChar();
System.out.println(ch);
}
}上面的代码为什么输入英文 读出来是中文, 如何解决
解决方案 »
- 大家对中间件怎么理解?
- 为什么 总是 java.sql.SQLException: No suitable driver found for jdbc:Cache://localhost:1972/SAMPLES
- 关于mysql与oracle语句之间的转换,limit的。怎么弄,请帮忙
- runtime.getruntime().exec(batch file)
- java mail的问题
- JPanel,如何能使它有右侧的和底部的滚轴?
- 【求助】各位大神!小弟新学java,第一个程序就老编译报错
- 求try finally 的资源释放,大家帮我解释一下
- 简单问题! java中可以使用类似于 X + =10;的语句?
- oracle客户端环境变量设置的问题
- 有没有办法知道数据库那边在插入不成功后进行了回滚操作
- 要在目标文件里写内容,就是没成功
new InputStreamReader(System.in));
String line = consoleReader.readLine();
char cmd = line.length() == 0 ? 0 : line.charAt(0);
改为“char ch =(char) in.read();”即可
比如我直接打一个回车。对于c的getChar()也是可以算是获取一个输入字符吧
但是你这里读到一个空字符串。似乎不是很合适
2.用(char)System.in.read()
仅局限于ascii字符。如果你尝试输入一个非ascii字符,就不是这么回事了
1.Reader reader = System.console().reader();
2.Reader reader = new InputStreamReader(System.in);获取reader后,执行 reader.read(),并转为char值即可得到输入的字符值。不论是ascii码还是中文,都正常运行(char)reader.read();ps:方法1,在IDE里运行可能会有问题.
就可以读取你输入的第一个字符。然后有了字符你就随便处理好了。比如可以用 switch 语句:
switch (c) {
case 'A':
// do something
case 'B':
// do something
}---------------------------------------
你初学者,我就把代码再写一遍吧:import java.io.*;public class Demo {
public static void main (String args[]) {
char c = 0;
try {
c = (char)new BufferedReader(new InputStreamReader(System.in)).read();
} catch (IOException ioe) {
System.exit(0);
}
switch (c) {
case 'A':
System.out.println("It is A.");
break;
case 'B':
System.out.println("It is B.");
break;
}
}
}
比如楼上的, 我输入AB 只能输出A 那个B就给活生生的吞了。
读入一个字节!!
-----------------
你的代码为什么输入英文 读出来是中文,可以看DataInputStream.readChar()的实现就明白了.
char readChar(){
int ch1 = in.read();
int ch2 = in.read();
if ((ch1 | ch2) < 0)
throw new EOFException();
return (char)((ch1 << 8) + (ch2 << 0));
}
char readChar(){
int ch1 = in.read();
int ch2 = in.read();
if ((ch1 | ch2) < 0)
throw new EOFException();
return (char)((ch1 << 8) + (ch2 << 0));
}
小弟很菜,谢谢