/
JAVA 判斷輸入字串是否為字元或是奇偶數
79 lines (70 loc) · 2.39 KB
/
JAVA 判斷輸入字串是否為字元或是奇偶數
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
// JAVA 判斷輸入字串是否為字元或是奇偶數
public class HelloWorld{
public static void main(String []args)
{
//System.out.println("Hello World");
String str= "123";
String str1= "122";
String str2= "1t2";
String str3= "ttt";
isNumeric(str);
isNumeric(str1);
isNumeric(str2);
isNumeric(str3);
}
public static boolean isNumeric(String str){
for ( int i = 0 ; i < str.length(); i ++ ){
//System.out.println(str.charAt(i));
if ( ! Character.isDigit( str.charAt(i)))
{
System.out.println("輸入字串 "+ str + " is not int");
return false ;
}
}
//System.out.println("string is int");
//這邊再把確定字串為數字再轉int做 x%2==0 就是偶數 反之則基數
int i = Integer.parseInt(str);
if (i %2 ==0)
System.out.println("輸入字串 "+ str + " is 偶數");
else
System.out.println("輸入字串 "+ str + " is 奇數");
return true ;
}
}
//新版
public class HelloWorld{
public static void main(String []args)
{
//System.out.println("Hello World");
String str= "1tttt1";
boolean b = false;
for ( int i = 0 ; i < str.length(); i ++ )
{
//System.out.println(str.charAt(i));
if ( ! Character.isDigit( str.charAt(i)))
{
System.out.println("輸入字串 "+ str + " is not int");
b = true;
System.out.println(b);
break;
//System.out.println(i);
}
}
if(b ==false)
{
int a = Integer.parseInt(str);
if (a %2 ==0)
{
System.out.println("輸入字串 "+ str + " is 偶數");
//getServletContext().setAttribute("str", "偶數");//
//response.sendRedirect("index.jsp");
//break;
}
else
{
System.out.println("輸入字串 "+ str + " is 奇數");
//getServletContext().setAttribute("str", "奇數");
//response.sendRedirect("index.jsp");
//break;
}
}