日期:2014-05-20 浏览次数:20881 次
Scanner console = new Scanner(System.in); String val = console.next(); int n = 0; try { n = Integer.parseInt(val); } catch(Exception e) { n = (int) Float.parseFloat(val); } for(int i = 0; i <= n; i++) { System.out.print("[" + i + "] "); }
------解决方案--------------------
public static void main(String args[]) { Scanner console = new Scanner(System.in); String s = console.next(); int n = 0; try{ if(s.matches("[0-9]*[.]{1}[0-9]*")){//小数 double d = Double.parseDouble(s); n = (int) d; }else if(s.matches("[0-9]*")){//整数 n = Integer.parseInt(s); } }catch(Exception e){ } for (int i = 0; i <= n; i++) { System.out.print("[" + i + "] "); } }
------解决方案--------------------
import java.io.*;
public class printNumber {
public static void main(String[] args){
printNumbers();
}
public static void printNumbers(){
System.out.println("输入截至数据这里必须是整数");//如果这里给的输入错误不是整数那么程序则无法运行,得做一个什么呢??
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String str;
try {
str = br.readLine();
int n = (int)Float.parseFloat(str);
for(int i=0;i<=n;i++)
{
System.out.print("["+i+"] ");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
希望对你有用。。。
------解决方案--------------------
for example
public static void printNumbers(){ while (true) { System.out.println("输入截至数据这里必须是整数/输入[quit]退出程序"); Scanner console=new Scanner(System.in); String data = console.nextLine(); int n = 0; try { if ("quit".equals(data)) { System.out.println("退出程序。"); break; } n = Integer.parseInt(data); } catch (Exception e) { System.out.println("输入非法数据,请重试。"); continue; } for(int i=0;i<=n;i++) { System.out.print("["+i+"] "); } } }