Switch Statement not initializing value

I'm taking a basic JAVA class and one of our assignments is to use the switch statement to determine the price of a product the add up the total of all products entered at the end. The code below won't compile because it says that "price" isn't initialized. If I initialize the variable as "0.0" then when the program finishes it is still "0.0" which means the switch section isn't working. Can anyone tell me why this isn't working?
import java.util.Scanner;
public class Product
public static void main( String args[] )
     Scanner input = new Scanner(System.in);
     int product;
     int quantity;
     double price;
     double total = 0.0;
     System.out.print("Enter product number: ");
     product = input.nextInt();
     while (product != -1)
          System.out.print("Enter quantity: ");
          quantity = input.nextInt();
          switch (product)
               case 5:
                    price = 6.87;
                    break;
               case 4:
                    price = 4.49;
                    break;
               case 3:
                    price = 9.98;
                    break;
               case 2:
                    price = 4.50;
                    break;
               case 1:
                    price = 2.98;
                    break;
               default:
                    System.out.print("Invalid product number");
                    break;
          total = total + price;
          System.out.println("Enter product number: (-1 to quit)");
          product = input.nextInt();
     System.out.printf("Total retail value of product is: $%.2f", price);
Thanks for any help!
Nathan

I think the correct code should be:
import java.util.Scanner;
public class Product
public static void main( String args[] )
     Scanner input = new Scanner(System.in);
     int product;
     int quantity;
     double price = 0.0;
     double total = 0.0;
     System.out.print("Enter product number: ");
     product = input.nextInt();
     while (product != -1)
          System.out.print("Enter quantity: ");
          quantity = input.nextInt();
          switch (product)
               case 5:
                    price = 6.87;
                    break;
               case 4:
                    price = 4.49;
                    break;
               case 3:
                    price = 9.98;
                    break;
               case 2:
                    price = 4.50;
                    break;
               case 1:
                    price = 2.98;
                    break;
               default:
                    System.out.print("Invalid product number");
                    break;
          total = total + (price*quantity);
          System.out.println("Enter product number: (-1 to quit)");
          product = input.nextInt();
     System.out.printf("Total retail value of product is: $%.2f", total);
}

Similar Messages

  • Java switch statement

    Is it possible to have a switch statement for multiple values. By this i mean, if a user types in a number between 1-3, it should print out the line
    System.out.println("Well done you got a First");break; So can i have a switch statement which is like
    case 1-3:  System.out.println("Well done you got a First");break;

    This will work:
    case 1:
    case 2:
    case 3:
       System.out.println("Well done you got a First");
    break;No, there's no way to express a "range" in a case statement though.

  • Whether or not remember values if switching tabs using ShowOneTab component

    I am using ShowOneTab and ShowDetailItem components.
    I have 4 ShowDetailItems inside showOneTab (let me say there are tab1,tab2,tab3,tab4)
    The default tab is tab1, and I input data, select some values. Then I switch to tab2, do the same thing. Now I switch back (tab1). I'd like to see the values are still there (not the initial values).
    Is it possible?
    I know that tab content indeed is not accessible if the tab is disclosed.
    Any ideas / help will appreciate.
    Thanks
    Joyce

    Hi,
    if the values you set are persisted in the model or a session scoped managed bean, then this works fine using EL
    Frank

  • Enum class not supported for switch() statement in 12.4 beta?

    Hi fellow 12.4 beta testers,
    It would appear "enum class" isn't supported for switch() statements in the 12.4 beta. This compiles fine under clang and g++. Will this be fixed for the final release? This currently causes compile errors for us, since __cplusplus >= 201103L evaluates to true, so our code uses "enum class" instead of plain "enum". It looks like the C++11 standard says it should be supported:
       Switching on enum class in C++ 0x - Stack Overflow
    Many thanks,
    Jonathan.
    $ cat test.cpp
    #include <iostream>
    enum class Ternary { KnownFalse = 0, KnownTrue = 1, Unknown = 2 };
    int main( void )
       Ternary foo;
       switch ( foo ) {
          case Ternary::KnownTrue:
          case Ternary::KnownFalse:
          case Ternary::Unknown:
             std::cout << "Success\n";
    $ clang++ -std=c++11 test.cpp
    $ g++ -std=c++11 test.cpp
    $ /opt/SolarisStudio12.4-beta_mar14-solaris-x86/bin/CC -std=c++11 test.cpp
    "test.cpp", line 8: Error: Cannot use Ternary to initialize integral type.
    "test.cpp", line 8: Error: Switch selection expression must be of an integral type.
    "test.cpp", line 9: Error: An integer constant expression is required for a case label.
    "test.cpp", line 10: Error: An integer constant expression is required for a case label.
    "test.cpp", line 11: Error: An integer constant expression is required for a case label.
    5 Error(s) detected.

    Thanks for reporting this problem! I have filed bug 18499900.
    BTW, according to the C++11 standard, the code is actually not valid. Section 6.4.2, switch statement, says an implicit conversion to an integral type is required, which is not the case for for a scoped enum (one using the "class enum" syntax). This limitation was raised in the C++ Committee as an issue to be fixed, and the C++14 standard makes the code valid.
    As a workaround, or to make the code conform to C++11, you can add casts to int for the enum variable and the enumerators.
    Message was edited by: Steve_Clamage

  • Shared Variable Initial value not licenced error with cRIO

    Hello Everyone,
    I've a project that will be deploed on cRIO. This project was created on a different machine and didn't have any error regarding the shared variables. when I transfered the project to the computer connected to the cRIO, I have this error with all shared variable. The error message says that:
    1. Initial Values: Not Licenced or can't be edited outside of LabVIEW.
    2. Logging: Not Licenced or can't be edited outside of LabVIEW.
    attached are two images for the error i have.
    Can I have help with this issue?
    Thanks in advance
    Attachments:
    1.png ‏134 KB
    2.png ‏142 KB

    Good day,
    Sounds like you are using the DSC module features on your code and you forgot to activate the runtime system on that machine. If you have access to the NI License Manager, please check the status of the license.
    We need an active license for the second message but, for the first one you can try to program your own initial values for all of your network-published shared variables by initializing whenever the PC is started. During the initialization portion of your code, you can just write a constant value to the shared variables so the values are the same initial values every time it is run.
    Regards,
    Alejandro | Academic Program Engineer | National Instruments

  • Default case not working in a switch statement

    I get a run-time error when i input other flavor than the three listed in the code.
    Any comments and suggestions are welcomed.
    import java.util.Scanner;
    public class EnumSwitchDemo
         enum Flavor {VANILLA, CHOCOLATE, STRAWBERRY};
         public static void main(String[] args)
              Flavor favorite = null;
              Scanner keyboard = new Scanner(System.in);
              System.out.println("What is your favorite flavor? ");
              String answer = keyboard.next();
              answer = answer.toUpperCase();
              favorite = Flavor.valueOf(answer);          
              switch(favorite)
                   case VANILLA:
                        System.out.println("Classic");
                        break;
                   case CHOCOLATE:
                        System.out.println("Rich");
                        break;
                   case STRAWBERRY:
                        System.out.println("Tasty");
                        break;
                   default:
                        System.out.println("Sorry, Flavor unavailable");
                        break;
    }

    Yes, the static valueOf method of an Enum type throws an IllegalArgumentException, if the name is not defined, I think. So the problem is not the switch statement.
    Btw, normally you don't need switch statements with enums, since you can define methods in enums.
    -Puce

  • Hp laser jet m1005 mfp is in initializing state not coming to ready how can i solve it

    hp laser jet m1005 mfp is in initializing state not coming to ready how can i solve it

    Me too. I have this exact same problem. Can anyone help?

  • Form text item initial value not taking effect

    Hello,
    Sorry for the simple question, but I'm at a loss.
    I'm trying to present a system date on my form using $$DATE$$ as the initial value of a text item. The form will not display it. Am I running up against a bug, or is there a block setting that might be getting in the way? Possibly an OAS issue? The item is in a control block, and the form is insanely simple. It makes use of menu as well.
    Any help is appreciated,
    Jim

    I tried setting the initial value to $$DATE$$ in a control block item in Forms 10g (9.0.4), and it worked fine. I think the online help is referring to creating a record in a block (not the database), which happens in a control block as well as a base table block.
    Not sure what version of Forms you are using, but in the unlikely chance that you're still on 6.0, there are some bugs (1046279, 2970983) filed on 6.0 about the initial value not displaying when the text item is subclassed from an object library. If that's what you're experiencing, you should be able to fix it by upgrading to 6i.

  • Break statement not working in switch case

    Hi,
    I've run into this problem multiple times and have looked up the syntax for a switch statement. The problem with the code below is that when it goes into the first case, it executes the break statement but still executes the next case instead of breaking out of the switch case. Can anyone see whats going wrong?
    try
                switch (columnProps.getCellType())
                     case (ExcelConstants.CELL_TYPE_STRING):
                         excelCell.setCellValue(iterator.getCurrentColumnStringValue());
                         break;
                     case (ExcelConstants.CELL_TYPE_NUMERIC):
                         excelCell.setCellValue(iterator.getCurrentColumnIntValue());
                         break;
    catch (Exception e)
    System.out.println(e.toString()):
           

    it executes the break statement but
    still executes the next case instead of breaking out
    of the switch case. Can anyone see whats going wrong?You can if you put in traces (print statements) in proper places. This will allow you to exactly follow the switch behaviour.

  • Switch statement and case variables

    Since constant variables do not have to be initialized when declared, they could be initialized later based on conditional logic and used to make the Switch statement more useful by using them as case labels. Well, sounds good in theory but I can't find anyway to make it work.
    I can't even get this to compile when the value of the case label is obvious at compile time :
    public class Switchtest
    public static void main(String[] args)
    int test = 0;
    final int x;
    x = 1;
    switch (test)
    case x: System.out.println("case x " );break;
    default: System.out.println("Default ");break;
    It gives an error about expecting x to be constant. I've tried static initializer blocks, etc. Is there anyway to have the case label variables initialized at runtime to make the Switch statement more useful?

    If jvm can use a hashtable for a switch statement. This hashtable is as constant as the compiled code, i.e., it can be defined at compile- time and it con not be modified runtime. Therefore a switch- case construction is faster than an else-if construction. But the strength of else- if is that it is more flexible. If you want to test on multiple variable values, you must use else-if
    class a
       public int method()
          int val = (int)(Math.random()*3);
          int x;
          if(val == 0)
             x = 1;
          else if(val == 1)
             x = 2;
          else
             x = 3;
          return x;
    class b
       public int method()
          int val = (int)(Math.random()*3);
          int x;
          switch (val)
             case 0:
                x = 1;
                break;
             case 1:
                x = 2;
                break;
             default:
                x = 3;
                break;
          return x;
    }b is bigger than a, but also faster. The technique used in a is more flexible, but b uses O(1) time where a uses O(n). (where n is the number of cases/else-ifs)

  • Sequence created in anon PL/SQL missing initial value

    If I create a sequence in an anonymous PL/SQL block, with execute immediate, then perform a select nextval from that sequence outside the block, it misses it's initial value.
    Easily reproducable here:
    create table tab_a ( col_a number(4) not null );
    begin
      execute immediate 'create sequence seq_a start with 47 increment by 1';
    end;
    insert into tab_a select seq_a.nextval from dual;
    select * from tab_a;
    This is a much simplified representation of the circumstance I found myself in, but it reproduces the effect I see.
    If I drop the sequence and truncate the table, and run the statements (excluding the first) again, it works as expected. If I drop the table and run all the statements again, it returns the wrong answer again.
    I don't need a workaround, the issue has been addressed long ago, but I would like to know WHY this happens. starting the sequence at 47 can be any number, it's there just to show the issue when 48 is inserted into the table. The insert could be into any table, and the from could be over any table rather than dual.
    Oracle EE 11.2.0.1.0 on OE Linux, RAC and Single node.
    TIA.

    Can you show the output you get like this? Mine is a 10g DB. But sure it would work in 11g DB as well.
    SQL> select * from v$version where rownum = 1;
    BANNER
    Oracle Database 10g Enterprise Edition Release 10.2.0.5.0 - 64bi
    SQL> drop table t;
    Table dropped.
    SQL> create table t (no integer not null);
    Table created.
    SQL> begin
      2     execute immediate 'create sequence seq start with 47 increment by 1';
      3  end;
      4  /
    PL/SQL procedure successfully completed.
    SQL> insert into t select seq.nextval from dual;
    1 row created.
    SQL> select * from t;
            NO
            47
    SQL>

  • Use of boolean variables in BPEL switch statements

    I have a workflow with a single boolean input parameter:
    <element name="input" type="boolean"/>
    I wish to use a switch statement within the workflow, based on the value of that boolean parameter.
    When I use the following XPath expression:
    bpws:getVariableData("input","payload","/tns:BooleanRequest/tns:input")
    I get the correct functionality, although I get the following BPEL compiler warning:
    " [bpelc] [Warning ORABPEL-10078]: return value of this expression may not be a boolean
    [bpelc] [Description]: in line 35 of "C:\eclipse\workspace\Boolean\Boolean.bpel", xpath expression "bpws:getVariableData("input","payload","/tns:BooleanRequest/tns:input")" used in <switch> may not return boolean type value, the xpath engine would automatically try to convert the return value to boolean..
    [bpelc] [Potential fix]: Please use one of the built-in boolean functions from xpath http://www.w3.org/TR/xpath#section-Boolean-Functions to convert the return value to boolean.."
    However, the boolean functions referenced do not appear to be relevant to a variable which is already of a boolean type. If I attempt to use the boolean() function in my XPath expression, I get rid of the compiler error, but the workflow now does not work as required.
    How can I get rid of the compiler warning and still get the required functionality, and/or am I doing the wrong thing?
    I am currently running on JBoss, with BPEL release 2.1.2 [build #1226].
    Thanks for any help or ideas.

    Hi Marlon,
    Thanks for that - I guess we have to accept the vagaries of XPath and the absence of type-checking for variables.
    I hadn't fully understood until I started investigating that I can assign ANY string to variable of type xsd:boolean, which has been the cause of some of the confusion for me - whether that value is then considered true or false depends on how you write your test condition.
    I tried with your condition, and it didn't seem to work (evaluated to true if the variable data was the string "true()", but otherwise it seemed to always evaluate to false.
    I also tried the following:
    condition="bpws:getVariableData('booleanVariable')=true()"
    but that evaluates to true for any string of length > 0.
    The only one I can get to consistently work is:
    condition="bpws:getVariableData('booleanVariable')=string(true())"
    although that means that variable data of "TRUE" will evaluate to false (may well be the correct behaviour, depending on how you're setting the boolean variable in the first place).

  • Switch Statement

    I am new to Java and am trying to learn how to use and understand the nuances involved in using the Switch statment.
    I am trying to write an application that will calculate grades for a student. I can use the If Then Else Control structure for this (which runs) but I would like to incorporate the Switch Statement in place of the multiple if then else structure. Here is the code that I have for the application:
    import javax.swing.JOptionPane;
    public class Switchgrades
    public static void main(String args[])
    String midone; String midtwo; String quiz; String homework;
    String last;
    double one; //first midterm
    double two; //second midterm
    double three;double four; double five; //final, quiz and homework scores
    double average; //GPA
    int a; int b; double c; double d; double f;int grade;
    midone = JOptionPane.showInputDialog("Please enter the first midterm"); //first score to add
    one = Double.parseDouble(midone);
    midtwo = JOptionPane.showInputDialog("please enter second midterm"); //second midterm to add
    two = Double.parseDouble(midtwo);
    last = JOptionPane.showInputDialog("please enter final exam score");//final exam score to add
    three = Double.parseDouble(last);
    quiz = JOptionPane.showInputDialog("please enter quiz score");//quiz score to add
    four = Double.parseDouble(quiz);
    homework= JOptionPane.showInputDialog("please enter homework score");//homework score to add
    five = Double.parseDouble(homework);
    average = (one + two+ three + four + five)/5; //average of all five scores
    switch (grade)
    case a: //this is where I become confused and lost. I don't what I need to do to make it run.
    {if(average >= 90)
         b = Integer.parseInt(average);
       JOptionPane.showMessageDialog(null,"The total of all your scores is " + b+"\nYour final grade is an A");}
    / I am just using one choice to make it run. When I can make it run, I plan on incorporating the other grades.
    break;
    <=====================================================================>
    <=====================================================================>
    //else --->this is part of the if that works in another program
    // if(average >= 80 )
    // JOptionPane.showMessageDialog(null,"The total of all your scores is " + average +"\nYour final grade is a B");
    //else
    //if(average >= 70 )
    // JOptionPane.showMessageDialog(null,"The total of all your scores is " + average +"\nYour final grade is a C");
    //else
    //if(average >= 60 )
    // JOptionPane.showMessageDialog(null,"The total of all your scores is " + average +"\nYour final grade is a D");
    //else
    //if(average <= 60 )
    <=====================================================================>
    <=====================================================================>
    default:
    JOptionPane.showMessageDialog(null,"Sorry, you received a grade of " + average + ". \nYou failed.");
    System.exit(0);
    As you can see, I already have all the if then else statements set up--between the <==>. The program runs with the If's but I can two error messages when I incorporate the Switch statement.
    1) constant expression required.
    I have case a and i guess it is not a constant. Again, I don't understand switch well enough to figure what I need to do to correct it.
    2)"b = Integer.parseInt(average);" - cannot resolve the symbol--whatever that means. I have a "^" pointing at the period between Integer and parseInt.
    Can anyone help explain what I have to do to make this program work using Switch.
    I have not used Switch before and don't understand what I can use as opposed to what I must use for it to work.
    Thanks for your help.

    I don't really know how you want your program going, but here is what I think.
    1) From the start of the switch statement, where do you assign the value for "grade"? If you write the switch statement like below, you meant something like, if(grade == 'a'){...}, right!? Then, where did you get the "grade" from?
    switch (grade)
    case a:
    You may want declare variable "grade" as char and place if sentence like this before the switch.
    if(average >= 90)
    grade = 'a';
    else if(average >= 70)
    grade = 'b';
    switch (grade)
    case a:
    System.out.print("Your grade: A");
    break;
    case b:
    System.out.print("Your grade: A");
    break;
    Is that What you want???
    2)The method, Integer.parseInt(), takes String as parameter? Did you override this method? The variable "average" was declare as double, so why don't you just cast it to int??

  • Keyboard Input and switch statement error

    Hi,
    Below is a program to read an alphabet and check whether its a vowel/consonent using switch statement.
    Its always executin' the default stmt and not going into the case 1. This is because the ascii value of the character is being stored rather than the character.Could you please rectify this program?
    Thanks,
    vs
    import java.io.*;
    class vowel
    public static void main(String args[])throws Exception
    System.out.println("Enter a character:");
    char ch=(char)System.in.read();
    switch(ch)
    case 1: if(ch=='a')//||ch=='e'||ch=='i'||ch=='o'||ch=='u')
    System.out.println("The character is a vowel-a");
    break;
    default: System.out.println("The character is a consonent ! ");

         ch = Character.toLowerCase(ch);
         switch (ch) {
              case 'a' :
              case 'e' :
              case 'i' :
              case 'o' :
              case 'u' :
                   System.out.println("The character is a vowel: " + ch);
                   break;
              default :
                   System.out.println("The character is a consonent ! ");
         }

  • Statement not reached

    Hi
    I need help please
    I have these 2 errors:
    Statement not reached
    Variable tv may not have been initialized
    Here my code:
    switch(index)
    TreeView test;
    case 0: test = treeView1; break;
    case 1: test = treeView2; break;
    case 2: test = treeView3; break;          
    case 3:
    classif = treeView4.getSelectedText();
    break;
    default:
    if (index != 3)
    TreeNode tn = test.getSelectedNode();
    classif = tn.getText();
    while(tn.getParent() != null)
    tn = tn.getParent();
    classif = tn.getText() + ":" + classif;     
    what is the problem ?
    Thanks

    You define variable test as a TreeView. This simply creates the variable but it is not initialized.
    For example:
    TreeView test = new TreeView();This should resolve one of the errors.
    Now, you may be wanting to initialize test with a different constructor based on your program.

Maybe you are looking for