gpt4 book ai didi

java - 如何重新分配已输入的基于扫描仪的值? - java

转载 作者:行者123 更新时间:2023-12-01 11:36:29 25 4
gpt4 key购买 nike

没有看到任何可以回答我的问题的帖子,我会自己问。我目前正在尝试弄清楚一些编程,并打算制作一个简单的程序,要求用户输入一个整数。输入用户输入的任何内容后,如果它是变量,则会在下面的输出行中如此表示。如果用户没有输入整数,它会捕获错误并要求用户尝试重新输入整数 - 这个过程会重复,直到输入整数并且程序可以终止。

通常,对于任何高于真正直接的编程并取得成功的经验水平都非常低,我的代码不仅比我当前遇到的问题有更多的错误,而且我可能有我什至没有的错误知道在那里。

我尝试了很多不同的事情,这就是我对其他一些 block 的情况有一定了解的地方,但这是我现在所处的位置:

import java.util.Scanner;

public class LauncherMain {

static Scanner reader = new Scanner(System.in);

public static void setInputValue() {
int userInput = reader.nextInt();
}

public static void tryInputValue(int userInput) { //do I even need this parameter, it seems to not have any correlation with the userInput integer I defined above
try {
setInputValue();
}
catch (java.util.InputMismatchException userInput) { //if the code is in the method it will accept using userInput, but then goes on about some duplicate variable
System.out.println("That wasn't an integer!"); //I haven't really looked into it, but I also would like this to be a warning instead of basic output
setInputValue(); //I don't think this is right either, would it have to call a tertiary method that calls the try again? ...but I have a (necessary) finally block
}
finally {
System.out.println("Awesome, your value is now: " + userInput);
}
}

public static void main(String[] args) {
System.out.println("Enter an integer:");
tryInputValue(int userInput); //Looks like I am also getting some sort of error down here, it has to do with not being able to be resolved to a variable
}

}

好吧,如果您成功地阅读了可能非常错误的代码,那么我遇到的主要问题是获取它,以便用户在上次尝试失败后能够重新输入希望是整数的内容。在尝试添加一个 block 来执行此操作之前,我所拥有的将起作用,此外,如果输入的内容不是整数,则不会崩溃,因为该 catch block 就在那里。问题是我被错误输入的值困住了,因此无法使用变量:userInput,因为它是输入不匹配。因此,在尝试添加一些允许重新分配的内容后,它开始抛出一些错误,我开始更改内容,现在我在不同的地方遇到了我什至不理解的错误。

如果有人愿意帮忙,万分感谢!如果您愿意,对您提供的修复中所有内容的描述将非常有用! :)

最佳答案

您正在将“int userInput”传递给该方法,这是不正确的语法。您需要传递一个值而不是声明。例如:

int ui = 0;
tryInputValue(ui);

所以如果你想传入用户输入的值,你需要在调用 tryInputValue 之前扫描他们的输入。测试用户是否输入整数的一个简单方法是使用 Integer.partInt(String) 这里是文档:http://docs.oracle.com/javase/6/docs/api/java/lang/Integer.html#parseInt%28java.lang.String%29

你可能还应该有一个 do{...}while();循环,以便继续提示用户输入,直到格式正确为止。

关于java - 如何重新分配已输入的基于扫描仪的值? - java ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29931726/

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