Switch statement & system.read.in

I am attempting to code a java text program that will calculate and print out 3 different mortgage's, I am trying to use a switch statement to select which mortgages I will output. I am trying a simple switch statement first and I am stuck, Can anyone help.
//test switch case program
import java.text.*;
import java.io.IOException;
//import java.util.*;
//import java.lang.*;
public class TestIfElse
{ // start of main method
public static void main (String[] args)
          // throws java.io.IOExceptions
{//start Main
double interestRate = 0;
int year;
double loan;
char choice;
//enter # of years & find interest rate
System.out.println("Enter Years:     7, 15, 30 only:");
choice = (char) System.in.read(); //System.in.read();
switch (choice)
case '1' :     interestRate = 7.25 / 1200;
System.out.println(+interestRate);
break;
case '2' :      interestRate = 8.50 / 1200;
System.out.println(+interestRate);
                         break;
               case '3': interestRate = 9.0 / 1200;
System.out.println(+interestRate);
                         break;
default : System.out.println("oops");
}

ok i couldnt get the switch to work so I tried this and now it wont read in ?? I am about ready to give up. can anybody help??
//Import the class in the java.text.
import java.text.*;
import java.io.IOException;
//Creates a public class named LarryInterest_f.
public class larryInterest_f2
{     //Start of main method using public static class members and void means it does not.
//return a value,inside main parenthesis is created an array of strings holding arguments.
public static void main(String[] args) throws IOException
{ //Start Main
double principal = 200000;//(principal) double (64 bits) string variable created and set to 200000.
double rate [ ] = {.0535, .055, .0575}; //(rate)double .
double amount; // (amount) double(64 bit)string variable created.
double moPay; //(moPay)double(64 bit)string variable created.
double totalInt; //(64 bit)string variable created.
int time; //(time) integer (32 bit) variable created and set 1 for total interest.
int i; // Creates an integer value called i
int [ ] term = {7,15,30}; // sets the term array of 7,15,30.
int ratePlace; //pointer
char answer;
char totalMo;
char test;
char firstIterate;
char secondIterate;
System.out.println("What Choice would you Like\n");
System.out.println("1-Interest rate of 5.35% for 7 years?\n");
System.out.println("2-Interest rate of 5.55% for 15 years?\n");
System.out.println("3-Interest rate of 5.75% for 30 years?\n");
System.out.println("4-Quit\n");
answer = (char)System.in.read();
if (answer = 1) {
ratePlace = 0;
firstIterate = 4;
secondIterate = 21;
totalMo = 84;
else
if (answer = 2) {
ratePlace = 1;
firstIterate = 8;
secondIterate = 24;
totalMo = 180;
else
if (answer = 3) {
ratePlace = 3;
firstIterate = 15;
secondIterate = 24;
totalMo = 360;
else
System.out.println("Booga Wooga Chooga");
amount = (principal + (principal * rate[ratePlace] ));
moPay = (amount / totalMo);
totalInt = (principal * rate[ratePlace]);
dAmount = amount-moPay;
intPay = totalInt / term[ratePlace];
          // Printout
DecimalFormat df = new DecimalFormat("#.###,00");
System.out.println("The Interest on $" + (df.format(principal) + " at" + rate[ratePlace] +"% for a
loan to be paid off in "+term[ratePlace]+"years is " +"$"+ (df.format(totalInt) +"Dollars\n")));          
System.out.println("Thek total amount of loan plus interest is $"+(df.formt(amount)+"Dollars.\n"));
System.out.println("The Payments spread over"+totalMo+"months. would be $"
+(df.format (moPay) + "Dollars a month for"+term[ratePlace]+"years.\n\n"));
System.out.println("Would you like to see a payment schedule? y for Yes, or x to Exit");
test = (char)System.in.read();
if (test=='y')
System.out.println("OK Here I Go");
intPay = (intPay + (totalInt/term[ratePlace]));
pmt = pmt +1;
for (int a=1; a<firstIterate; a++){
System.out.println(" Payment Schedule \n\n");
System.out.println("Month               Interest                    Balance");
for (int b=1;b<secondIterate;b++){
System.out.println(pmt +"\t\t\t\t"+ df.format(intPay) + "\t\t\t"+df.format(dAmount));
if(pmt <totMO){
System.out.println(("This Page Complete Press Enter to Continue"));
System.in.read();

Similar Messages

  • HELP -menu using a switch statement

    Hello to all. I'm new to the Java world, but currently taking my first Java class online. Not sure if this is the right place, but I need some help. In short I need to write a program that gives the user a menu to chose from using a switch statement. The switch statement should include a while statement so the user can make more than one selection on the menu and provide an option to exit the program.
    With in the program I am to give an output of all counting numbers (6 numbers per line).
    Can anyone help me with this?? If I'm not asking the right question please let me know or point me in the direction that can help me out.
    Thanks in advance.
    Here is what I have so far:
    import java.util.*;
    public class DoWhileDemo
         public static void main(String[] args)
              int count, number;
              System.out.println("Enter a number");
              Scanner keyboard = new Scanner (System.in);
              number = keyboard.nextInt();
              count = number;
              do
                   System.out.print(count +",");
                   count++;
              }while (count <= 32);
              System.out.println();
              System.out.println("Buckle my shoe.");
    }

    Thanks for the reply. I will tk a look at the link that was provided. However, I have started working on the problem, but can't get the 6 numbers per line. I am trying to figure out the problem in parts. Right now I'm working on the numbers, then the menu, and so on.
    Should I tk this approach or another?
    Again, thanks for the reply.

  • Switch Statement again

    I am new to Java and am trying to learn how to use and understand the nuances involved in using the Switch statment.
    Yesterday, I received tremendous help, As a result, I am closer to understanding the switch statement and how it works.
    My program is designed to use 5 different input boxes. These represent a total for quizzes, homework assignments, 2 midterms, and a final exam.
    These are casted to double; then, they are added together and divided by five to obtain an average (the student's GPA). The GPA is then going to assigned a grade depending up the range in the If then statement.
    I intend on using a message box to inform the user of the GPA and another followed by another message box to show them their grade.
    I would like to incorporate the switch statement (so I can learn how to use it) to show them their grade.
    I know the code needs tweaking but this is what I have so far:
    import javax.swing.JOptionPane;
    public class Switchgrade{
    //declaration of class
    public static void main(String args[])
    //declaration of main
    String midone; String midtwo; String quiz; String homework; //declares variables to hold the grades, quiz and homework scores
    String last;
    double one; //first midterm
    double two; //second midterm
    double three;double four; double five; //final, quiz and homework scores
    double average; //GPA
    char a; char b; char c; char d; char f;char 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
    if(average >= 90)
    grade = 'a';
    else
    if(average >= 80 )
    grade = 'b';
    switch (grade)
    case a:
    JOptionPane.showMessageDialog(null,"The total of all your scores is " + b+"\nYour final grade is an A");
    break;
    default:
    JOptionPane.showMessageDialog(null,"Sorry, you received a grade of " + b + ". \nYou failed.");
    break;
    System.exit(0);
    }//end of main
    }//end of class
    As you can see, I am only using two grades, just so I can learn to use it. However, when I go to compile this, I get this error message:
    constant expression required: case a:, with the ^ under the a.
    What does this error message me and how do I fix this.
    Thanks in advance for your help.

    case a:is trying to use a variable with the name "a" for the comparison. This is illegal in java
    what you want is
    case 'a':this will do a comparison against the char value 'a'

  • 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??

  • Using a Switch statement for Infix to Prefix Expressions

    I am stuck on the numeric and operator portion of the switch statement...I have the problem also figured out in an if/else if statement and it works fine, but the requirements were for the following algorithm:
    while not end of expression
    switch next token of expression
    case space:
    case left parenthesis:
    skip it
    case numeric:
    push the string onto the stack of operands
    case operator:
    push the operator onto the stack of operators
    case right parenthesis:
    pop two operands from operand stack
    pop one operator from operator stack
    form a string onto operand stack
    push the string onto operand stack
    pop the final result off the operand stack
    I know that typically case/switch statement's can only be done via char and int's. As I said I am stuck and hoping to get some pointers. This is for a homework assignment but I am really hoping for a few pointers. I am using a linked stack class as that was also the requirements. Here is the code that I have:
       import java.io.*;
       import java.util.*;
       import java.lang.*;
    /*--------------------------- PUBLIC CLASS INFIXTOPREFIX --------------------------------------*/
    /*-------------------------- INFIX TO PREFIX EXPRESSIONS --------------------------------------*/
        public class infixToPrefix {
          private static LinkedStack operators = new LinkedStack();
          private static LinkedStack operands = new LinkedStack();
            // Class variable for keyboard input
          private static BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
             // Repeatedly reads in infix expressions and evaluates them
           public static void main(String[] args) throws IOException {
          // variables
             String expression, response = "y";
          // obtain input of infix expression from user
             while (response.charAt(0) == 'y') {
                System.out.println("Enter a parenthesized infix expression.");          // prompt the user
                System.out.println("Example: ( ( 13 + 2 ) * ( 10 + ( 8 / 3 ) ) )");
                System.out.print("Or as: ((13+2)*(10+(8/3))):  ");
                expression = stdin.readLine();     // read input from the user
             // output prefix expression and ask user if they would like to continue          
                System.out.println("The Prefix expression is: " + prefix(expression));     // output expression
                System.out.println("Evaluate another? y or n: ");          // check with user for anymore expressions
                response = stdin.readLine();     // read input from user
                if (response.charAt(0) == 'n') {          // is user chooses n, output the statement
                   System.out.println("Thank you and have a great day!");
                }     // end if statement
             }     // end while statement
          }     // end method main
       /*------------- CONVERSION OF AN INFIX EXPRESSION TO A PREFIX EXPRESSION ------------*/ 
       /*--------------------------- USING A SWITCH STATEMENT ------------------------------*/
           private static String prefix(String expression) {
                // variables
             String symbol, operandA, operandB, operator, stringA, outcome;
               // initialize tokenizer
             StringTokenizer tokenizer = new StringTokenizer(expression, " +-*/() ", true);     
             while (tokenizer.hasMoreTokens()) {
                symbol = tokenizer.nextToken();     // initialize symbol     
                switch (expression) {
                   case ' ':
                      break;     // accounting for spaces
                   case '(':
                      break;     // skipping the left parenthesis
                   case (Character.isDigit(symbol.charAt(0))):      // case numeric
                      operands.push(symbol);                                   // push the string onto the stack of operands
                      break;
                   case (!symbol.equals(" ") && !symbol.equals("(")):     // case operator
                      operators.push(symbol);                                             // push the operator onto the stack of operators
                      break;
                   case ')':
                      operandA = (String)operands.pop();     // pop off first operand
                      operandB = (String)operands.pop();     // pop off second operand
                      operator = (String)operators.pop();     // pop off operator
                      stringA = operator + " " + operandB + " " + operandA;          // form the new string
                      operands.push(stringA);
                      break;
                }     // end switch statement
             }     // end while statement
             outcome = (String)operands.pop();     // pop off the outcome
             return outcome;     // return outcome
          }     // end method prefix
       }     // end class infixToPrefixAny help would be greatly appreciated!

    so, i did what flounder suggested:
             char e = expression.charAt(0);
             while (tokenizer.hasMoreTokens()) {
                symbol = tokenizer.nextToken();     // initialize symbol     
                switch (e) {
                   case ' ':
                      break;     // accounting for spaces
                   case '(':
                      break;     // skipping the left parenthesis
                   case '0':
                   case '1':
                   case '2':
                   case '3':
                   case '4':
                   case '5':
                   case '6':
                   case '7':
                   case '8':
                   case '9':
                      operands.push(symbol);     // push the string onto the stack of operands
                      break;                               // case numeric
                   case '+':
                   case '-':
                   case '*':
                   case '/':
                      operators.push(symbol);     // push the operator onto the stack of operators
                      break;                               // case operator
                   case ')':
                      operandA = (String)operands.pop();     // pop off first operand
                      operandB = (String)operands.pop();     // pop off second operand
                      operator = (String)operators.pop();     // pop off operator
                      stringA = operator + " " + operandB + " " + operandA;          // form the new string
                      operands.push(stringA);
                      break;
                   default:
                }     // end switch statement
             }     // end while statement
             outcome = (String)operands.pop();     // pop off the outcome
             return outcome;     // return outcomeafter this, I am able to compile the code free of errors and I am able to enter the infix expression, however, the moment enter is hit it provides the following errors:
    Exception in thread "main" java.lang.NullPointerException
         at LinkedStack$Node.access$100(LinkedStack.java:11)
         at LinkedStack.pop(LinkedStack.java:44)
         at infixToPrefix.prefix(infixToPrefix.java:119)
         at infixToPrefix.main(infixToPrefix.java:59)
    Any ideas as to why? I am still looking through seeing if I can't figure it out, but any suggestions? Here is the linked stack code:
        public class LinkedStack {
       /*--------------- LINKED LIST NODE ---------------*/
           private class Node {
             private Object data;
             private Node previous;
          }     // end class node
       /*--------------  VARIABLES --------------*/
          private Node top;
      /*-- Push Method: pushes object onto LinkedStack --*/     
           public void push(Object data) {
             Node newTop = new Node();
             newTop.data = data;
             newTop.previous = top;
             top = newTop;
          }     // end function push
       /*--- Pop Method: pop obejct off of LinkedStack ---*/
           public Object pop()      {
             Object data = top.data;
             top = top.previous;
             return data;
          }     // end function pop
       } // end class linked stackEdited by: drmsndrgns on Mar 12, 2008 8:10 AM
    Edited by: drmsndrgns on Mar 12, 2008 8:14 AM
    Edited by: drmsndrgns on Mar 12, 2008 8:26 AM

  • Methods & Switch Statement in java.. HELP!!

    hi all...
    i am having a slight problem as i am constructing a method --> menu() which handles displaying
    menu options on the screen, prompting the user to select A, B, C, D, S or Q... and then returns the user
    input to the main method!!!
    i am having issues with switch statement which processes the return from menu() methd,,,
    could you please help?!!
    here is my code...
    import java.text.*;
    import java.io.*;
    public class StudentDriver
       public static void main(String[] args) throws IOException
          for(;;)
             /* Switch statement for menu manipulation */
             switch(menu())
                   case A: System.out.println("You have selected option A");
                                  break;
                   case B: System.out.println("You have selected option B");
                                  break;
                   case C: System.out.println("You have selected option C");
                                  break;
                   case D: System.out.println("You have selected option D");
                                  break;
                   case S: System.out.println("You have selected option S");
                                  break;
                   case Q: System.out.println("\n\n\n\n\n\n\t\t Thank you for using our system..." +
                                                                    "\n\n\t\t\t Good Bye \n\n\n\n");
                                  exit(0);    
       static char menu()
          char option;
          BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));       
          System.out.println("\n\n");
          System.out.println("\n\t\t_________________________");
          System.out.println("\t\t|                       |");
          System.out.println("\t\t| Student Manager Menu  |");
          System.out.println("\t\t|_______________________|");
          System.out.println("\n\t________________________________________");
          System.out.println("\t| \t\t\t\t\t|");
          System.out.println("\t| Add new student\t\t A \t|");
          System.out.println("\t| Add credits\t\t\t B \t|");
          System.out.println("\t| Display one record\t\t C \t|");
          System.out.println("\t| Show the average credits\t D \t|");
          System.out.println("\t| \t\t\t\t\t|");
          System.out.println("\t| Save the changes\t\t S \t|");
          System.out.println("\t| Quit\t\t\t\t Q \t|");
          System.out.println("\t|_______________________________________|\n");
          System.out.print("\t  Your Choice: ");
          option = stdin.readLine();
             return option;
    }Thanking your help in advance...
    yours...
    khalid

    Hi,
    There are few changes which u need to make for making ur code work.
    1) In main method, in switch case change case A: to case 'A':
    Characters should be represented in single quotes.
    2) in case 'Q' change exit(0) to System.exit(0);
    3) The method static char menu() { should be changed to static char menu() throws IOException   {
    4) Change option = stdin.readLine(); to
    option = (char)stdin.read();
    Then compile and run ur code. This will work.
    Or else just copy the below code
    import java.text.*;
    import java.io.*;
    public class StudentDriver{
         public static void main(String[] args) throws IOException {
              for(;;) {
                   /* Switch statement for menu manipulation */
                   switch(menu()) {
                        case 'A': System.out.println("You have selected option A");
                        break;
                        case 'B': System.out.println("You have selected option B");
                        break;
                        case 'C': System.out.println("You have selected option C");
                        break;
                        case 'D': System.out.println("You have selected option D");
                        break;
                        case 'S': System.out.println("You have selected option S");
                        break;
                        case 'Q':
                        System.out.println("\n\n\n\n\n\n\t\t Thank you for using our system..." +
                        "\n\n\t\t\t Good Bye \n\n\n\n");
                        System.exit(0);
         static char menu() throws IOException {
              char option;
              BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
              System.out.println("\n\n");
              System.out.println("\n\t\t_________________________");
              System.out.println("\t\t| |");
              System.out.println("\t\t| Student Manager Menu |");
              System.out.println("\t\t|_______________________|");
              System.out.println("\n\t________________________________________");
              System.out.println("\t| \t\t\t\t\t|");
              System.out.println("\t| Add new student\t\t A \t|");
              System.out.println("\t| Add credits\t\t\t B \t|");
              System.out.println("\t| Display one record\t\t C \t|");
              System.out.println("\t| Show the average credits\t D \t|");
              System.out.println("\t| \t\t\t\t\t|");
              System.out.println("\t| Save the changes\t\t S \t|");
              System.out.println("\t| Quit\t\t\t\t Q \t|");
              System.out.println("\t|_______________________________________|\n");
              System.out.print("\t Your Choice: ");
              option = (char)stdin.read();
              return option;
    regards
    Karthik

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

  • Problem with switch statement

    Here's my dilemma,
    I'm trying to write a program that takes a user input ZIP Code and then outputs the geographical area associated with that code based on the first number. My knowledge of Java is very, very basic but I was thinking that I could do it with the charAt method. I can get the input fine and isolate the the first character but for some reason the charAt method is returning a number like 55 (that's what I get when it starts with 7). Additionally, to use the charAt my input has to be a String and I can't use a String with the switch statement. To use my input with the Switch statement I have to make the variable an int. When I do that however, I can't use the charAt method to grab the first digit. I'm really frustrated and hope someone can point me in the right direction.
    Here's what I have so far:
    import java.util.Scanner;
    public class ZipCode
         public static void main(String[] args)
              // Get ZIP Code
              int zipCodeInput;
              Scanner stdIn = new Scanner(System.in);
              System.out.print("Please enter a ZIP Code: ");
              zipCodeInput = stdIn.nextInt();
              // Determine area of residence
              switch (zipCodeInput)
                   case 0: case 2: case 3:
                        System.out.println(zipCodeInput + " is on the East Coast");
                        break;
                   case 4: case 5: case 6:
                        System.out.println(zipCodeInput + " is in the Central Plains area");
                        break;
                   case 7:
                        System.out.println(zipCodeInput + " is in the South");
                        break;
                   case 8: case 9:
                        System.out.println(zipCodeInput + " is int he West");
                        break;
                   default:
                        System.out.println(zipCodeInput + " is an invalid ZIP Code");
                        break;
    }

    Fmwood123 wrote:
    Alright, I've successfully isolated the first number in the zip code by changing int zipCodeChar1 into char zipCodeChar1. Now however, when I try to run that through the switch I get the default message of <ZIP> is an invalid ZIP Code. I know that you said above that switch statements were bad so assume this is purely academic at this point. I'd just like to know why it's not working.
    import java.util.Scanner;
    public class ZipCode
         public static void main(String[] args)
              // Get ZIP Code
              String zipCodeInput;
              char zipCodeChar1;
              Scanner stdIn = new Scanner(System.in);
              System.out.print("Please enter a ZIP Code: "); // Input of 31093
              zipCodeInput = stdIn.nextLine();
              System.out.println("zipCodeInput is: " + zipCodeInput); // Retuns 31093
              zipCodeChar1 = zipCodeInput.charAt(0);
              System.out.println("zipCodeChar1 is: " + zipCodeChar1); // Returns 3
              // Determine area of residence
              switch (zipCodeChar1)
                   case 0: case 2: case 3:
                        System.out.println(zipCodeInput + " is on the East Coast");
                        break;
                   case 4: case 5: case 6:
                        System.out.println(zipCodeInput + " is in the Central Plains area");
                        break;
                   case 7:
                        System.out.println(zipCodeInput + " is in the South");
                        break;
                   case 8: case 9:
                        System.out.println(zipCodeInput + " is int he West");
                        break;
                   default:
                        System.out.println(zipCodeInput + " is an invalid ZIP Code");
                        break;
    When you print the char '7' as a character you will see the character '7', but char is really a numeric type: think of it as unsigned short. To convert '0'...'9' to the numbers 0...9, do the math:
    char ch = ...
    int digit = ch - '0';edit: or give your cases in terms of char literals:
    case '0': case '2': case '3':

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

  • Switch statement problem

    I am doing a question in which I have to make a simple ATM program that can withraw and deposit money as many times as the user wants. To exit the program the user has to hit "x". I have to use a switch statement. Im getting incompatible type errors after compiling it. Can anyone help me? Sorry if the formattings not too good.
    //ATM.java
    //This program reads in a user's opening balance and performs a withdrawal or a deposit at the request of the user
    import java.text.*;
         public class ATM
         public static void main(String args[])
              int      balance;
              char      withdrawal, deposit, choice;
              //Ask for the opening balance
              System.out.print("Please enter your opening balance");
              balance=UserInput.getInt();
              //Find out what the user wants done
              System.out.print("What would you like to do? (Withdrawal, Depositor Exit(x))");
              choice=UserInput.getChar();
                                                                          switch(choice){     
    case "w":
                                                                          while(balance>0)
                                                                                              System.out.print("How much would you like to withdraw?");
                                                                                              withdrawal=UserInput.getChar();
                                                                                              balance=balance-withdrawal;
                                                                                              System.out.print("Your remaining balance is " + balance);
                                                                                              break;
    case "d":     
    while(balance>0)
                                                                                              System.out.print("How much do you wish to deposit?");
                                                                                              deposit=UserInput.getChar();
                                                                                              balance=balance+deposit;
                                                                                              System.out.print("Your new balance is " + balance);
                                                                                              break;
    case "x":          
                                                                System.out.print("Goodbye and thank you for using this program");
                                                                                              break;
    default:     
                                                                     System.out.print("We were not able to process your request, please try again");
                                                                                              break;
    }

    Type a reply to the topic using the form below. When finished, you can optionally preview your reply by clicking on the "Preview" button. Otherwise, click the "Post" button to submit your message immediately.
    Subject:
    Click for bold      Click for italics      Click for underline           Click for code tags      
      Formatting tips
    Message:
    Add topic to Watchlist:
    Original Message:
    Switch statement problem
    Xivilai Registered: Mar 3, 2007 9:52 AM      Mar 3, 2007 10:06 AM
    I am doing a question in which I have to make a simple ATM program that can withraw and deposit money as many times as the user wants. To exit the program the user has to hit "x". I have to use a switch statement. Im getting incompatible type errors after compiling it. Can anyone help me? Sorry if the formattings not too good.
    //ATM.java
    //This program reads in a user's opening balance and performs a withdrawal or a deposit at the request of the user
    import java.text.*;
    public class ATM
    public static void main(String args[])
    int balance;
    char withdrawal, deposit, choice;
    //Ask for the opening balance
    System.out.print("Please enter your opening balance");
    balance=UserInput.getInt();
    //Find out what the user wants done
    System.out.print("What would you like to do? (Withdrawal, Depositor Exit(x))");
    choice=UserInput.getChar();
    switch(choice){
    case 'w':
    while(balance>0)
    System.out.print("How much would you like to withdraw?");
    withdrawal=UserInput.getChar();
    balance=balance-withdrawal;
    System.out.print("Your remaining balance is " + balance);
    break;
    case 'd':
    while(balance>0)
    System.out.print("How much do you wish to deposit?");
    deposit=UserInput.getChar();
    balance=balance+deposit;
    System.out.print("Your new balance is " + balance);
    break;
    case 'x':
    System.out.print("Goodbye and thank you for using this program");
    break;
    default:
    System.out.print("We were not able to process your request, please try again");
    break;
    }

  • Help with switch statement

    Hello I have a copy of my code below. Everything compiles fine its just when the code gets to the switch statement I get an error saying
    Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Scanner.java:819)
    at java.util.Scanner.next(Scanner.java:1431)
    at java.util.Scanner.nextInt(Scanner.java:2040)
    at java.util.Scanner.nextInt(Scanner.java:2000)
    at Sample.main(Sample.java:55)
    Something is not working right when the user enters an integer expression. what can I do to fix this?
    import java.util.*;
    import java.io.*;
    // Declare a public class
    public class Sample {
         public static void main (String[] args){
         //Declare Variables
         float float0, float1;
         int int0, int1;
         String mathSign;
         char charMathSign;
         Scanner sc = new Scanner(System.in);
         //Ask user to Enter FLoating-Point Number Expression
         System.out.println("Enter a simple floating-point expression: ");
         float0 = sc.nextFloat();
         mathSign = sc.next ();
         float1 = sc.nextFloat();
         if(mathSign.equals("+"))
         System.out.println(float0 + " + " + float1 + " = " + (float0 + float1));     
         else if(mathSign.equals("-"))
         System.out.println(float0 + " - " + float1 + " = " + (float0 - float1));
         else if(mathSign.equals("*"))
         System.out.println(float0 + " * " + float1 + " = " + (float0 * float1));
         else if(mathSign.equals("/"))
         System.out.println(float0 + " / " + float1 + " = " + (float0 / float1));
         //Ask the user to enter a simple floating point expression
         System.out.println("Enter a simple integer expression: ");
         int0 = sc.nextInt ();
         charMathSign = mathSign.charAt(0);
         int1 = sc.nextInt ();
         switch (charMathSign)
              case '+': System.out.println(int0 + " + " + int1 + " = " + (int0 + int1));
              break;
              case '-': System.out.println(int0 + " - " + int1 + " = " + (int0 - int1));
              break;
              case '*': System.out.println(int0 + " * " + int1 + " = " + (int0 * int1));
              break;
              case '/': System.out.println(int0 + " / " + int1 + " = " + (int0 / int1));
              break;
    [/code]                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    {color:#000080}Duplicate posting, please post all responses at{color}{color:#0000ff}
    http://forum.java.sun.com/thread.jspa?threadID=5219239{color}{color:#000080}
    db{color}

  • 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.

  • HELP A COMPLETE NOOB! Java Switch Statement?

    Hi, I am trying to use a simple switch statement and I just cant seem to get it to work?;
    import java.util.Scanner;
    public class Month {
    public static void main(String[] args) {
    String message;
    Scanner scan = new Scanner(System.in);
    System.out.println("Enter a number:");
    message = scan.nextLine();
    int month = 8;
    if (month == 1) {
    System.out.println("January");
    } else if (month == 2) {
    System.out.println("February");
    switch (month) {
    case 1: System.out.println("January"); break;
    case 2: System.out.println("February"); break;
    case 3: System.out.println("March"); break;
    case 4: System.out.println("April"); break;
    case 5: System.out.println("May"); break;
    case 6: System.out.println("June"); break;
    case 7: System.out.println("July"); break;
    case 8: System.out.println("August"); break;
    case 9: System.out.println("September"); break;
    case 10: System.out.println("October"); break;
    case 11: System.out.println("November"); break;
    case 12: System.out.println("December"); break;
    default: System.out.println("Invalid month.");break;}
    Please can anyone help, all I want is to enter a number and the corresponding month to appear. Thank you.

    This will work.
    import java.util.Scanner;
    public class Month {
    public static void main(String[] args) {
    // read user input
    Scanner scan = new Scanner(System.in);
    System.out.println("Enter a number:");
    int month = scan.nextInt();
    // print the month
    switch (month) {
    case 1: System.out.println("January"); break;
    case 2: System.out.println("February"); break;
    case 3: System.out.println("March"); break;
    case 4: System.out.println("April"); break;
    case 5: System.out.println("May"); break;
    case 6: System.out.println("June"); break;
    case 7: System.out.println("July"); break;
    case 8: System.out.println("August"); break;
    case 9: System.out.println("September"); break;
    case 10: System.out.println("October"); break;
    case 11: System.out.println("November"); break;
    case 12: System.out.println("December"); break;
    default: System.out.println("Invalid month.");break;}
    }

  • Switch statement help!!

    ive not done switch statements before, i have a list of months and i have a number from another method which i need to use in this switch statement to obtain the right month.
    example is that the other method returns me with the number 4.....this should give me the month april =D
    im not sure where to go with this.....
    private static String getMonthName(String[] args)
            switch (month)
                case 1:  monthName = "January"; break;
                case 2:  monthName = "February"; break;
                case 3:  monthName = "March"; break;
                case 4:  monthName = "April"; break;
                case 5:  monthName = "May"; break;
                case 6:  monthName = "June"; break;
                case 7:  monthName = "July"; break;
                case 8:  monthName = "August"; break;
                case 9:  monthName = "September"; break;
                case 10: monthName = "October"; break;
                case 11: monthName = "November"; break;
                case 12: monthName = "December"; break;
                default: System.out.println("Invalid month.");break; 
            }

    Either you can do this
          private static String getMonthName(String[] args)
            month=getMonthIndex();
            switch (month)
                case 1:  monthName = "January"; break;
                case 2:  monthName = "February"; break;
                case 3:  monthName = "March"; break;
                case 4:  monthName = "April"; break;
                case 5:  monthName = "May"; break;
                case 6:  monthName = "June"; break;
                case 7:  monthName = "July"; break;
                case 8:  monthName = "August"; break;
                case 9:  monthName = "September"; break;
                case 10: monthName = "October"; break;
                case 11: monthName = "November"; break;
                case 12: monthName = "December"; break;
                default: System.out.println("Invalid month.");break; 
    or this
          private static String getMonthName(String[] args)
            switch (getMonthIndex())
                case 1:  monthName = "January"; break;
                case 2:  monthName = "February"; break;
                case 3:  monthName = "March"; break;
                case 4:  monthName = "April"; break;
                case 5:  monthName = "May"; break;
                case 6:  monthName = "June"; break;
                case 7:  monthName = "July"; break;
                case 8:  monthName = "August"; break;
                case 9:  monthName = "September"; break;
                case 10: monthName = "October"; break;
                case 11: monthName = "November"; break;
                case 12: monthName = "December"; break;
                default: System.out.println("Invalid month.");break; 
                  Assuming that you have a method which returns an index representing a month which in this case i have assumed as getMonthIndex( )

  • Switch statement help please

    I have been advised on this forum that a switch statement in place of the if else etc would be neater. Could someone tell me where the switch statement goes in the code below.
    Thanks
    Calculator class Calculator.java
    class Calculator {
    public void Calculator() {
    public double workOut(String s1) {
    int count = 0, i_s1_len = 0, i_dot=0, i_neg =0;
    double d_calc=0,d_num = 0, d_snum=0 ;
    String s2 = "", s3 = "", s_num="";
    if (s1.length()==0){ //Check for an input eg contains at least one character
    System.out.println("Sorry you must input a equation ending in an equals '=' sign");
    return 0;
    else {
    i_s1_len = s1.length();
    count = 0; //reset count to zero
    //remove spaces s2 becomes the equation
    for (count=0; count+1 <= i_s1_len;){
    if (s1.charAt(count)==32){
    count++;
    else{
    s2=s2+s1.charAt(count);
    count++;
    i_s1_len = s2.length();//
    // check final character is an "=" sign
    if (s2.endsWith("=")){
    else{
    System .out.println( "Sorry your equation must end with an = sign ");
    return 0;
    // Checking if characters in the equation are legal eg 1-9 or ()-+/*. or the = sign is only at the end.
    count = 0; //reset
    for (count=0; count+1 <= i_s1_len;){
    if ((s2.charAt(count)>39)&(s2.charAt(count)<58)){
    count++;
    else if ((s2.charAt(count)==61) & (count != i_s1_len-1)) {
    System.out.println("Operator'=' is in two places ");
    return 0;
    else{
    count++;
    // Selecting Calculation type +-*/ and calculation Type and conversion
    for (count=0; count+1 <= i_s1_len;){
    //Addition calculation 43 = +
    if (s2.charAt(count)== 43){
    s3="+";
    // Subtraction Calculation 45 = -
    else if (s2.charAt(count)== 45){
    s3="-";
    // check for minus minus
    if (s2.charAt(count+1)== 45){
    s3="+";
    // multiplication Calculation 42 = *
    else if (s2.charAt(count)== 42){
    s3="*";
    // Division Calculation 47 =/
    else if (s2.charAt(count)== 47){
    s3="/";
    //Get String for conversion to number
    else s_num=s_num+s2.charAt(count);{
    count++;
    // Transfer number to single varable
    while ((s2.charAt(count)>47)&(s2.charAt(count)<58)||(s2.charAt(count)==46)){
    s_num=s_num+s2.charAt(count);
    count++;
    //check for multiple decimal points
    if (s2.charAt(count-1)==46){
    i_dot++;
    if (i_dot > 1){
    System.out.println("One of your numbers contains two decimals points ");
    return 0;
    i_dot=0; //reset decimal counter
    // Get opperator + - * /
    if (s3 =="+"){
    d_num = d_num + Double.parseDouble(s_num);
    else if (s3 =="-"){
    d_num = d_num - Double.parseDouble(s_num);
    else if (s3 =="*"){
    d_num = d_num * Double.parseDouble(s_num);
    else if (s3 =="/"){
    if (Double.parseDouble(s_num)==0){
    System.out.println("You are trying to divide by Zero which is infinity");
    return 0;
    d_num = d_num / Double.parseDouble(s_num);
    else{
    d_num = Double.parseDouble(s_num);
    s_num="";
    if (s2.length()==count+1) {
    return d_num;
    return d_num;

    Instead of writing
    if (x == 1)
        // do this
    else if (x == 2)
        // do that
    else
        // do the otheryou can write
    switch (x) {
    case 1:
        // do this
        break;
    case 2:
        // do that
        break;
    default:
        // do the other
        break;
    }

Maybe you are looking for

  • A list of inputs using netui tags

    Hi all, we have a family of netui problems which occur quite frequently. The main problem is: what to do when we have a list of items (we don't now how many), and we want to display them, and get some input from the user. 1. The simplest form, when t

  • How to search the location of the single quote using instr func in a string

    I have a string '345634','234'(all 4 single quotes are part of the string) and I want to find the location of the 3rd single quote using the instr function , could sum1 quickly please help me out. Regards Rahul Edited by: Rahul Kalra on Aug 26, 2010

  • How to set default mail client

    I occasionally respond to a email address and Microsoft outlook express comes up instead of gmail, which I prefer. How can I keep Outlook from butting in?

  • Top photo in iOS 8 folders?

    The top photo changed somewhat arbitrarily when I upgraded to iOS 8 and remains that way on my iPhone 6. IS there any way to manually choose the photo that displays as the folder icon? thanks, tom

  • ACR 4.6 Making Photoshop CS3 Unusable to get my work done...

    In my CS3 Photoshop crash saga, ACR 4.6 has made the problem worse, this makes about the 17th Crash report I sent Adobe: www.gballard.net/PScrashNov5.zip This crashed without building a layered master file. www.gballard.net/PScrashNov2.zip This crash