gpt4 book ai didi

java - 我需要 Java 扫描仪 'reset' 修复无效字符

转载 作者:太空宇宙 更新时间:2023-11-04 11:16:58 30 4
gpt4 key购买 nike

我是一个学习编码的新人!

我的扫描仪有问题,我需要它在无效字符上“重置”。

我的代码:

public class Lemonade {

static int m = 150;
private static Scanner scan;

public static void main(String[] args) {

int day = 1;

for(int gameover = m; gameover > 0; day++) {
int Random = (int) (Math.random() * 100);
if(Random <= 25) {
System.out.println("Great Chance!");
System.out.println("--------------------------------");
}
else if(Random <= 50) {
System.out.println("Good Chance!");
System.out.println("--------------------------------");
}
else if(Random <= 75) {
System.out.println("Bad Chance!");
System.out.println("--------------------------------");
}
else if(Random <= 100) {
System.out.println("Awful Chance!");
System.out.println("--------------------------------");
}

int count = 0;

int none = 0;

scan = new Scanner(System.in);

System.out.println("Enter a number between 0 and " + m + "!");

count = scan.nextInt();

if(count >= none && count <= m) {
System.out.println("You entered " + count + "!");
System.out.println("--------------------------------");
day = day + 1;
m = m - count;
System.out.println("Day " + day);
}
else {
System.out.println("Enter a number between 0 and " + m + ".");
count = scan.nextInt();
}

}
}
}

现在我的问题是如何在“f”等无效字符上“重置”它,因为扫描仪只接受数字。

感谢您的帮助!

最佳答案

如果我理解正确的话,那么这就是您正在寻找的东西,如果用户输入无效字符而不是 int,则会抛出 InputMismatchException。您可以使用循环,直到用户输入整数

import java.util.Scanner;
import java.util.InputMismatchException;


class Example
{
public static void main(String args[])
{
boolean isProcessed = false;
Scanner input = new Scanner(System.in);
int value = 0;
while(!isProcessed)
{

try
{
value = input.nextInt();
//example we will now check for the range 0 - 150
if(value < 0 || value > 150) {
System.out.println("The value entered is either greater than 150 or may be lesser than 0");
}
else isProcessed = true; // If everything is ok, Then stop the loop
}
catch(InputMismatchException e)
{
System.out.print(e);
input.next();
}

}

}
}

如果这不是您要找的,请告诉我!

关于java - 我需要 Java 扫描仪 'reset' 修复无效字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45355699/

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