如何读取字符串中的字符并根据输入返回?

时间:2015-10-26 15:48:32

标签: java string java.util.scanner

这就是我所拥有的:我想制作一个程序,要求用户输入:你的名字。

这是我需要帮助的:然后,我希望程序读取名称中的每个字符,字母。最后,我希望它返回与用户名中每个字符对应的形容词列表。

这是我到目前为止所做的:

public static void main (String [] args) {

    System.out.println("This program will give meanings to every "
                        + "letter in your name.\n");

    Scanner input = new Scanner (System.in);
    System.out.println("Please enter your name:");
    String name = input.next();

    String A = "adventurous";
    String B = "bold";
    String C = "caring";
    String D = "devoted";
    String E = "encouraging";
    String F = "funny";
    String G = "gentle";
    String H = "honest";
    String I = "intelligent";
    String J = "joyful";
    String K = "kind";
    String L = "loving";
    String M = "mature";
    String N = "neat";
    String O = "organized";
    String P = "persistent";
    String Q = "quick";
    String R = "religious";
    String S = "sensitive";
    String T = "thankful";
    String U = "useful";
    String V = "virtuous";
    String W = "witty";
    String X = "this letter isn't in your name";
    String Y = "young";
    String Z = "zany";  
}

2 个答案:

答案 0 :(得分:3)

将你的形容词放在Map中(以char作为键和形容词作为值)而不是使用这些字符串,然后将名称转换为CharArray,迭代它并为每个字母只从地图中获取项目。您可以将您的形容词放入列表中,然后再打印出来。

//create the map and the list of adjectives
Map<Character, String> adjectives = new HashMap<>();
List<String> personAdjectives = new ArrayList<>();
//fill the map (although it would be better retrieving data from a database)
adjectives.put('a',"adventurous");
adjectives.put('b',"bold");
// ...
//convert the name to a char array
char[] chars = name.toCharArray();
//iterate over it
for(char c : chars){
  //access the map and fill the list
  personAdjectives.add(adjectives.get(c));
}
//print the list

答案 1 :(得分:-1)

#我希望这可以帮助#

我没有足够的时间,所以总结一下这段代码,您可以自己工作

import java.io.*;

public class StringRead
{
    
    public static void main(String[] arg){
        
        String hi = "hi all man and sexy.";
        
        for(int x = 0; x < hi.length(); x++){
            
            System.out.println(hi.charAt(x));
            
        }
        
        
    
    
    }
}