之前我用最基本的输入输出语句写一个小程序,总出现我输入的是一个INT型常量,出来却是出来ASCII码,然后我写了个最简单的测试一下还是出现这样的情况,希望有高手帮助回答一下啊....还有,是不是JAVA中的定义 一个变量的同时一定要给他初始化一个值??import java.io.*;public class test{
public static void main(String args[]){
int a=0;
try{
a=(int)System.in.read();
}catch(IOException e){
System.err.println(e.toString());
}
System.out.print("hello world"+ a);
}
}
public static void main(String args[]){
int a=0;
try{
a=(int)System.in.read();
}catch(IOException e){
System.err.println(e.toString());
}
System.out.print("hello world"+ a);
}
}
System.out.print("hello world"+ (char)a);
c里面就好多了...我刚学JAVA,教材里从没用过基本的输入输出语句,一上来就全给我整SWING....我用的那本书是 JAVA HOW TO PROGRAM....国外的教材....
若想INT,要转换一下的
import java.io.*;public class test{
public static void main(String args[]){
char a='a';
try{
a=(char)System.in.read();
}catch(IOException e){
System.err.println(e.toString());
}
System.out.print("hello world"+ a);
}
}
这样就有用...
如何转换啊???把我的输入的INT输出也是INT?
public static void main(String args[]){
try{
System.out.print(args[0]);
}catch(Exception e){
System.err.println(e.toString());
}
}
}
import java.io.*;public class test{
public static void main(String args[]){
int a=0;
char b=' ';
try{
a=System.in.read();
b=(char)a;
}catch(IOException e){
System.err.println(e.toString());
}
System.out.print("hello world"+ b);
}
}
我在网上看到有人这样解释:System.in.read()读到了一个int(即使你输入的是一个char,他还是优先转换为这个char的ASC码),本来就是一个int型的返回值再被强制转换一次毫无意义,他如果再赋值给一个char的时候,很不幸,他会从一个int的值变成一个char型的ASC码,如果赋值给一个int型的变量,就是2种结果了
public static void main(String args[]){
int a=0;
try{
a=Integer.parseInt(System.in.read());
}catch(IOException e){
System.err.println(e.toString());
}
System.out.print("hello world"+ a);
}
}
public static void main(String[] args)throws IOException{
BufferedReader read=new BufferedReader(new InputStreamReader(System.in));
System.out.println("please inter a inetger");
String s=read.readLine();
int n=Integer.parseInt(s);
System.out.println(n);
}
}
}
但是要注意到java是强类型的语言,java中int是4个字节,但是我们用的键盘向电脑输入的只是8位的ASC码,所以你按了一个数字(比如1),表面是个int型,但键盘传入主机的只是一个8位位串,他的ASC码是49,被read()返回到一个int的变量中存储,用二进制表示是00000000 00000000 00000000 00110001 ,当你再想从这个int变量中读出的时候只能读出它的int值了,即49
所以要么用类型转换,要么用其他的读取方法,比如:
import java.util.Scanner;public class Test
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int a;
a = scanner.nextInt();
System.out.println("hello world "+a);
}
}
System.out.println(br.readLine());
还要抛异常……
或者直接用BuffredRead br=new BufferdRead(new IuputStreamReader(System.in));
前一个是把你输入的全部转化为ASCII码,而后一个则不是。 你试试吧....
int i = sc.nextInt();
System.out.println(i);
int a = 0;
try {
BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
a = Integer.parseInt(buf.readLine());
} catch (IOException e) {
System.err.println(e.toString());
}
System.out.print("hello world " + a);
}
}
强制类型转换出错,用我这方法试试