我需要if语句的帮助。如果故障单没有以特定字符串开头,那么它会提示“无效,再试一次”,票证示例为BA200
public class Game
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter Ticket");
String ticket = keyboard.nextLine();
if(ticket=("AB"|| "ab" || "BA" || "ba" || "CB" || "cb"))
{
System.out.println("correct");
}
else
{
System.out.println("invalid, try again");
}
}
}
答案 0 :(得分:3)
使用startsWith方法:
import java.util.Scanner;
public class Game
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter Ticket");
String ticket = keyboard.nextLine();
if(ticket.toUpperCase().trim().startsWith("AB") ||
ticket.toUpperCase().trim().startsWith("BA") ||
ticket.toUpperCase().trim().startsWith("CB") )
{
System.out.println("correct");
}
else
{
System.out.println("invalid, try again");
}
}
}
答案 1 :(得分:2)
它可以给:
List<String> validPrefixes = Arrays.asList("AB","BA","CB");
if(ticket.length() >=2 && validPrefixes.contains(ticket.subString(0,2).toUpperCase()){
System.out.println("correct");
}
答案 2 :(得分:2)
将您的if
声明更改为以下内容:
if(ticket.toUpperCase().startsWith("AB") ||
ticket.toUpperCase().startsWith("BA") ||
ticket.toUpperCase().startsWith("CB") )