- Java code
import java.io.*;public class Czhb{ public static void main(String[] args)throws Exception { int t=System.in.read(); System.out.println(t); } }
代码是这样的,我想实现的是从键盘读取一个整数或者字符串,但是这样编译时通过的,但是在我输入一个整数时输出的并不是原来的数值,请问这个是什么原因,怎么样才能显示正确? 还有什么很好的办法实现从键盘读取数值吗?
------解决方案--------------------
用JDK1.5,在java.util包中有一个Scanner类,专门用于接受键盘输入
import Java.util. Scanner ;
……… ………
……… ………
Scanner input = new Scanner(System.in);
常用三个接受方法
int nextInt();
将输入信息的下一个标记扫描为一个 int
double nextDouble();
将输入信息的下一个标记扫描为一个double
String next();
查找并返回来自此扫描器的下一个完整标记(字符串)
------解决方案--------------------
- Java code
import java.util.Scanner;public class Czhb{ public static void main(String[] args){ Scanner in=new Scanner(System.in); int t=in.nextInt(); System.out.println(t); }}
------解决方案--------------------
通用的方法:
- Java code
import java.io.*;public class Test{ public static void main(String[] args){ try{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print("请输入:"); String s = br.readLine(); System.out.println(s); }catch(IOException e){ e.printStackTrace(); } } }
------解决方案--------------------
import java.io.*;
public class Test{
public static void main(String[] args){
try{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("请输入:");
String s = br.readLine();
System.out.println(s);
}catch(IOException e){
e.printStackTrace();
}
}
}
同意4楼
------解决方案--------------------
没有强制转化吧?读入的默认是STRING, 而你这样是不行的。
- Java code
import java.io.*;//最多算到25的阶乘public class test { public static void main(String[] args)throws IOException { //System.out.println("输入一个数, 算"); BufferedReader buf; buf = new BufferedReader(new InputStreamReader(System.in)); String str; int x; while(true) { str = buf.readLine(); if(str.equals("quit")) break; x = Integer.parseInt(str); System.out.println(x + "的阶乘是:" + fact(x)); } } static long fact(int k) { long result = 1; for(int i = 2; i <= k; ++i) { result *= i; } return result; }}
------解决方案--------------------
这个是ASCII码值