如何将扫描器的输入与Java中的字符串数组相关联?

时间:2014-09-26 16:55:36

标签: java

这就是我所拥有的:

String[] LettersOne = new String[] {"A", "B", "C"};
String[] LettersTwo = new String[] {"D", "E", "F"};
String[] LettersThree = new String[] {"G", "H", "I"};
String[] LettersFive = new String[] {"J", "K", "L"};
String[] LettersSix = new String[] {"M", "N", "O"};
String[] LettersSeven = new String[] {"P", "Q", "R", "S"};
String[] LettersEight = new String[] {"T", "U", "V"};
String[] LettersNine = new String[] {"W", "X", "Y", "Z"};

Scanner input = new Scanner(System.in);
System.out.print("Enter an uppercase letter: ");
String Letter = input.next();

我想要做的就是让用户输入的大写字母,它会打印出一个指定的数字(我还没有做)。

因此,如果Letter来自LettersOne,那么系统将打印出指定的数字。

我是编程新手,所以我还在学习。可以这样做吗?怎么样?

2 个答案:

答案 0 :(得分:2)

你的方法会起作用,但会变得非常混乱。我建议使用HashMap,它允许您将字符串与它们映射到的整数相关联。

你可以从头开始:

HashMap<String, Integer> myMap = new HashMap<String, Integer>();
myMap.put("A", 1);
myMap.put("B", 1);
myMap.put("C", 1);
myMap.put("D", 2);
// and so on

或者,您可以保留阵列并执行此操作:

HashMap<String, Integer> myMap = new HashMap<String, Integer>();
for(String letter : LettersOne) { //agh, please use camel case!
    myMap.put(letter,1);
}
for(String letter : LettersTwo) { //agh, please use camel case!
    myMap.put(letter,2);
}

这允许您存储单个字母并将其关联到数字。因为这是一次学习经历,所以我会让你阅读文档以确定如何获得int。

答案 1 :(得分:0)

如果你真的想要使用你的数组结构,可以通过拥有一个数组数组来实现。这是一个示例脚本:

Enter an uppercase letter: X
Array number: 8; letter number 2

以下是代码:

String[] lettersOne = {"A", "B", "C"};
String[] lettersTwo = {"D", "E", "F"};
String[] lettersThree = {"G", "H", "I"};
String[] lettersFour = {"J", "K", "L"};
String[] lettersFive = {"M", "N", "O"};
String[] lettersSix = {"P", "Q", "R", "S"};
String[] lettersSeven = {"T", "U", "V"};
String[] lettersEight = {"W", "X", "Y", "Z"};
boolean found; // set to true once we've found the letter.

String[][] arrayOfArrays
      = {lettersOne, lettersTwo, lettersThree, lettersFour, 
          lettersFive, lettersSix, lettersSeven, lettersEight};

Scanner input = new Scanner(System.in);
System.out.print("Enter an uppercase letter: ");
String letter = input.next();

found = false; // we haven't found it yet.

// loop through each of our arrays, and loop through each letter in each array.
for(int arrayNum = 0; (arrayNum < arrayOfArrays.length) && !found; arrayNum++) {
    // look through this array
    String[] thisArray = arrayOfArrays[arrayNum];
    for(int letterNum = 0; letterNum < thisArray.length; letterNum++) {
        String thisLetter = thisArray[letterNum];
        if (thisLetter.equalsIgnoreCase(letter)) {
            System.out.println("Array number: " + (arrayNum + 1) + "; letter number " + (letterNum+1));
            found=true;
            break;
        }
    }
}