如何将数字转换为仅包含循环的字符串?

时间:2014-05-27 23:02:17

标签: java loops

Scanner input=new Scanner(System.in);
String s=input.nextLine();
int a=s.length();
String v;
int[] arrayno={1,2,3,4,5,6,7,8,9,10};
char b;
String[] array={"one","two","three","four","five","six","seven","eight","nine","ten"};
for(int i=0;i<a;i++)
{    
    b=s.charAt(i);
    if(b==arrayno[i])
    {
        v=array[i];
        System.out.println(v);
    }
    else   
        System.out.print(b);
}

示例:

输入:

I have 3 Networking books, 0 Database books, and 8 Programming books.

输出:

I have three Networking books, zero Database books, and eight Programming books.

仅使用循环!

但是这会输出相同的短语! 我该怎么办?

2 个答案:

答案 0 :(得分:0)

以下代码仅适用于您的场景,即0-10的数字 但我觉得这不是使用数字的正确方法。

Scanner scanner=new Scanner(System.in);
String input = scanner.nextLine();

String[] numbers={"10", "9", "8", "7", "6", "5", "4", "3", "2", "1", "0"};
String[] numberInWords={"ten", "nine", "eight", "seven",
     "six", "five", "four", "three", "two", "one", "zero"};

for(int i=0; i<numbers.length; i++) {

    if(input.contains(numbers[i])) {
        input = input.replaceAll(numbers[i], numberInWords[i]);             
    }
}  

System.out.println(input);

答案 1 :(得分:0)

在我看来,使用HashMap(在java.util中)最合适,而不是两个数组。你的问题只询问使用循环的解决方案,但目前还不清楚哪些类是公平游戏,哪些不是。

我的解决方案如下:

HashMap numberMap = new HashMap<String,String>();
Scanner scan = new Scanner(System.in);

numberMap.put("0","zero");
numberMap.put("1","one");
numberMap.put("2","two");
numberMap.put("3","three");
numberMap.put("4","four");
numberMap.put("5","five");
numberMap.put("6","six");
numberMap.put("7","seven");
numberMap.put("8","eight");
numberMap.put("9","nine");
numberMap.put("10","ten");

System.out.println("Enter something:");
String input = scan.nextLine();
String[] inputArray = input.split(" ");
String output = "";

for (int i=0; i<inputArray.length; i++){
    if (numberMap.containsKey(inputArray[i])){
        output += numberMap.get(inputArray[i]);
    } else {
        output += inputArray[i];
    }
    output += " ";
}

System.out.println(output);