【问题标题】:Converting String to Integer JOptionPane将字符串转换为整数 JOptionPane
【发布时间】:2021-06-14 23:36:53
【问题描述】:

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

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

【问题讨论】:

  • String response 更改为 Integer response
  • 非常感谢,我花了 2 个小时才弄清楚这一点,哈哈
  • 如果用户没有输入任何值,您的程序将无法运行。
  • 嗯,好的 nvm,我该如何解决这个问题?
  • 在您的问题上添加错误的堆栈跟踪总是好的。

标签: java string compiler-errors integer


【解决方案1】:

我建议首先从 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");
        }


    }
}

【讨论】:

  • 只要用户输入一个值,程序就会结束。我猜因为'responseToInt'被赋值为0?我对 Java 很陌生,所以请多多包涵@Typhon
  • 尝试输入2.你会发现不是因为它没有分配0
  • 只有当数字是 =1 时才会响应,就像你提到的那样
  • 是的,但是当我输入数字 1 - 3 时,程序就结束了。我只是猜测因为变量“responseToInt”被声明并赋值为0,所以程序刚刚结束0不是婴儿乳液的条件吗?
  • 0 它只是作为起点,在接受用户输入后,整数被分配一个新值
猜你喜欢
  • 2021-09-13
  • 1970-01-01
  • 1970-01-01
  • 2012-02-21
  • 2010-12-31
相关资源
最近更新 更多