日期:2014-05-20 浏览次数:21135 次
import java.util.*; public class Test { public static void main(String[] args) { int k = 0; String str = ""; boolean flag = false; Scanner s = new Scanner(System.in); while (true) { str = s.next(); for (int i = str.length(); --i >= 0;) { if (!Character.isDigit(str.charAt(i))) { flag = false; } else { flag = true; } } if (flag) { k = Integer.parseInt(str); if (k > 0) { System.out.print(k + 1); } } else { System.out.print("你输入的不是数字,请重新输入"); } } } }
------解决方案--------------------
借用楼上的代码
import java.util.*; public class Test { public static void main(String[] args) { String str = ""; boolean flag = false; Scanner s = new Scanner(System.in); while (true) { str = s.next(); if("exit".equals(str)) {break;} try{ int k = Integer.parseInt(str); if(k > 0) { System.out.println("你输入的数加上1后值为:"+(++k)); }else{ System.out.println("你输入的不是正整数,请重新输入"); } }catch(Exception e){ System.out.println("你输入的不是整数,请重新输入"); } } } }
------解决方案--------------------
import java.util.Scanner; public class Test { final static String EXIT = "exit"; public static void main(String[] args) { fun(); } static void fun() { Scanner s = new Scanner(System.in); String str = null; while (true) { str = s.next(); int index = str.length(); if(str.equals(EXIT)) return; while (index-- > 0) { if (!Character.isDigit(str.charAt(index))) { System.out.println("你输入的不是正整数,请重新输入"); break; } } if(index < 0) System.out.println(Integer.parseInt(str) + 1); } } }
------解决方案--------------------
加上了对0的判断和超长字符串的处理
import java.math.BigInteger; import java.util.Scanner; public class Test { final static String EXIT_MSG = "exit"; final static String ERROR_MSG = "你输入的不是正整数,请重新输入"; final static String ADD_NUM = "1"; public static void main(String[] args) { fun(); } static void fun() { Scanner s = new Scanner(System.in); String str = null; while (true) { str = s.next(); int index = str.length(); if(str.equals(EXIT_MSG)) return; while (index-- > 0) { if (!Character.isDigit(str.charAt(index))) { System.out.println(ERROR_MSG); break; } } if(index < 0){ BigInteger num = new BigInteger(str); System.out.println(!num.toString().equals("0") ? num.add(new BigInteger(ADD_NUM)).toString(): ERROR_MSG); } } } }