gpt4 book ai didi

java - 在输入中为字符设置异常以退出仅接受整数且不停止的程序

转载 作者:行者123 更新时间:2023-12-02 03:45:06 24 4
gpt4 key购买 nike

我试图对 char(0) 进行异常(exception)处理,如果它是“Q”或“q”来退出该程序。它计算测试分数,并继续允许用户输入测试分数(它不会结束)并且只接受数字。我想对字母 Q 或 q 进行异常(exception)处理以退出程序。

我尝试过使用 charAt 但不能,因为它是一个整数。

import java.util.Scanner;
public class Main {

public static void main(String[] args) {
boolean run = true;
while (run) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the test score: ");
while (!input.hasNextInt()) {//Will run till an integer input is found
System.out.println("Only number input is allowed!");
System.out.print("Enter the test score: ");
input.next();
}

int tS = input.nextInt();



int sum = (10 + tS);
System.out.println(sum);


}
}
}

最佳答案

一种可能的方法是首先接受字符串,然后使用 .contains() 检查“q”。

如果包含“q”,则抛出异常,否则解析为int。

类似这样的事情:

Scanner sc = new Scanner(System.in);
System.out.println("Enter Test Score");
String input = sc.next();
if (input.toLowerCase().contains("q")) {
throw new RuntimeException("The input is not numeric");
}
int tS = Integer.parseInt(input);

// do something

您可以在此处使用循环来继续接受输入。

希望这有帮助。祝你好运。

关于java - 在输入中为字符设置异常以退出仅接受整数且不停止的程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56812146/

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