JAVA中如何实现从键盘中输入一个整数?

如题所述

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Test{
public static void main(String[] args){
int num ;
String str ;
BufferedReader brd=new BufferedReader(new InputStreamReader(System.in)) ;
while(true)
{
System.out.print("请输入数字:") ;
try
{
str=brd.readLine() ;
num=Integer.parseInt(str) ;
break ;
}
catch(Exception e)
{
System.out.println("对不起,只能输入整数,请重新输入。") ;
}
}
System.out.println("你输入的整数是: "+num) ;
}
}

要输出的是整数,当然要来个判断如果输入的不是时就重新提示输入的说。
温馨提示:答案为网友推荐,仅供参考
第1个回答  2009-03-12
首先需要用到Scanner 类,所以要在最开始import java.util.Scanner;
然后在需要用到的方法里面创建个Scanner 物体,Scanner sc = new Scanner(System.in);
然后就可以用Scanner的方法nextInt()了: sc.nextInt();
举例如下:
import java.util.Scanner; //import the Scanner class
public class sampleInput{
public static void main(String[] args){
Scanner sc = new Scanner(System.in); //create the new Scanner object sc
System.out.println("please input an integer");
int a = sc.nextInt(); //use the nextInt() method to read in
System.out.println("Thanks for your help!" + a); //print the input integer
}
}
第2个回答  2009-03-12
import java.util.*
public class test{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("请输入一个整数: ");
int num = input.nextInt();
System.out.println("你输入的整数是:"+num);
}
}
第3个回答  推荐于2016-02-22
system.in InputStream
你可以用java I/O中的Stream类,也可以用scranner类。
相关知识:I/O和nI/o,包括InputStream与OutputStream。
贴上代码:
ublic class Test{
public static void main(String[] args){
int num ;
String str ;
BufferedReader brd=new BufferedReader(new InputStreamReader(System.in)) ;
while(true)
{
System.out.print("请输入数字:") ;
try
{
str=brd.readLine() ;
num=Integer.parseInt(str) ;
break ;
}
catch(Exception e)
{
System.out.println("对不起,只能输入整数,请重新输入。") ;
}
}
System.out.println("你输入的整数是: "+num) ;
}
}
相似回答