gpt4 book ai didi

java - 在系统检查异常之前,如何允许输入三个整数,后跟一个空格和一个单词?

转载 作者:行者123 更新时间:2023-12-01 13:23:28 25 4
gpt4 key购买 nike

这是一项家庭作业,我对这个愚蠢的问题表示歉意,我似乎无法破解它,我尝试了几种方法,包括 .hasInt();。我的代码用于检查用户是否输入整数,在我想要允许用户输入“5 小时,10 分钟,15 秒。”之后,购买将不允许任何操作。到目前为止,我只能允许他们输入 "5 10 15" ,其他任何内容都会被异常捕获并要求他输入有效的数字。这是代码。

import java.util.*;

public class TimetoSeconds
{
public static void main(String[] args)
{
System.out.println("Time converter");
System.out.println();
//start scanner and variables
Scanner sc = new Scanner(System.in);
int x = 60;
String choice = "y";
while (choice.equalsIgnoreCase("y"))
{
//catch exceptions
int hours = 0;
int minutes = 0;
int seconds = 0;
try
{
// get user input
System.out.print("Enter time in hours (space), minutes (space), and
seconds: ");
hours = sc.nextInt();
minutes = sc.nextInt();
seconds = sc.nextInt();
System.out.println();
}
catch (InputMismatchException e)
{
sc.nextLine();
System.out.print("Error! Invalid number. Try again.\n");
continue;
}

int sec1 = (hours * x) * x;
int sec2 = minutes * x;
int totalSec = sec1 + sec2 + seconds;

System.out.print("Total seconds are: " + totalSec + "\n");
System.out.println();

System.out.print("Continue? (y/n): ");
choice = sc.next();
System.out.println();
}
}
}

最佳答案

只需更改这部分即可。

    System.out.print("Enter time in hours (space), minutes (space), and seconds:  ");
hours = sc.nextInt();
sc.next();
minutes = sc.nextInt();
sc.next();
seconds = sc.nextInt();
sc.next();

那么你的程序就可以正常工作了。

Time converter

Enter time in hours (space), minutes (space), and seconds: 5 hours, 10 minutes, 12 seconds

Total seconds are: 18612

Continue? (y/n): y

Enter time in hours (space), minutes (space), and seconds: 3 hours, 10 minutes, 20 seconds

Total seconds are: 11420

Continue? (y/n): n

但这很容易出错。我宁愿阅读整个大字符串
用户输入的内容,例如“5小时10分20秒”然后
从那里提取我需要的任何东西(我只需要 3 个数字)。
什么是容易出错?因为如果用户输入“5小时,10分钟,20秒”,
它仍然会检测到这是无效输入(因为逗号没有粘在单词上)。

关于java - 在系统检查异常之前,如何允许输入三个整数,后跟一个空格和一个单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21912891/

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