本人写的一个小程序,输入一个五位数,输出这个五位数每一位的数字,用数字隔开,如果输入的不是五位数,弹出对话框提示错误并重新输入。本人不知道当输入字母或其他字符时怎样写代码判断,高手们帮帮忙,怎样判断输入的是字母或字符/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package numberapartd;
/**
*
* @author Administrator
*/
// Lab 3: Five.java
// Program breaks apart a five-digit number
import javax.swing.JOptionPane;
public class Five {
public static void main( String args[] )
{
int originalNumber;
int number;
String inputString;
String resultString;
// read five-digit number from user as a String
inputString = JOptionPane.showInputDialog( "Enter five digit integer:" );
// convert inputString to an integer and assign it to originalNumber
originalNumber = Integer.parseInt( inputString );
while((originalNumber<10000)||(originalNumber>99999))
{
resultString ="您输入的不是五位数,请重新输入!";
JOptionPane.showMessageDialog( null, resultString,
"Digits in " + originalNumber, JOptionPane.INFORMATION_MESSAGE );
inputString = JOptionPane.showInputDialog( "Enter five digit integer again:" );
originalNumber = Integer.parseInt( inputString );
}
// determine the 5 digits
int digit1; // first digit of number
int digit2; // second digit of number
int digit3; // third digit of number
int digit4; // fourth digit of number
int digit5; // fifth digit of number
digit1 = originalNumber / 10000; // get leftmost digit
number = originalNumber % 10000; // get rightmost four digits
digit2 = originalNumber % 10000 / 1000;
digit3 = originalNumber % 10000 % 1000/ 100;
digit4 = originalNumber % 10000 % 1000 % 100 / 10;
digit5 = originalNumber % 10000 % 1000 % 100 % 10;
// create the result string
resultString =
digit1 + " " + digit2 + " " +
digit3 + " " + digit4 + " " + digit5 ;
// display results
JOptionPane.showMessageDialog( null, resultString,
"Digits in " + originalNumber, JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
}
} // end class Five
!
package cn.jhf;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Random {
/**
* @param args
*/
public static void main(String[] args) {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
String str = null;
int k = 0, flag = 0;
try {
str = bf.readLine();
} catch (Exception e) {
}
while (str != null) {
try {
k = Integer.parseInt(str);
} catch (Exception e) {
System.out.println("输入的是非数字,请重新输入!!");
flag = 1;
}
if (flag != 1)
System.out.println("你输入的是数字:" + k);
try {
str = bf.readLine();
} catch (Exception e) {
}
}
}
}
int number;//这里可以是你接受的数字
if(String.valueOf(number).matches("^\\d+$"))
System.out.println("输入是数字");
else
System.out.println("输入不是数字");
String s = JOptionPane.showInputDialog( "Enter five digit integer:" );
try{
Integer.parseInt(s);
}catch(NumberFormatException e){
System.out.println("input is not a integer.");
}
类似这样的方法判断。
网上还有类似validate的包,关于ajax的
用起来也方便