简体   繁体   English

将字符串转换为 Integer JOptionPane

[英]Converting String to Integer JOptionPane

Am trying to get an input from user as an integer (age).我试图从用户那里得到一个输入作为 integer(年龄)。 But I keep getting "String cannot be converted to string" and "bad operand types for binary operator '<='and '>='. Any help will be much appreciated但我不断收到“字符串无法转换为字符串”和“二进制运算符'<='和'> ='的错误操作数类型。任何帮助将不胜感激

import javax.swing.JOptionPane;
class LotionFinder {
    public static void main(String[] args) {
        String response;
        response = Integer.parseInt(JOptionPane.showInputDialog ("Please Enter Your Age:"));
        if (response == null) {
            JOptionPane.showMessageDialog(null, "Please Contact a Sales Representative For a Private Consultation");
        } else if (response.equals("")) {
            JOptionPane.showMessageDialog(null, "Please Contact a Sales Representative For a Private Consultation");
        } else if (response <= 3 && response >= 1){
            JOptionPane.showMessageDialog(null, "It's Recommended That You Purchase Our No-Tears Baby Lotion!");
            
        }
        

        System.exit (0);
    }
}

I suggest first getting the value from JOptionPane as a String我建议首先从 JOptionPane 获取值作为String

String response = JOptionPane.showInputDialog ("Please Enter Your Age:");

Then checking if the user has entered something then parse it to Integer然后检查用户是否输入了某些内容,然后将其解析为Integer

     if (response.length() !=0) {
    responseToInt = Integer.parseInt(response);

With try and catch, we can limit that the user should enter only numbers.通过 try and catch,我们可以限制用户只能输入数字。

            try {
                responseToInt = Integer.parseInt(response);
            }catch (NumberFormatException e){
                System.out.println("Please enter a number");
                 response = JOptionPane.showInputDialog ("Please Enter Your Age:");
            }

FULL CODE完整代码

 public static void main(String[] args) {
        Integer responseToInt = 0;
       String response = JOptionPane.showInputDialog ("Please Enter Your Age:");
        if (response.length() !=0) {
            try {
                responseToInt = Integer.parseInt(response);
            }catch (NumberFormatException e){
                System.out.println("Please enter a number");
                 response = JOptionPane.showInputDialog ("Please Enter Your Age:");
            }
        }  if (responseToInt <= 3 && responseToInt >= 1){
            JOptionPane.showMessageDialog(null, "It's Recommended That You Purchase Our No-Tears Baby Lotion!");

        }else{
            JOptionPane.showMessageDialog(null, "Please Contact a Sales Representative For a Private Consultation");
        }


    }
}

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

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