1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Rep Power

    JOption input validation

    I have this very simple beginner program for my java class. I cannot seem to grasp why my if statement is not being executed when the correct input is entered. I know I could probably get the user to enter a number which I could convert and run through a switch but I really have to know why this doesn't work, I've been reading through JOption forums for the past hour and I guess I'm not seeing my solution.

    I am probably not comprehending something so simple and fundamental. I rightfully deserve any tongue/keyboard lashing.

    Thanks in advance,

    import javax.swing.*;
    public class Week04_InternetServiceProvider_michaelBrooks {
    	public static void main(String[] args) {
    		String input;
    		String internetType;
    		double hours = 0;
    		double overages = 0;
    		double internetPlanA = 9.95;
    		//double internetPlanB = 13.95;
    		//double internetPlanC = 19.95;
    		input = JOptionPane.showInputDialog("What type of internet package do you you have? Enter A, B or C").toUpperCase();
    		internetType = input;
    		input = JOptionPane.showInputDialog("How many hours did you use?");
    		hours = Double.parseDouble(input);
    		if (internetType == "A"){
    			if (hours >10) {
    				overages = hours - 10;
    				overages *= 2;
    				internetPlanA += overages;
    			JOptionPane.showMessageDialog(null, "Your total monthly bill is: $" + internetPlanA);
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Rep Power
    Change the line:

    		if (internetType == "A"){

    		if (internetType.equals("A")){
    The reason is that a String is handled like an Object. To perform equality checks with a String (and any other Object or subclass of Object) you use the 'equals'-method. Frankly, the == operator is also an equality operator for objects, but it checks if the references are equal (or in other words: if both objects are on the same memory position).
    This only holds for objects. If you want to test for equality with primitive types, such as int, byte, boolean, char, then you can use the == operator

IMN logo majestic logo threadwatch logo seochat tools logo