【发布时间】:2016-07-02 23:32:23
【问题描述】:
编辑:对,我忘了说明问题——事实上我得到了0 作为输出。
上下文
我的程序旨在获取用户输入的数字字(1-99)并将其输出为整数(即三十四 = 34)。我不知道代码中的错误在哪里,需要帮助:
Scanner scInput = new Scanner(System.in);
String word = scInput.nextLine(); //number in word-form (i.e. twenty six)
char[] charArray = word.toCharArray();//string to char array for word^
int divider = 0; //position of hyphen/space in charArray
所有 2 字数字均由一个十位值和一个个位值组成。假设语法正确 [english],连字符/空格 divider 之前的单词是十位,divider 之后的单词是个位。
阵列
//word values - components & syntax (1-99)
//ONES
public static final String[] wONES = {"one","two","three","four","five","six","seven","eight","nine"};
//TENS
public static final String[] wTENS = {null,"twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"};
//TEENS
public static final String[] wTEENS = {"ten", "eleven", "twelve", "thirteen","fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"};
我已将所有单词组件组织成 3 个不同的数组:ones、tens 和 teens。
//equivalent integer-array of above String arrays
//ONES
public static final int[] nONES = {1,2,3,4,5,6,7,8,9};
//TENS
public static final int[] nTENS = {0,20,30,40,50,60,70,80,90};
//TEENS
public static final int[] nTEENS = {10,11,12,13,14,15,16,17,18,19};
我创建了 3 个与上述三个数组相同的其他数组,除了它们存储整数值。
代码
在这里,我将用户输入的字符串分成两部分:十位和个位。所以如果数字是 72:70 = 十,2 = 个。
int tensValue = 0; //number's tens value (i.e. 30)
int onesValue = 0; //ones value (i.e. 3)
char[] tensArray = null; //array storing tens section of word (before divider)
for (int u = 0; u < divider; u++){
tensArray[u] = charArray[u];
}
String tens = new String(tensArray); //convert char array to String
char[] onesArray = null; //array storing ones section of word (after divider)
for (int u = divider + 1; u > divider && u < charArray.length; u++){
onesArray[u] = charArray[u];
}
String ones = new String(onesArray);
//searches for matches in String array for tens
for(int u = 0; u < wTENS.length; u++){
if(tens.equals(wTENS[u])){
tensValue = nTENS[u];
total += tensValue;
}
}
//searches for matches in String array for ones
for(int u = 0; u < wONES.length; u++){
if(ones.equals(wONES[u])){
onesValue = nONES[u];
total += onesValue;
【问题讨论】:
-
对于初学者来说,
char[] tensArray = null;应该类似于char[] tensArray = new char[10];