gpt4 book ai didi

java - 比较字符串和整数 (java)

转载 作者:行者123 更新时间:2023-12-02 04:27:00 26 4
gpt4 key购买 nike

我在进行一些 Java 编程时遇到了麻烦,而且我对输入之间的比较操作数如何工作感到非常困惑。

我想要的是我的程序接受输入,分析输入,检查它等于什么,并根据输入显示一条消息。我如何将输入与 option1 进行比较我设置了变量吗?

这是一个名为 loadfile.java

的文件
package subsets;

import java.io.*;
import java.util.Scanner;

public class loadfile {

public static void main(String args[]) {

}

public static void choose(String[] args) {

// Set an option
int option1 = 1;

// Start grabbing input
System.out.print("Choose one: ");
Scanner scanner = new Scanner( System.in );
String input = scanner.nextLine();

// Parse input into an integer (expecting int)
int selection = Integer.parseInt(input);

// If input == option1, let's go with this code.
if(input.equals(option1)){

System.out.println("You choose option 1.");

}
}
}

我有loadfile.choose(args);在另一个文件中,该文件处理我将要实现的其余文件。

这是文件:otherfile.java

package subsets;

public class otherfile {

public static void main(String args[]){
System.out.println("Please select an option (using number keys): \n");
System.out.println(
"1. Option 1 \n"
+ "2. Option 2 \n"
+ "3. Option 3 \n"
+ "4. option 4 \n");

// Start analyzing their choice
loadfile.choose(args);
}

}

最佳答案

您可以将 int option1 = 1; 更改为 String option1 = "1"; 或将用户输入解析为整数,或者执行 scanner.nextInt () 而不是 nextLine 这里有很多选项可以解决这个问题。 Integer.parseInt(String)

关于java - 比较字符串和整数 (java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32018204/

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