8.20更新:
这一次看到了hasNextInt,那么输入方式就可以进行改变了
做一个循环判断,对就输入错就重新来,根本不需要对字符进行检测 ORZ...
if (scan.hasNextInt()) {
int num = scan.nextInt();
System.out.println("输入的数据为:" + num);
}
hasNextInt()返回值是true和false,用于if判断即可
这一次是上次字符检测是否全为数字的增强版。欢迎各位朋友或大神指出不足之处。
简书代码排版总有点问题,如果有需要,可通过博客园的代码进行使用:
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在外面定义,如果在循环中定义会出错
String[] two =new String[6];
String pre;
int[] str =new int[6];
int count = 0;//用于退出循环
while(true){
System.out.println("请依次输入6个数");
count = 0;//如果输入字符不是数字时,从if中出来,重新计数
for(inti=0;i<6;i++){
pre = s.next();//接收字符串
if(!(pre.matches("\\d+"))) {//非(pre全为数字)
System.out.println("输入的" + pre + "不是数字,请重新输入");
break;//这个退出的是for循环,退出后会再次执行while循环,重新输入数字 }
else {
str[i] = Integer.parseInt(pre);//把数字型字符串转换为int型数字 }
count++;//每执行一次数据输入后,count才会+1 }
if(count==6)break;//这个退出的是while循环 }
for(int i=0;i<6;i++){//输出打印数字
if(i==0){
System.out.print(str[i]);
}
else{
System.out.print(","+str[i]);
}
}
}
}
网友评论