【发布时间】:2015-04-28 23:32:21
【问题描述】:
没有看到任何我能够回答我的问题的帖子,我会自己问。我目前正试图弄清楚一些编程,并打算制作一个简单的程序,要求用户输入一个整数。在输入用户输入的任何内容后,如果它是一个变量,它会在下面的输出行中这样说。如果用户没有输入整数,它会捕获错误并要求用户尝试重新输入他们的整数——这个过程会一直重复,直到输入整数并且程序可以终止。
一般来说,在真正直接的编程之上的任何事情的经验水平都非常低,如果它成功了,我的代码不仅比我目前遇到的问题有更多的错误,而且我可能有我什至没有的错误知道在那里。
我尝试了很多不同的东西,这就是我对其他一些块的情况有所了解的地方,但这是我现在所处的位置:
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
}
}
好的,所以如果你设法通过阅读那个可能非常错误的代码幸存下来,我遇到的主要问题是得到它,以便用户能够在上一次尝试失败后重新输入希望是整数的内容。在尝试添加一个块来执行此操作之前,我所拥有的会起作用,此外,如果输入的不是整数,则不会崩溃,因为那个 catch 块在那里。问题在于我被错误输入的值所困扰,因此无法使用变量:userInput,因为它是输入不匹配。因此,在尝试添加允许重新分配的内容后,它开始抛出一些错误,我开始更改内容,现在我在不同的地方遇到了我什至不理解的错误。
如果有人愿意提供帮助,谢谢!如果您愿意,描述您提供的修复程序中的所有内容将非常有用! :)
【问题讨论】:
-
您在同一范围内有一个
int userInput和一个InputMismatchException userInput,这也会给您带来一些问题。finally块在完成try或catch后运行,这不是您尝试使用它的方式。try/catch/finally不是 Control Flow Statement。
标签: java methods input console-application java.util.scanner