use*_*204 0 java if-statement string-substitution
我有一个简单的替换应用程序,用户输入一个字符串,该字符串被分为子串,然后每个字符替换一个数字.
我遇到的麻烦只是最后一组替换被采取行动,或者至少如果前两个正在工作它们被取消并返回"0".
因此,对于"abc"的输入,我需要输出"123"但是我得到"003",或者如果输入是"bcd",则输出应该是"234"但是我得到"004".
我哪里错了?
JButton button_1 = new JButton("Substitute");
button_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String str = textField_1.getText();
String str0 = str.substring(0);
int val1 = 0;
if (str0.equalsIgnoreCase("a")) { val1 += 1; }
if (str0.equalsIgnoreCase("b")) { val1 += 2; }
if (str0.equalsIgnoreCase("c")) { val1 += 3; }
if (str0.equalsIgnoreCase("d")) { val1 += 4; }
String str1 = str.substring(1);
int val2 = 0;
if (str1.equalsIgnoreCase("a")) { val2 += 1; }
if (str1.equalsIgnoreCase("b")) { val2 += 2; }
if (str1.equalsIgnoreCase("c")) { val2 += 3; }
if (str1.equalsIgnoreCase("d")) { val2 += 4; }
String str2 = str.substring(2);
int val3 = 0;
if (str2.equalsIgnoreCase("a")) { val3 += 1; }
if (str2.equalsIgnoreCase("b")) { val3 += 2; }
if (str2.equalsIgnoreCase("c")) { val3 += 3; }
if (str2.equalsIgnoreCase("d")) { val3 += 4; }
textField_2.setText(""+Integer.toString(val1)+(val2)+(val3));
}
});
button_1.setBounds(315, 50, 90, 25);
panel.add(button_1);
Run Code Online (Sandbox Code Playgroud)
String str0 = str.substring(0);返回从位置0开始并在原始字符串结尾处结束的子字符串.因此,在您的情况下,它返回"abc",您将其与"a"进行比较.
你可以String str0 = str.substring(0,1);改用.
或者作为评论,您可以单独查看每个角色:
String str = textField_1.getText();
int[] vals = new int[3];
//you should check that your string is at least 3 characters long
String lower = str.toLowerCase(); //no need to equalsIgnorCase any more
for (int i = 0; i < 3; i++) { //loop over the first 3 characters
char c = lower.charAt(i);
if (c >= 'a' && c <= 'd') vals[i] = c - 'a' + 1; //populate the array
}
textField_2.setText("" + Integer.toString(vals[0]) + (vals[1]) + (vals[2]));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
112 次 |
| 最近记录: |