Java输入阅读和匹配帮助 [英] Java input reading and matching Help
问题描述
import java.util.Scanner;
import java.util.Random;
import java.io.*;
public class Placeholdername {
public static void main(String args[]){
InputStreamReader keyboard = new InputStreamReader(System.in) ;
BufferedReader bufRead = new BufferedReader(keyboard) ;
System.out.println("Some text goes here");
System.out.println("Which way do you want to go? North, East, West, South.");
String userinput = bufRead.readLine();
//NORTH ROUTE:
if (userinput) == ("North")
所以最后一行是我需要的帮助,我尝试了所有我知道并找到的方法。那么,我如何读取用户输入并查看它是否匹配北方或任何其他单词?
so that last line is what i need help with i've tryed all the methods i know and have found. So, how do i read the user input and see if it maches North or any other word?
推荐答案
我认为您可以尝试类似:
I think you can try something like:
if (userinput.contains("North"))
System.out.println("It is North"); //do whatever you want
else if (userinput.contains("East"))
System.out.println("It is East");
else if (userinput.contains("West"))
System.out.println("It is West");
else if (userinput.contains("South"))
System.out.println("It is South");
else
System.out.println("None of these");
假设您的程序用户应该只使用提供的单词路由,然后您可以尝试以下:这假设您使用JDK 1.7进行带字符串的切换。
On the assumption that the user of your program is supposed to use only the provided words for routes, then you can try the following: This assumes you're using JDK 1.7 for switch with strings.
switch(userinput.readLine().toUpperCase()){
case "NORTH":
// North Route
break;
case "SOUTH":
// South Route
break;
case "EAST":
// East Route
break;
case "WEST":
// West Route
break;
default:
// Throw Error or Show message
}
但是,如果您使用的是JDK 1.6或更低版本,则可以通过以下方式实现代码:
However, if you're using JDK 1.6 or below, you can implement your code in the following way:
String input = userinput.readLine().toUpperCase();
if(input.equals("NORTH"))
// North
else if(input.equals("SOUTH"))
// South
else if(input.equals("EAST"))
// East
else if(input.equals("WEST"))
// West
else
// Throw Error or Show message
但是,如果上述解决方案都不适合您,您可以查看 Java的正则表达式API [ ^ ]或 Java的正则表达式教程 [ ^ ]。
如果这符合您的要求,您可以随时将其标记为已接受的解决方案并对其进行投票,以便其他人也可以从中受益。
However, if neither of the above solutions work for you, you can check Java's Regular Expressions API[^] or the Java's Regular Expression Tutorial[^].
In case this satisfies your requirements, you can always mark it as an accepted solution and upvote it so that others may also benefit from the same.
这篇关于Java输入阅读和匹配帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!