8.20更新:
這一次看到了hasNextInt叛赚,那么輸入方式就可以進(jìn)行改變了
做一個(gè)循環(huán)判斷掠械,對(duì)就輸入錯(cuò)就重新來徐许,根本不需要對(duì)字符進(jìn)行檢測 ORZ...
if (scan.hasNextInt()) {
? ? ? ? ? ? int num = scan.nextInt();
? ? ? ? ? ? System.out.println("輸入的數(shù)據(jù)為:" + num);
? ? ? ? }
hasNextInt()返回值是true和false羊精,用于if判斷即可
這一次是上次字符檢測是否全為數(shù)字的增強(qiáng)版改执。歡迎各位朋友或大神指出不足之處赦邻。
簡書代碼排版總有點(diǎn)問題髓棋,如果有需要,可通過博客園的代碼進(jìn)行使用:
https://www.cnblogs.com/bkytep/p/9495093.html
package com.hw.h817;
import java.util.Scanner;
public class Check {
? ? public static void main(String[] args){
? ? ? ? Scanner s =new Scanner(System.in);
? ? ? ? //把pre和str在外面定義,如果在循環(huán)中定義會(huì)出錯(cuò)
String[] two =new String[6];
? ? ? ? String pre;
? ? ? ? int[] str =new int[6];
? ? ? ? int count = 0;//用于退出循環(huán)
while(true){
? ? ? ? ? ? System.out.println("請(qǐng)依次輸入6個(gè)數(shù)");
? ? ? ? ? ? count = 0;//如果輸入字符不是數(shù)字時(shí)按声,從if中出來膳犹,重新計(jì)數(shù)
for(inti=0;i<6;i++){
? ? ? ? ? ? ? ? pre = s.next();//接收字符串
if(!(pre.matches("\\d+"))) {//非(pre全為數(shù)字)
System.out.println("輸入的" + pre + "不是數(shù)字,請(qǐng)重新輸入");
? ? ? ? ? ? ? ? ? ? break;//這個(gè)退出的是for循環(huán)签则,退出后會(huì)再次執(zhí)行while循環(huán)须床,重新輸入數(shù)字? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? else {
? ? ? ? ? ? ? ? ? ? str[i] = Integer.parseInt(pre);//把數(shù)字型字符串轉(zhuǎn)換為int型數(shù)字? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? count++;//每執(zhí)行一次數(shù)據(jù)輸入后,count才會(huì)+1? ? ? ? ? ? }
? ? ? ? ? ? if(count==6)break;//這個(gè)退出的是while循環(huán)? ? ? ? }
? ? ? ? for(int i=0;i<6;i++){//輸出打印數(shù)字
if(i==0){
? ? ? ? ? ? ? ? System.out.print(str[i]);
? ? ? ? ? ? }
? ? ? ? ? ? else{
? ? ? ? ? ? ? ? System.out.print(","+str[i]);
? ? ? ? ? ? }
? ? ? ? }
? ? }
}