gpt4 book ai didi

java - 尝试关闭控制台时输入不匹配错误

转载 作者:太空宇宙 更新时间:2023-11-04 13:08:02 25 4
gpt4 key购买 nike

我编写了一个非常基本的程序,有 3 个选项。在执行代码的“退出”部分时,我收到一个InputMismatchError。我知道这是因为当我/用户给它一个字符串时,程序需要一个整数。我只是想知道如何设置这样的东西。我也尝试过 string to 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");
}
}
}

最佳答案

您的问题是您无法使 if 语句中的参数成立吗?尝试将其设置为 boolean 值而不是 int/string,并且在整个代码中将 quit 更改为 true/false 而不是数字/字符串。

编辑:哦,我明白了。所以你只想让用户按下一个键就会退出,就像“请输入 Y 退出程序”您设置了扫描仪吗?

关于java - 尝试关闭控制台时输入不匹配错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34245681/

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