gpt4 book ai didi

Java,如何为错误输入设置循环?

转载 作者:行者123 更新时间:2023-12-01 15:42:04 24 4
gpt4 key购买 nike

//作者:tlc

import java.util.Scanner;
public class assignment2 {
public static int t1;
public static int t2;
public static int x;
public static int y1;
public static int m1;
public static int d1;
public static int y2;
public static int m2;
public static int d2;
public static void date1() {

Scanner scanner = new Scanner (System.in);

System.out.println("Please enter the first date \n");
System.out.println ("Please enter the year: ");
y1=scanner.nextInt();

System.out.println("Please enter the month: ");
m1=scanner.nextInt();

System.out.println("Please enter the day: \n");
d1=scanner.nextInt();

}
public static void date2() {
Scanner scanner = new Scanner (System.in);

System.out.println("Please enter the second date \n");
System.out.println ("Please enter the year: ");
y2=scanner.nextInt();

System.out.println("Please enter the month: ");
m2=scanner.nextInt();

System.out.println("Please enter the day: \n");
d2=scanner.nextInt();

}
public static void finaldate() {
x = Math.abs(t1-t2);
}
public static void main(String[] args) {
date1();
if (m1==1 + 3 + 5 + 7 + 8 + 10 + 12){
t1 = ((365*y1)+d1+31);}
else
if (m1==2) {
t1 = ((365*y1)+d1+28);}
else
if (m1==4 + 6 + 9 + 11); {
t1 = ((365*y1)+d1+30);}

date2();
if (m2==1 + 3 + 5 + 7 + 8 + 10 + 12){
t2 = ((365*y2)+d2+31);}
else
if (m2==2) {
t2 = ((365*y2)+d2+28);}
else
if (m2==4 + 6 + 9 + 11); {
t2 = ((365*y2)+d2+30);}
finaldate();

System.out.println("The difference between the two dates is: " + x + " days.");

}
}

如何设置捕获错误输入(例如:不是整数)并让程序显示一条错误消息,然后显示一个返回到程序开头的循环?我已经为此苦苦挣扎了一段时间了。

感谢所有帮助! :)

最佳答案

用 try catch block 包围以捕获 java.util.InputMismatchException,当下一个值与整数正则表达式不匹配时抛出该异常。

Scanner API 中所述, nextInt() 方法在这些情况下将抛出此异常。

关于Java,如何为错误输入设置循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7897028/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com