我写了一个非常基本的程序,有3个选项。在执行代码的“退出”部分时,我得到一个InputMismatchError。我知道这是因为当我/用户给它一个字符串时,程序期望一个整数。 我只是想知道如何设置这样的东西。 我也尝试了一个字符串到char的方法,但这也给了我同样的错误。
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
static Scanner S = new Scanner(System.in);
public static void main(String[] args) throws IOException
{
int DisJ, ISJ, User;
ISJ = 1;
DisJ = 2;
String input = "";
// change print outs to appropriate names::::
System.out.println("--Main Menu--");
System.out.println("Display Journeys:" + ISJ);
System.out.println("Suitable Journeys:" + DisJ);
System.out.println("Quit: " );
//User = S.next().charAt(0);
User = S.nextInt();
if (User == 1)
{
System.out.println("You have selected Display Journeys");
try
(BufferedReader ReadFile = new BufferedReader(new FileReader("E:\\input.txt")))
{
String line = null;
while ((line = ReadFile.readLine()) != null)
{
System.out.println(line);
}
}
}
else if (User ==2)
{
System.out.println("You have selected Suitable Journeys");
}
System.out.println("Specify Destination: ");
String destination = S.next();
System.out.println("Specify Max Time (HH:MM): ");
String specificTime = S.next();
// This assigns the first two integers to the string hours
String hours = specificTime.substring(0,2);
//This assigns the last two integers to the string minutes
String minutes = specificTime.substring(3,5);
//integer.parseInt converts the string into an integer
int hours1 = Integer.parseInt(hours);
//integer.parseInt converts the string into an integer
int minutes1 = Integer.parseInt(minutes);
int Time;
// Equation to convert the hh:mm into minutes
Time = (60 * hours1) + minutes1;
System.out.println("Specify number of changes");
int Changes = S.nextInt();
System.out.println( "Destination selected: " + input + "Minutes specified: " + Time + "," + "Number of changes: " + Changes);
int quit;
String Quit = S.next();
if (Quit.equals("Quit")) {
System.out.println("Goodbye!");
System.exit(0);
}
try {
quit = Integer.parseInt(Quit);
}
catch (Exception e)
{
System.out.println("Type Quit to leave");
}
}
}
答案 0 :(得分:0)
尝试包裹yor coe并捕获错误来处理它们
int quit;
try {
quit = Integer.parseInt(Quit);
} catch (Exception e) {
// handle error...
}
http://beginnersbook.com/2013/04/try-catch-in-java/
简单地检查用户输入的内容只接受字符串并检查其值如下:
Scanner scanner = new Scanner(System.in);
System.out.print("Quit?");
String text = scanner.nextLine();
if (text.equals("Quit") or text.equals("q")) {
//...
}
答案 1 :(得分:0)
您的问题是您无法使if语句中的参数成立吗? 尝试将其设置为布尔值而不是int / string,并且在整个代码中只需将quit更改为true / false而不是数字/字符串。
编辑:哦,我明白了。所以你只想做到这一点,以便用户可以按一个键然后退出,就像“请输入Y退出程序” 你有扫描仪吗?