将字符串转换为整数 JOptionPane

Converting String to Integer JOptionPane

我正在尝试从用户那里获取整数(年龄)的输入。但我不断收到“字符串无法转换为字符串”和“二元运算符 '<='and '>=' 的错误操作数类型。任何帮助将不胜感激

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

我建议首先从 JOptionPane 获取值作为 String

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

然后检查用户是否输入了内容然后将其解析为Integer

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

通过 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:");
            }

完整代码

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


    }
}