简体   繁体   English

将特定的字符串字符索引替换为0

[英]Replace a specific string character index into 0

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. 因此,首先,该动作事件将从名为field的文本字段按钮获取getText。 After that it will convert the string into int. 之后,它将字符串转换为int。 But, I want to check one thing before converting the string into int. 但是,我想在将字符串转换为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 也就是说,我想检查字符串索引[0]是否等于'-',如果是,那么它将被更改为0。

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

but it is saying condition is not comparable from char to string. 但是说条件从char到string是不可比的。 Is there any other way to replace an index character into 0? 还有其他方法可以将索引字符替换为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': 我试过下面的代码,但我不知道如何将'text'分配给'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); 当新字符串设置为'str'而不是'text'时,我无法将str分配为字符串,例如StringBuilder str = new StringBuilder(str); Therefore; 因此; I am basically stuck in this line. 我基本上陷入了这一行。

In : 在:

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

Moreover, you should never use == on a Character or a String. 而且,永远不要在字符或字符串上使用== Use equals() instead. 使用equals()代替。

Try 尝试

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

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

"a" - String “ a”-字符串

'a' - char 'a'-字符

text.charAt[0] == "-"

In this line checking a string "-" change it as '-' 在此行中,检查字符串"-"将其更改为'-'

Instead of == , use equals() as follows: 代替== ,使用equals()如下:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM