java怎么定义接收用户输入4个整数,不是4个整数就显示报错

qq_37592400 2018-03-27 10:06:34
刚入门,有大神能回答吗 百度没找到。
...全文
828 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
qq_39936465 2019-09-10
  • 打赏
  • 举报
回复
引用 楼主 qq_37592400 的回复:
刚入门,有大神能回答吗 百度没找到。

import java.util.Scanner;

public class test7 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner sc = new Scanner(System.in);
		int count = 1;
		int[] s = new int[4];
		while (count < 5) {
			System.out.println("请输入第" + count + "个整数");
			try {
				s[count - 1] = sc.nextInt();
				count++;
			} catch (Exception e) {
				// TODO Auto-generated catch block
				System.out.println("输入不正确请重新输入");
				sc.next();
			}
		}
		for (int i = 0; i < 4; i++) {
			System.out.print(s[i] + "\t");
		}
	}
}

变速不变道 2019-09-10
  • 打赏
  • 举报
回复
直接用nextInt()逐个读取然后保存起来,这些读取的语句用try catch语句包起来,如果出现异常就返回并提示报错,停止数据输入并停止程序。
变速不变道 2019-09-10
  • 打赏
  • 举报
回复
报错了,,还继续输入吗?
huxiaoto 2018-04-08
  • 打赏
  • 举报
回复
定义一个int类型的数组,长度为4,再用for循环里面写个接受语句,然后用try catch当长度不为4时给出提示语句
小葡萄、 2018-03-29
  • 打赏
  • 举报
回复
定义的一意思就是说
rickylin86 2018-03-28
  • 打赏
  • 举报
回复

import java.util.Scanner;

public class Test{
	public static void main(String[] args){
		Scanner keyboard = new Scanner(System.in);
		int time = 0;
		String content = null;
		while(time ++ < 4){
			System.out.print("第" + time + "次输入一个整数:");
			content = keyboard.nextLine();
			if(!content.matches("^\\s*\\d+\\s*$")){
				System.out.println("输入的内容'" + content + "'无效");
				System.exit(1);
			}else{
				System.out.println("输入的内容'" + content + "'有效");
			}
		}
	}
}
变速不变道 2018-03-28
  • 打赏
  • 举报
回复
直接当字符串形式接收,然后再用正则表达式判断这个值是不是整数,即在0到9范围内。
  • 打赏
  • 举报
回复
public static void main(String[] args) { // TODO Auto-generated method stub Scanner input = new Scanner(System.in); String str = input.nextLine(); String [] contents = str.split(input.delimiter().toString()); System.out.println("输入的内容'" + str + "'!"); System.out.println("输入的数量:'" +contents.length + "'!"); if(contents.length != 4){ System.out.println("请输入4个数字!"); } else{ for(int i = 0; i < contents.length; i++){ if(!contents[i].matches("^\\s*\\d+\\s*$")){ System.out.println("请输入4个数字!"); System.exit(1); }else{ System.out.println("输入第"+ (i + 1)+"的数字:" + contents[i] + "!"); } } } }
qq_37592400 2018-03-27
  • 打赏
  • 举报
回复
接收我会 但是就差判断了
Kingram 2018-03-27
  • 打赏
  • 举报
回复
Scanner sc = new Scanner; sc.nextInt()接收呀

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧