netbeans 检查字符串中是否有句点

ohtdti5x  于 2023-05-07  发布在  其他
关注(0)|答案(1)|浏览(174)

我在Java应用程序中做计算器,在那里我有更多的文本字段,并根据哪个用户选择我扫描它的值,然后与他们一起工作。这部分是工作,但我试图添加小数点的期间按钮。这个代码我试过了,它不工作。
当用户点击点按钮时,我尝试了这个方法:

Number = Double.parseDouble(DisplayFocus.getText());
HelpS = Double.toString(Number);

if(HelpS.contains(".")){ //here im trying to find out if there is any period in the number
           Period ++;  //if there is, i put in into this counter
            }
        else{
                if(Period == 0){ //if the counter is zero, it means there is no period 

                    Number = Double.parseDouble(DisplayFocus.getText());
                    DisplayFocus.setText(DisplayFocus.getText()+"."); //so i can add the period

                }
        }
        
        Period = 0; //so i can check the piriod next time

HelpS用于将double转换为String
在这一刻,它甚至没有添加点。我想让它检查数字中是否有点,如果没有,我可以添加一个。问题是,我需要它检查它每次我试图添加一个,因为你可以点击一个文本字段和写点,然后做同样的事情,在另一个,然后你可以回到第一个。
所以我只需要它在每个文本字段中只接受一个句点,但我真的不知道,为什么这不起作用。感谢大家的帮助。

5w9g7ksd

5w9g7ksd1#

我觉得你不需要经期计数器。我设想当用户单击句号按钮时,您发布的代码将被触发。如果是的话,你检查这个数字是否已经有句号,如果有,你什么也不做,如果没有,你就加它。

Number = Double.parseDouble(DisplayFocus.getText());
HelpS = Double.toString(Number);

if(!HelpS.contains(".")){
    DisplayFocus.setText(DisplayFocus.getText()+".");
}

相关问题