Frage

I have built a table chart application. I have a calculate button with an action event. So, first of all, the action event will getText from a textfield button named field. After that it will convert the string into int. But, I want to check one thing before converting the string into int. That is, I would like to check if the string character index [0] is equal to '-', if so then it will be changed to 0. I have tried to put an if condition like

if(text.charAt[0] == "-"){text.setCharAt(0, "0")}

but it is saying condition is not comparable from char to string. Is there any other way to replace an index character into 0?

Here's the action listener code:

calculate = JButton; result = JTextArea; field = JTextField;
calculate.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent evt) {
    result.setText(null);
    String text = field.getText();
    Integer i = Integer.valueOf(text);
    for (int j = 1; j <= 10; j++){
    result.append((i + " " + "x" + " " + j + "=" + " " +(i * j)) + "\n");
}});

I have tried the code below but i can't figure out how to assign 'text' to 'str':

    if(text.charAt(0) == '-'){
     StringBuilder str = new StringBuilder(text);
     str.setCharAt(0, '0');
}        

Moreover; when the new string is set to 'str' instead of 'text', I could not assign str as a string, such as StringBuilder str = new StringBuilder(str); Therefore; I am basically stuck in this line.

War es hilfreich?

Lösung

In :

text.charAt[0] == "-"
  • text.charAt[0] is a char.
  • "-" is a String.

Moreover, you should never use == on a Character or a String. Use equals() instead.

Try

text.charAt[0].equals('-');

Andere Tipps

try if(text.charAt[0] == '-'){text.setCharAt(0, '0')}

"a" - String

'a' - char

text.charAt[0] == "-"

In this line checking a string "-" change it as '-'

Instead of == , use equals() as follows:

text.charAt[0].equals('-')
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top