ArchR0n1n
ArchR0n1n

Reputation: 3

Converting String to Integer JOptionPane

Am trying to get an input from user as an integer (age). 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);
    }
}

Upvotes: 0

Views: 125

Answers (1)

Dren
Dren

Reputation: 1099

I suggest first getting the value from JOptionPane as a String

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

Then checking if the user has entered something then parse it to Integer

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

With try and catch, we can limit that the user should enter only numbers.

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


    }
}

Upvotes: 1

Related Questions