編寫這種IO程序,就不要再用System.in了,去使用Scanner掃描流
在這裏兩個程序都提供
用System.in遇到了一些困難,卡了一個多小時,很是噁心的小困難,主要是自己基礎不牢
1.關於byte數組的有效長度的問題
2.關於System.in中輸入結束後換行,換行符同時進入數據中的問題
3.正則表達式
4.String轉爲int數組的問題
package com;
import java.io.*;
public class T6 {
public static void main(String[] args) throws Exception {
InputStream input = System.in ;
byte[] data = new byte[1024];
System.out.println("請輸入數字:");
int len=input.read(data);//取得byte數組中有效數據的長度
//這點很重要,如果不獲取len則整個1024大小會讀取到input中
String str1 = new String(data,0,len,"UTF-8");//將byte數組轉換爲字符串
String str = str1.replaceAll("(\r\n|\r|\n|\n\r)",""); //濾掉回車所佔的兩個位置
//這是System.in不好的地方,所用Scanner吧
judgeint(str);
//String轉爲int數組
int[] nub = new int[str.length()];
for(int i=0;i < str.length();i++){
//substring取出字符串中從i開始到i+1的字符,不包括i+1
nub[i] =Integer.parseInt(str.trim().substring(i,i+1));
}
statistic(nub);
}
//判斷是否爲全數字形式
public static void judgeint(String s){
String regex="^[0-9]*$";//正則表達式匹配全是數字
if(s.trim().matches(regex)==true){
System.out.println("匹配");
}else{
System.out.println("不匹配");
System.exit(1);
}
}
//判斷奇數偶數
public static void statistic(int[] n){
int even=0;
int odd=0;
for(int i=0;i<n.length;i++){
if(n[i] % 2 == 0){
if(n[i] == 0){
}else{
even++;
}
}else{
odd++;
}
}
System.out.println("輸入的數據中偶數個數爲:" + even);
System.out.println("輸入的數據中奇數個數爲:" + odd);
}
}
Scanner代碼:
import java.util.Arrays;
import java.util.Scanner;
public class TestDemo {
public static void main(String[] args) throws Exception {
Scanner scan = new Scanner(System.in);
scan.useDelimiter("\n") ;
String data = null ; // 接收數據
boolean flag = true ; // 循環標記
while(flag) {
System.out.print("請輸入一串數字:");
if (scan.hasNext()) {
data = scan.next().trim() ; // 接收數據
if (data.matches("\\d+")) { // 由數字所組成
flag = false ; // 循環結束
} else {
System.out.println("輸入數據不是數字,請重新輸入!");
}
}
}
int oddCount = 0 ; // 奇數個數
int evenCount = 0 ; // 偶數個數
String result [] = data.split("") ; // 逐個拆分
for (int x = 1 ; x < result.length ; x ++) {
int temp = Integer.parseInt(result[x]) ; // 取得每一個數字
if (temp % 2 == 0) { // 是偶數
evenCount ++ ;
} else {
oddCount ++ ;
}
}
System.out.println("奇數個數:" + oddCount);
System.out.println("偶數個數:" + evenCount);
}
}