当前位置: 动力学知识库 > 问答 > 编程问答 >

Java - Multiple if statements but only the last is acted upon

问题描述:

I have a simple substitution app, the user inputs a string which is divided into substrings, then each character is substituted for a number.

The trouble I have is only the last set of substitutions is acted on, or at least if the first two are working they are being nulled and return "0".

So for an input of "abc" I need an output of "123" but I'm getting "003", or if the input was "bcd" the output should be "234" but I'm getting "004".

Where am I going wrong?

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);

网友答案:

String str0 = str.substring(0); returns a substring starting a position 0 and ending at the end of the original string. So in your case it returns "abc", which you compare to "a".

You can use String str0 = str.substring(0,1); instead.

Or as commented, you can look at each character individually:

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]));
网友答案:

This gives you everything from the first character e.g. "abc" which will not be equal to "a"

String str0 = str.substring(0);

What you intended may have been

String str0 = str.substring(0, 1);

BTW a simpler way to do much the same thing.

String str = "abc";
StringBuilder sb = new StringBuilder();
for (char ch : str.toCharArray())
    sb.append(ch % 32);
System.out.println(sb.toString());

prints

123
分享给朋友:
您可能感兴趣的文章:
随机阅读: