Java Program.. HELP  (switch statement)

I need help on fixing this program for school.ive looked at information online but i still do not see what i am doing wrong.
The College Rewards Program is based on a student�s achievements on the ACT Test. Students that have excelled on the test are going to be rewarded for the hard work that they put into high school and studying for the exam. The following are the rewards that will be given to students. They are cumulative, and they get all rewards below their score.
1. 35-36 $100 a week spending money
2. 33-34 Free computer
3. 31-32 $10,000 free room and board
4. 25-30 $5000 off the years tuition
5. 21-24 $500 in free books per year
6. 17-20 Free notebook
7. 0-16 Sorry, no rewards, please study and try taking the ACT again.
Make a prompt so the user is asked for their ACT score( be careful).
Change the ACT score into a number
Then have the program use that number to display a message about the Rewards program.
Sample output:
What was your score on the ACT: 44
Entry error, please enter a number from 0 to 36.      (error trap wrong numbers)
What was your score on the ACT: 27
You got a 27 on the ACT, your rewards are:      ( have it number the rewards)
1. $5,000 off the year�s tuition
2. $500 dollars a year in books
3. A free notebook
Congratulations on your hard work and good score.
import java.util.Scanner;
import java.text.*;
public class Act
    public static void main (String [] args)
         Scanner scan = new Scanner( System.in );
          int score,reward;
          score=0;
          boolean goodnum;
          do
                  System.out.println( "What was your ACT score? " );
                          score = scan.nextInt() ;
          if (score >0 || score <36) goodnum = true;      
               else
                System.out.println ("Please enter the correct number");
                          goodnum=false;     
                while (score<0 || score>36) {
                          if (score==35 || score==36) reward=1;
                               else if (score ==34 || score score==33) reward=2;
                                    else if (score==32 || score==31) reward=3;
                                         else if (score>=25 && score<=30) reward=4;
                                              else if (score>=21 && score<=24) reward=5;
                                                 else if (score>=17 && score<=20) reward=6;
                                                          else reward=7;
    c=0
    switch (reward) {
    case 1: $100 a week spending money
              c++
              System.out.println ("$100 a week spending money");     
    case 2:     Free computer
              c++
              System.out.println ("Free computer");     
        case 3:      $10,000 free room and board
              c++
              System.out.println ("$10,000 free room and board");
    case 4:      $5000 off the years tuition
          c++
          System.out.println ("$5000 off the years tuition");
    case 5:      $500 in free books per year
          c++
           System.out.println ("$500 in free books per year");
    case 6:      Free notebook
          c++
          System.out.println ("Free notebook");
    case 7:      Free notebook
          c++
          System.out.println ("Sorry, no rewards, please study and try taking the ACT again.");
          break;
    default:
         System.out.println ("Sorry, no rewards, please study and try taking the ACT again.");
        break;
    }

There are some strange things going on here that could be fixed, so I'll just put my version of how i'd handle this up.
import java.util.Scanner;
import java.text.*; // is this really needed? Scanner's the only class I see
public class Act {
  public static void main( String[] args ) {
    Scanner scan = new Scanner( System.in );
    int score, reward; // don't need to set a value yet
    boolean goodnum;
    do {
      System.out.println( "What was your ACT score? " );
      score = scan.nextInt();
      if ( score >= 0 && score <= 36 ) goodnum = true; // note the && and =s
      else {
        System.out.println( "Please enter a valid number (between 0 and 36)." );
        goodnum = false;
    } while ( !goodnum ); // when this loop finished, the number will be between 0 and 36, a good number
    if ( score >= 35 ) reward = 1;      // save yourself the typing, by now score must be between 0 and 36
    else if ( score >= 33 ) reward = 2; // so just go down with else ifs.
    else if ( score >= 31 ) reward = 3; // this will only reach the lowest point.
    else if ( score >= 25 ) reward = 4;
    else if ( score >= 21 ) reward = 5;
    else if ( score >= 17 ) reward = 6;
    else reward = 7;
    // what was the c for? reward already tells how well they did
    // You handled the switch statement almost perfectly
    // don't break so that reward progressively adds to the output
    if ( reward >= 6 ) { // this if statement is optional, just for good esteem. You could even take it out of the if{}
      System.out.println( "For your score of "+String.valueOf( score )+" you will be rewarded the following:" );
    switch ( reward ) {
      case 1: // $100/week spending money
        System.out.println( "$100 a week spending money." );
      case 2: // Free computer
        System.out.println( "Free computer." );
      case 3: // $10,000 room and board
        System.out.println( "$10,000 free room and board." );
      case 4: // $5000 off tuition
        System.out.println( "$5000 off the year's tuition." );
      case 5: // $500 in free books per year
        System.out.println( "$500 in free books per year." );
      case 6: // Free notebook
        System.out.println( "Free notebook." );
        break; // break here to keep away from discouraging the fine score
      case 7: // since 7 and default are the same result, ignore this and it'll pass to default
      default: // but technically, since reward must be from 1 to 7, default would never explicitly be called
        System.out.println( "Sorry, no rewards. Please study and try taking the ACT again." );
        break; // likely this break is unneccessary
}That works in my head, hope it works on your computer.

Similar Messages

  • Basic Java Program help needed urgently.

    I have posted the instructions to my project assignment on here that is due tomorrow. I have spent an extremely large amount of time trying to get the basics of programming and am having some difficulty off of the bat. Someone who has more experience with this and could walk me through the steps is what I am hoping for. Any Help however will be greatly appreciated. I am putting in a lot of effort, but I am not getting the results I need. Thank you for the consideration of assisting me with my issues. If you have any questions please feel free to ask. I would love to open up a dialogue.
    CIS 120
    Mathematical Operators
    Project-1
    Max possible pts 100
    Write a program “MathOperators” that reads two integers, displays user’s name, sum, product,
    difference, quotients and modulus of the two numbers.
    1. Create a header for your project as follows:
    * Prgrammer: Your Name (1 pt) *
    * Class: CIS 120 (1 pt) *
    * Section: (1 pt) *
    * Instructor: (1 pt) *
    * Program Name: Mathematical Operators (1 pt) *
    * Description: This java program will ask the user to enter two integers and *
    display sum, product, difference, quotients and modulus of the two numbers
    * (5 pts) *
    2. Display a friendly message e.g. Good Morning!! (2 pts)
    3. Explain your program to the user e.g. This java program can add, subtract, multiply,
    divide and calculate remainder of any two integer numbers entered by you. Let’s get
    started…. (5 pts)
    4. Prompt the user- Please enter your first name, store the value entered by user in a
    string variable name. Use input.next() instead of input.nextLine(). (8 pts)
    5. Prompt the user- name, enter first integer number , store the value entered by user in
    an integer variable num1.(5 pts)
    6. Prompt the user- name, enter second integer number , store the value entered by user in
    an integer variable num2.(5 pts)
    7. Display the numbers entered by the user as: name has entered the numbers num1and
    num2.(5 pts)
    8. Calculate sum, product, difference, quotients and modulus of the two numbers. ( 30 pts)
    9. Display sum, product, difference, quotients and modulus of the two numbers. ( 10 pts)
    10. Terminate your program with a friendly message like- Thanks for using my program,
    have a nice day!!(2 pts)

    Nice try. You have not demonstrated that you've at least TRIED to do something. No one is going to do your homework for you. Your "urgency" is yours alone.

  • Java Programming Help

    I'm new to Java programming, and I have a pretty basic question. I'm writing a simple loan calculator, and I need to know how to format the output of my variables to two decimal places. I've been doing this for about a week, so be nice, please.
    Thanks in advance,
    Wayne

    NumberFormat nf = NumberFormat.getCurrencyInstance();
    double cash = 123.45;
    System.out.println(nf.format(cash));
    Your First Cup of Java
    Essentials, Part 1, Lesson 1: Compiling & Running a Simple Program
    The Java Tutorial - A practical guide for programmers
    New to Java Center
    How To Think Like A Computer Scientist
    Introduction to Computer Science using Java
    The Java Developers Almanac 1.4
    JavaRanch: a friendly place for Java greenhorns
    jGuru
    Object-Oriented Programming Concepts
    Object-oriented language basics
    Don't Fear the OOP
    Books:
    Bert Bates and Kathy Sierra's Head First Java
    Bruce Eckel's Thinking in Java (Free online)
    Joshua Bloch's Effective Java
    Java Design: Building Better Apps and Applets (2nd Edition)

  • ONe more time - Java program Help -

    HI. I need to know what the code would be to print the Nodes. I simply can't figure it out.I'm not allowed to change anything or add anything. I just have to fill in the methods and make the ListSort work as it is. I can't figure out how to print each node so the out put looks like this:
    *12 2 10 5*
    *12 2 10 5*
    Eventually I have to have to program sort them but I can probably figure it out if I can just print them. ANy help? I have posted before but with no luck. GOod advice its just i can't find out the code to write in the printLIst and insertNodeAtBeginning that will get the nodes to print.
    * implements various methods related to manipulating a singly-linked list
    public class LinkedList
    private Node firstNode = null;
    * prints all the elements of the list in order on one line, separated by s
    paces
    * puts a line of dashes above and below the printed list
    public void printList()
    System.out.println("----------");
    Node currentNode = firstNode;
    System.out.println("----------");
    * inserts a new node into the list at the beginning of the list
    public void insertNodeAtBeginning(Node newNode)
    // quick error checking
    if (newNode == null)
    return;
    // TODO: insert newNode into the beginning of the list
    * inserts the newNode into the list just before the first node that
    * has a larger value than newNode; if the list is empty or if newNode
    * has the smallest value, then newNode will be inserted at the beginning
    * of the list; if newNode has the largest value in the list, then it
    * should be inserted at the end of the list
    public void insertNodeInAscendingOrder(Node newNode)
    // quick error checking
    if (newNode == null)
    return;
    // TODO: insert newNode in the right place in the list
    * remove the first node in the list and return it. if there are no
    * elements in the list, then return null
    public Node removeFirstNode()
    return firstNode;// TODO: remove the first element in the list and return
    it, or
    // return null if the list is empty
    * use recursion to sort the given list in ascending order
    public static void recursiveListSort(LinkedList list)
    // quick error checking
    if (list == null)
    return;
    // TODO: use recursion to sort the list
    Next file:
    public class ListSort {
    * @param args
    public static void main(String[] args) {
    LinkedList list = new LinkedList();
    list.insertNodeAtBeginning(new Node(5));
    list.insertNodeAtBeginning(new Node(10));
    list.insertNodeAtBeginning(new Node(2));
    list.insertNodeAtBeginning(new Node(12));
    list.printList();
    LinkedList.recursiveListSort(list);
    list.printList();
    Next File:
    public class Node
    private int value;
    public Node next = null;
    public Node(int newValue)
    value = newValue;
    public int getValue()
    return value;
    }

    You did receive good advice previously and would do well to study it and search the forum as well. One other thing to help you get advice is to post your code so it is readable without hurting the eyes. So please use code tags so that your code will be well-formatted and readable. To do this, place the tag &#91;code&#93; at the top of your block of code and the tag &#91;/code&#93; at the bottom, like so:
    &#91;code&#93;
    // your code block goes here.
    &#91;/code&#93;

  • Handling result form Stored Proc in java program

    Folks, I have a question on how to handle results from Stored Procedures with the java.sql API. I execute a stored proc from a java program using the statement:
    statement.execute();
    where 'statement' is of type Statement. Then I get the results:
    ResultSet rs = query.getResultSet();
    The above returns me a ResultSet object. Now, my stored proc is such that it will return an integer in case of errors (as error code), and, if no error,it'll return the result set. Because I wouldn't know if the stored proc is returning an integer or a result set, how do I get the result of the stored proc in the java program? 'query.getResultSet()' would get me only an object of type ResultSet. What if the stored proc is returning an integer (i.e. when an error occurs)?
    Thanks.

    GSP wrote:
    Thanks to all for your replies. I do not have access to modify the stored procedure. I can just use it in my java program. The stored proc first validates its input parameters. If it finds them invalid, then it returns an appropriate error code (which is an integer) depending on which input param is found invalid. If all the input parameters are found valid, then it fetches the rows from the DB tables & returns them as result set. Now my question is: say if I give a statement as this in my java program:
    ResultSet rs = query.getResultSet();
    what if the stored proc returns an error code (Since the above statement gets only ResultSet object, how will it handle if the stored proc returns an int)? Is there any alternative?
    Ok, so there is a piece of missing data.
    Store procs, conceptuatlly can return data in a variety of ways.
    So the first step is to determine how the data is being returned.
    Unless you know that there is no way to determine how to use it in java.

  • 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

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

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

  • Help with Switch statements using Enums?

    Hello, i need help with writing switch statements involving enums. Researched a lot but still cant find desired answer so going to ask here. Ok i'll cut story short.
    Im writing a calculator program. The main problem is writing code for controlling the engine of calculator which sequences of sum actions.
    I have enum class on itself. Atm i think thats ok. I have another class - the engine which does the work.
    I planned to have a switch statement which takes in parameter of a string n. This string n is received from the user interface when users press a button say; "1 + 2 = " which each time n should be "1", "+", "2" and "=" respectively.
    My algorithm would be as follows checking if its a operator(+) a case carry out adding etc.. each case producing its own task. ( I know i can do it with many simple if..else but that is bad programming technique hence im not going down that route) So here the problem arises - i cant get the switch to successfully complete its task... How about look at my code to understand it better.
    I have posted below all the relevant code i got so far, not including the swing codes because they are not needed here...
    ValidOperators v;
    public Calculator_Engine(ValidOperators v){
              stack = new Stack(20);
              //The creation of the stack...
              this.v = v;          
    public void main_Engine(String n){
           ValidOperators v = ValidOperators.numbers;
                    *vo = vo.valueOf(n);*
         switch(v){
         case Add: add();  break;
         case Sub: sub(); break;
         case Mul: Mul(); break;
         case Div: Div(); break;
         case Eq:sum = stack.sPop(); System.out.println("Sum= " + sum);
         default: double number = Integer.parseInt(n);
                       numberPressed(number);
                       break;
                      //default meaning its number so pass it to a method to do a job
    public enum ValidOperators {
         Add("+"), Sub("-"), Mul("X"), Div("/"),
         Eq("="), Numbers("?"); }
         Notes*
    It gives out error: "No enum const class ValidOperators.+" when i press button +.
    It has nothing to do with listeners as it highlighted the error is coming from the line:switch(v){
    I think i know where the problem is.. the line "vo = vo.valueOf(n);"
    This line gets the string and store the enum as that value instead of Add, Sub etc... So how would i solve the problem?
    But.. I dont know how to fix it. ANy help would be good
    Need more info please ask!
    Thanks in advance.

    demo:
    import java.util.*;
    public class EnumExample {
        enum E {
            STAR("*"), HASH("#");
            private String symbol;
            private static Map<String, E> map = new HashMap<String, E>();
            static {
                put(STAR);
                put(HASH);
            public String getSymbol() {
                return symbol;
            private E(String symbol) {
                this.symbol = symbol;
            private static void put(E e) {
                map.put(e.getSymbol(), e);
            public static E parse(String symbol) {
                return map.get(symbol);
        public static void main(String[] args) {
            System.out.println(E.valueOf("STAR")); //succeeds
            System.out.println(E.parse("*")); //succeeds
            System.out.println(E.parse("STAR")); //fails: null
            System.out.println(E.valueOf("*")); //fails: IllegalArgumentException
    }

  • New Java Programming Student Needs Help

    Hey everyone,
    I've just started taking a Java programming class at Penn State University, and I have had some prior experience with programming, i.e. C, C++, HTML, SQL. However, this will be my first attempt at Java. I know there are a lot of similarities between C++ and Java, but I'm still a little lost on some methodology.
    To get myself going, I've been looking through the textbook a little and came across a problem that gave me some difficulty. I'll write out the outline:
    A company pays its employees as managers (who receive a fixed weekly salary), hourly workers (who receive a fixed hourly wage for up to the first 40 hours they work and time and a half (i.e. 1.5 times their hourly wage) for overtime hours worked, commission workers (who receive $250 plus 5.7% of their gross weekly sales), and pieceworkers (who receive a fixed amount of money per item for each of the items they produce � each pieceworker in this company works on only one type of item).
    +Define a Java class named EmployeePayment that includes functionality to compute the weekly pay for each employee. You do not know the number of employees in advance. Each type of employee has its own pay code: Managers have paycode 1, hourly workers have paycode 2, commission workers have paycode 3 and pieceworkers have paycode 4.+
    +Define a main method that creates an instance of the EmployeePayment class, and calls the setManagerPay method to set the managers weekly salary to $625.00. The main method should then prompt the user for the paycode ��Enter paycode (-1 to end): �, validate the input and perform the associated processing for that paycode. Your program should allow the user to process employees until a paycode of -1 has been entered. Use a switch structure to compute each employee�s pay, based on the employee�s paycode. Within the switch, prompt the user (i.e. the payroll clerk) to enter the appropriate facts your program needs to calculate each employee�s pay based on that employee�s paycode, invoke the respective method (defined below) to perform the calculations and return the weekly pay for each type of employee, and print the returned weekly pay for each employee.+
    +Define a setManagerPay method that accepts and stores the fixed weekly salary value for managers.+
    +A private instance variable weeklyManagerPay should be defined in the EmployeePayment class to support these accessor and mutator methods.+
    +Define a calcManagerPay method that has no parameters and returns the fixed weekly salary.+
    +Define a calcHourlyWorkerPay method that accepts the hourly salary and total hours worked as input parameters and returns the weekly pay based on the hourly worker pay code description.+
    +Define a calcCommWorkerPay method that accepts the gross weekly sales as an input parameter and returns the weekly pay based on the commission worker pay code description.+
    +Define a calcPieceWorkerPay method that accepts the number of pieces and wage per piece as input parameters and returns the weekly pay based on the piece worker pay code description.+
    +Once all workers have been processed, the total number of each type of employee processed should be printed. Define and manage the following private instance variables (*numManager*, numHourlyWorker, numCommWorker, and numPieceWorker) within the EmployeePayment class. What are the ways in which these variables can be updated?+
    Sorry for the length, but I wanted this to be thorough. Basically, I'm having the most trouble writing the switch statement, and outputting the total number of each type of employee...
    Any help and pointers will be greatly appreciated...thanks all.

    You said you've written C and C++ code before. I don't have an excellent memory but from the little code that I wrote in C, I believe the switch statement is exactly the same.
    Read this: [http://java.sun.com/docs/books/tutorial/java/nutsandbolts/switch.html]
    If you're having trouble understanding something post what your specific problem is. No one is going to write your homework for you, but many, myself included, would be more than willing to help if you're really stumped. Just post your concise problem.
    Edited by: sheky on Mar 12, 2008 9:52 PM

  • Challange for you, help for me! java program

    I am a beginning java student and desparately (again) in help of someone who will check my java program. See below what they want from me, and try to make a program of it that works in all the ways that are asked. Thank you for helping me, i am running out of time.
    Prem Pradeep
    [email protected]
    Catalogue Manager II
    Specification:
    1.     Develop an object to represent to encapsulate an item in a catalogue. Each CatalogueItem has three pieces of information: an alphanumeric catalogue code, a name, and a price (in dollars and cents), that excludes sales tax. The object should also be able to report the price, inclusive of a 15% sales tax, and the taxed component of the price.
    2.     Data input will come from a text file, whose name is passed in as the first command-line argument to the program. This data file may include up to 30 data items (the program will need to be able to support a variable number of actual items in the array without any errors).
    3.     The data lines will be in the format: CatNo:Description:Price Use a StringTokenizer object to separate these data lines into their components.
    4.     A menu should appear, prompting the user for an action:
    a.     Display all goods: this will display a summary (in tabulated form) of all goods currently stored in the catalogue: per item the category, description, price excluding tax, payable tax and price including tax.
    b.     Dispfay cheapest/dearest goods: this will display a summary of all the cheapest and most expensive item(s) in the catalogue. In the case of more than one item being the cheapest (or most expensive), they should all be listed.
    c.     Sort the list: this will use a selection sort algorithm to sort the list in ascending order, using the catalogue number as the key.
    d.     Search the list: this will prompt the user for a catalogue number, and use a binary search to find the data. If the data has not yet been sorted, this menu option should not operate, and instead display a message to the user to sort the data before attempting a search
    5.     Work out a way to be able to support the inc tax/ex tax price accessors, and the tax component accessor, without needing to store any additional information in the object.
    6.     Use modifiers where appropriate to:
    a.     Ensure that data is properly protected;
    b.     Ensure that the accessors and mutators are most visible;
    c.     The accessors and mutators for the catalogue number and description cannot be overridden.
    d.     The constant for the tax rate is publicly accessible, and does not need an instance of the class present in order to be accessible.
    7.     The program should handle all exceptions wherever they may occur (i.e. file 1/0 problems, number formatting issues, etc.) A correct and comprehensive exception handling strategy (leading to a completely robust program) will be necessary and not an incomplete strategy (i.e. handling incorrect data formats, but not critical errors),
    Sample Execution
    C:\> java AssignmentSix mydata.txt
    Loading file data from mydata.txt ...17 item(s) OK
    CATALOGUE MANAGER: MAIN MENU
    ============================
    a) display all goods b) display cheapest/dearest goods
    c) sort the goods list d) search the goods list
    e) quit
    Option: d
    The goods cannot be searched, as the list is not yet sorted.
    CATALOGUE MANAGER: MAIN MENU
    ============================
    a) display all goods b) display cheapest/dearest goods
    c) sort the goods list d) search the goods list
    e) quit
    Option: b
    CHEAPEST GOODS IN CATALOGUE
    Cat      Description      ExTax      Tax      IncTax
    BA023      Headphones      23.00      3.45      26.45
    JW289      Tape Recorder     23.00      3.45      26.45
    MOST EXPENSIVE GOODS IN CATALOGUE
    Cat      Description      ExTax      Tax      IncTax
    ZZ338      Wristwatch      295.00 44.25      339.25
    CATALOGUE MANAGER: MAIN MENU
    ============================
    a) display all goods b) display cheapest/dearest goods
    c) sort the goods list d) search the goods list
    e) quit
    Option: c
    The data is now sorted.
    CATALOGUE MANAGER: MAIN MENU
    ============================
    a) display all goods b) display cheapest/dearest goods
    c) sort the goods list d) search the goods list
    e) quit
    Option: d
    Enter the catalogue number to find: ZJ282
    Cat Description ExTax Tax IncTax
    ZJ282 Pine Table 98.00 14.70 112.70
    CATALOGUE MANAGER: MAIN MENU
    ============================
    a) display all goods b) display cheapest/dearest goods
    c) sort the goods list d) search the goods list
    e) quit
    Option: e
    Here you have the program as far as I could get. Please try to help me make it compact and implement a sorting method.
    Prem.
    By the way: you can get 8 Duke dollars (I have this topic also in the beginnersforum)
    //CatalogueManager.java
    import java.io.*;
    import java.text.DecimalFormat;
    import java.util.StringTokenizer;
    public class CatalogueManager {
    // private static final double TAXABLE_PERCENTAGE = 0.15;
    // Require it to be publicly accessible
    // static means it is class variable, not an object instance variable.
    public static final double TAXABLE_PERCENTAGE = 0.15;
    private String catalogNumber;
    private String description;
    private double price;
    /** Creates a new instance of CatalogueManager */
    public CatalogueManager() {
    catalogNumber = null;
    description = null;
    price = 0;
    public CatalogueManager(String pCatalogNumber, String pDescription, double pPrice) {
    catalogNumber = pCatalogNumber;
    description = pDescription;
    price = pPrice;
    // the mutators must be most visible
    // the final keyword prevents overridden
    public final void setCatalogNumnber(String pCatalogNumber) {
    catalogNumber = pCatalogNumber;
    // the mutators must be most visible
    // the final keyword prevents overridden
    public final String getCatalogNumber() {
    String str = catalogNumber;
    return str;
    // the mutators must be most visible
    // the final keyword prevents overridden
    public final void setDescription(String pDescription) {
    description = pDescription;
    // the accessors must be most visible
    // the final keyword prevents overridden
    public final String getDescription() {
    String str = description;
    return str;
    // If the parameter is not a double type, set the price = 0;
    // the mutators must be most visible
    public boolean setPrice(String pPrice) {
    try {
    price = Double.parseDouble(pPrice);
    return true;
    catch (NumberFormatException nfe) {
    price = 0;
    return false;
    // the accessors must be most visible
    public double getPrice() {
    double rprice = price;
    return formatDouble(rprice);
    double getTaxAmount(){
    double rTaxAmount = price * TAXABLE_PERCENTAGE;
    return formatDouble(rTaxAmount);
    double getIncTaxAmount() {
    double rTaxAmount = price * (1 + TAXABLE_PERCENTAGE);
    return formatDouble(rTaxAmount);
    double formatDouble(double value) {
    DecimalFormat myFormatter = new DecimalFormat("###.##");
    String str1 = myFormatter.format(value);
    return Double.parseDouble(str1);
    public static void main(String[] args) throws IOException {
    final int MAX_INPUT_ALLOW = 30;
    int MAX_CURRENT_INPUT = 0;
    FileReader fr;
    BufferedReader br;
    CatalogueManager[] catalogList = new CatalogueManager[MAX_INPUT_ALLOW];
    String str;
    char chr;
    boolean bolSort = false;
    double cheapest = 0;
    double mostExpensive = 0;
    String header = "Cat\tDescription\tExTax\tTax\tInc Tax";
    String lines = "---\t-----------\t------\t---\t-------";
    if (args.length != 1) {
    System.out.println("The application expects one parameter only.");
    System.exit(0);
    try {
    fr = new FileReader(args[0]);
    br = new BufferedReader(fr);
    int i = 0;
    while ((str = br.readLine()) != null) {
    catalogList[i] = new CatalogueManager();
    StringTokenizer tokenizer = new StringTokenizer(str, ":" );
    catalogList.setCatalogNumnber(tokenizer.nextToken().trim());
    catalogList[i].setDescription(tokenizer.nextToken().trim());
    if (! catalogList[i].setPrice(tokenizer.nextToken())){
    System.out.println("The price column cannot be formatted as dobule type");
    System.out.println("Application will convert the price to 0.00 and continue with the rest of the line");
    System.out.println("Please check line " + i);
    if (catalogList[i].getPrice() < cheapest) {
    cheapest = catalogList[i].getPrice();
    if (catalogList[i].getPrice() > mostExpensive) {
    mostExpensive = catalogList[i].getPrice();
    i++;
    fr.close();
    MAX_CURRENT_INPUT = i;
    catch (FileNotFoundException fnfe) {
    System.out.println("Input file cannot be located, please make sure the file exists!");
    System.exit(0);
    catch (IOException ioe) {
    System.out.println(ioe.getMessage());
    System.out.println("Application cannot read the data from the file!");
    System.exit(0);
    boolean bolLoop = true;
    BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
    do {
    System.out.println("");
    System.out.println("CATALOGUE MANAGER: MAIN MENU");
    System.out.println("============================");
    System.out.println("a) display all goods b) display cheapest/dearest goods");
    System.out.println("c) sort the goods list d) search the good list");
    System.out.println("e) quit");
    System.out.print("Option:");
    try {
    str = stdin.readLine();
    if (str.length() == 1){
    str.toLowerCase();
    chr = str.charAt(0);
    switch (chr){
    case 'a':
    System.out.println(header);
    System.out.println(lines);
    for (int i = 0; i < MAX_CURRENT_INPUT; i++){
    System.out.println(catalogList[i].getCatalogNumber() + "\t" +
    catalogList[i].getDescription() + "\t" +
    catalogList[i].getPrice() + "\t" +
    catalogList[i].getTaxAmount() + "\t" +
    catalogList[i].getIncTaxAmount());
    System.out.println("");
    break;
    case 'b':
    System.out.println("");
    System.out.println("CHEAPEST GOODS IN CATALOGUE");
    System.out.println(header);
    System.out.println(lines);
    for (int i = 0; i < MAX_CURRENT_INPUT; i++){
    if (catalogList[i].getPrice() == cheapest){
    System.out.println(catalogList[i].getCatalogNumber() + "\t" +
    catalogList[i].getDescription() + "\t" +
    catalogList[i].getPrice() + "\t" +
    catalogList[i].getTaxAmount() + "\t" +
    catalogList[i].getIncTaxAmount());
    System.out.println("");
    System.out.println("MOST EXPENSIVE GODS IN CATALOGUE");
    System.out.println(header);
    System.out.println(lines);
    for (int i = 0; i < MAX_CURRENT_INPUT; i++){
    if (catalogList[i].getPrice() == mostExpensive) {
    System.out.println(catalogList[i].getCatalogNumber() + "\t" +
    catalogList[i].getDescription() + "\t" +
    catalogList[i].getPrice() + "\t" +
    catalogList[i].getTaxAmount() + "\t" +
    catalogList[i].getIncTaxAmount());
    System.out.println("");
    break;
    case 'c':
    if (bolSort == true){
    System.out.println("The data has already been sorted");
    else {
    System.out.println("The data is not sorted");
    break;
    case 'd':
    break;
    case 'e':
    bolLoop = false;
    break;
    default:
    System.out.println("Invalid choice, please re-enter");
    break;
    catch (IOException ioe) {
    System.out.println("ERROR:" + ioe.getMessage());
    System.out.println("Application exits now");
    System.exit(0);
    } while (bolLoop);

    One thing you're missing totally is CatalogueItem!! A CatalogueManager manages the CatalogueItem's, and is not an CatalogueItem itself. So at least you have to have this one more class CatalogueItem.
    public class CatalogueItem {
    private String catalogNumber;
    private String description;
    private double price;
    //with all proper getters, setters.
    Then CatalogueManager has a member variable:
    CatalogueItem[] items;
    Get this straight and other things are pretty obvious...

  • Switch statement to java string

    Hello!
    I am programing a form in jsp that will send an e-mail to different people , depending on the selection of a SELECT box.
    I am using a Bean which will take the option chosen in the select and then prepare the message.
    My problem is that the option list has a lot of values and I would like to use the switch statement , but I always receive a compilation error since the switch statement only allows int and I am using a String....
    Should I use a nested if in that case...or there is another solution?
    ================
    Form.html
    Region <SELECT NAME="region">
    <OPTION VALUE="SouthEastEurope">South East Europe</OPTION>
    <OPTION VALUE="Italy">Italy</OPTION>
    <OPTION VALUE="SouthernAfrica">Southern Africa</OPTION>
    <OPTION VALUE="France">France</OPTION>
    <OPTION VALUE="NorthernAfrica">Northern Africa</OPTION>
    <OPTION VALUE="MiddleEast">Middle East</OPTION>
    <OPTION VALUE="Iberia">Iberia</OPTION>
    </SELECT><P>....
    ==============================
    SendMail.java
    switch(region)
                        case SouthEastEurope:
                             toAddress = "[email protected]";
                             break;
                        case Italy:
                             toAddress = "[email protected]";
                             break;
    ........and so on.....
                   }

    How about generating a Map to match the country to an address.
    Map mymap = new HashMap();
    mymap.put("SouthEastEurope", "[email protected]");
    mymap.put("Italy", "[email protected]");
    String toadress = (String) mymap.get(region);Saves you from a horrible switch statement.

  • Help With Switch Statements

    Alrighty, so I have to do this assignment for my Java course, using a switch statement. The assignment is to have the user enter a number (1-5), and have the corresponding line of a poem be displayed. So if the user entered 1, "One two, buckle your shoe" would be displayed. This is what I have and it's giving me a huge problem:
    import java.util.Scanner;
    public class Poem
         public static void main(String[] args);
              Scanner kboard = new Scanner(System.in);
              System.out.println("Enter a number 1-5 (or 0 to quit).");
              int n = kboard.nextLine();
              switch (n);
                   case 1: System.out.println("One two, buckle your shoe.");
                   break;
                   case 2: System.out.println("Three four, shut the door.");
                   break;
                   case 3: System.out.println("Five six, pick up sticks.");
                   break;
                   case 4: System.out.println("Seven eight, lay them straight.");
                   break;
                   case 5: System.out.println("Nine ten, a big fat hen.");
                   break;
                   default: System.out.println("Goodbye.");
                   break;
    }This is giving me a HUGE string of errors. (Something like 45). I'm wracking my brain here trying to figure this out. Any help is greatly appreciated. Thanks!

    Well that solved a lot of the errors. Now all I get is this:
    --------------------Configuration: <Default>--------------------
    C:\JavaPrograms\Poem.java:8: <identifier> expected
    System.out.println("Enter a number 1-5 (or 0 to quit).");
    ^
    C:\JavaPrograms\Poem.java:8: illegal start of type
    System.out.println("Enter a number 1-5 (or 0 to quit).");
    ^
    C:\JavaPrograms\Poem.java:12: illegal start of type
    switch (n) {
    ^
    C:\JavaPrograms\Poem.java:12: <identifier> expected
    switch (n) {
    ^
    C:\JavaPrograms\Poem.java:14: orphaned case
    case 1: System.out.println("One two, buckle your shoe.");
    ^
    C:\JavaPrograms\Poem.java:30: class, interface, or enum expected
    }

  • Having problem with switch statement..please help

    here my question :
    GUI-based Pay Calculator
    A company pays its employees as executives (who receive a fixed weekly salary) and hourly workers (who receive a fixed hourly salary for the first 40 hours they work in a week, and 1.5 times their hourly wage for overtime worked).
    Each category of employee has its own paycode :
    ?     Paycode 1 for executives
    ?     Paycode 2 for hourly workers
    Write a GUI-based application to compute the weekly pay for each employee. Use switch to compute each employee?s pay based on that employee?s paycode.
    Use CardLayout layout manager to display appropriate GUI components. Obtain the employee name, employee paycode and other necessary facts from the user to calculate the employee?s pay based on the employee paycode:
    ?     For paycode 1, obtain the weekly salary.
    ?     For paycode 2, obtain the hourly salary and the number of hours worked.
    You may obtain other information which you think is necessary from the user.
    Use suitable classes for the GUI elements. (You can use javax.swing package or java.awt package for the GUI elements.)
    here my code so far :
    import java.awt.;*
    import java.awt.event.;*
    import javax.swing.;*
    *public class PayrollSystem implements ItemListener {*
    JPanel cards, JTextField, textField1, JLabel, label1;
    final static String EXECUTIVEPANEL = "1.EXECUTIVE";
    final static String HOURLYPANEL = "2.HOURLY WORKER";
    public void addComponentToPane(Container pane)
    *//Put the JComboBox in a JPanel to get a nicer look.*
    JPanel comboBoxPane = new JPanel(); //use FlowLayout
    JPanel userNameAndPasswordPane = new JPanel();
    *// User Name JLabel and JTextField*
    userNameAndPasswordPane.add(new JLabel("NAME"));
    JTextField textField1 = new JTextField(25);
    userNameAndPasswordPane.add(textField1);
    *String comboBoxItems[] = { EXECUTIVEPANEL, HOURLYPANEL };*
    JComboBox cb = new JComboBox(comboBoxItems);
    cb.setEditable(false);
    cb.addItemListener(this);
    comboBoxPane.add(cb);
    *//Create the "cards".*
    JPanel card1 = new JPanel();
    card1.add(new JLabel("WEEKLY SALARY"));
    card1.add(new JTextField(6));
    card1.add(new JLabel("TOTAL PAY"));
    card1.add(new JTextField(8));
    card1.add(new JButton("CALCULATE"));
    JPanel card2 = new JPanel();
    card2.add(new JLabel("HOURLY SALARY"));
    card2.add(new JTextField(6));
    card2.add(new JLabel("TOTAL HOURS WORK"));
    card2.add(new JTextField(8));
    card2.add(new JButton("CALCULATE"));
    *//Create the panel that contains the "cards".*
    cards= new JPanel(new CardLayout());
    cards.add(card1, EXECUTIVEPANEL);
    cards.add(card2, HOURLYPANEL);
    pane.add(comboBoxPane, BorderLayout.PAGE_START);
    pane.add(userNameAndPasswordPane, BorderLayout.CENTER);
    pane.add(cards, BorderLayout.PAGE_END);
    public void itemStateChanged(ItemEvent evt)
    CardLayout cl = (CardLayout)(cards.getLayout());
    cl.show(cards, (String)evt.getItem());
    ** GUI created*
    *private static void createAndShowGUI() {*
    *//Make sure we have nice window decorations.*
    JFrame.setDefaultLookAndFeelDecorated(true);
    *//Create and set up the window.*
    JFrame frame = new JFrame("GUI PAY CALCULATOR");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    *//Create and set up the content pane.*
    PayrollSystem demo = new PayrollSystem();
    demo.addComponentToPane(frame.getContentPane());
    *//Display the window.*
    frame.pack();
    frame.setVisible(true);
    *public static void main(String[] args) {*
    *//Schedule a job for the event-dispatching thread:*
    *//creating and showing this application's GUI.*
    *javax.swing.SwingUtilities.invokeLater(new Runnable() {*
    *public void run() {*
    createAndShowGUI();
    HOW CAN I PERFORM THE SWITCH STATEMENT INSIDE THIS CODE TO LET IT FULLY FUNCTIONAL..?
    I MUST PERFORM THE SWITCH STATEMENT LIKE IN THE QUESTION..
    PLEASE HELP ME..REALLY APPRECIATED...TQ

    hi
    A switch works with the byte, short, char, and int primitive data types. So you can simply give the
    switch (month) {
                case 1: 
                            System.out.println("January");
                            break;
                case 2:  {
                            System.out.println("February");
                             break;
                case 3: {
                              System.out.println("March");
                              break;
                             }where month controlls the flow
    moreover u can go to http://www.java-samples.com/java/free_calculator_application_in_java.htm
    for reference, just replace the if statement with switch with correct syntax

  • Help needed, new to java programming

    hi,
    I have craeted a Frame with some check boxes and button called "button1".
    Can anyone tell me how can i count the number of CHECKED check boxes so that when i press the button1 in my code it should display the result as number of checked check boxes divided by total number of check boxes. It should display the result in a textfield here RESULT textfield in my code
    Thanks in advance ...i am sending the code i have written so far....
    public class Frame extends java.awt.Frame {
        /** Creates new form Frame */
        public Frame() {
            initComponents();
            setSize(600, 600);
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        private void initComponents() {
            buttonGroup1 = new javax.swing.ButtonGroup();
            checkbox1 = new java.awt.Checkbox();
            checkbox2 = new java.awt.Checkbox();
            checkbox3 = new java.awt.Checkbox();
            button1 = new java.awt.Button();
            textField1 = new java.awt.TextField();
            setLayout(null);
            addWindowListener(new java.awt.event.WindowAdapter() {
                public void windowClosing(java.awt.event.WindowEvent evt) {
                    exitForm(evt);
            checkbox1.setLabel("checkbox1");
            add(checkbox1);
            checkbox1.setBounds(160, 50, 84, 20);
            checkbox2.setLabel("checkbox2");
            add(checkbox2);
            checkbox2.setBounds(160, 70, 84, 20);
            checkbox3.setLabel("checkbox3");
            add(checkbox3);
            checkbox3.setBounds(160, 90, 84, 20);
            button1.setLabel("button1");
            button1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    button1ActionPerformed(evt);
            add(button1);
            button1.setBounds(150, 180, 57, 24);
            textField1.setText("Result");
            textField1.setName("Result");
            add(textField1);
            textField1.setBounds(260, 180, 44, 20);
            pack();
        private void button1ActionPerformed(java.awt.event.ActionEvent evt) {
            // Add your handling code here:
        /** Exit the Application */
        private void exitForm(java.awt.event.WindowEvent evt) {
            System.exit(0);
         * @param args the command line arguments
        public static void main(String args[]) {
            new Frame().show();
        // Variables declaration - do not modify
        private java.awt.Button button1;
        private javax.swing.ButtonGroup buttonGroup1;
        private java.awt.Checkbox checkbox1;
        private java.awt.Checkbox checkbox2;
        private java.awt.Checkbox checkbox3;
        private java.awt.TextField textField1;
        // End of variables declaration
    }

    Two problems in the code you repost-ed:
    1. It lacks import statements.
    2. There is an extraneous } at the end of the button1ActionPerformed method.
    Correct them and it'll work fine. Posting the full source code:
    import java.awt.Component;
    import java.awt.Checkbox;
    public class Frame extends java.awt.Frame
         /** Creates new form Frame */
         public Frame()
              initComponents();
          * This method is called from within the constructor to initialize the form.
          * WARNING: Do NOT modify this code. The content of this method is always
          * regenerated by the Form Editor.
         private void initComponents()
              checkbox1 = new java.awt.Checkbox();
              checkbox2 = new java.awt.Checkbox();
              checkbox3 = new java.awt.Checkbox();
              button1 = new java.awt.Button();
              textField1 = new java.awt.TextField();
              setLayout( null );
              addWindowListener( new java.awt.event.WindowAdapter()
                   public void windowClosing( java.awt.event.WindowEvent evt )
                        exitForm( evt );
              checkbox1.setLabel( "checkbox1" );
              add( checkbox1 );
              checkbox1.setBounds( 120, 40, 84, 20 );
              checkbox2.setLabel( "checkbox2" );
              add( checkbox2 );
              checkbox2.setBounds( 120, 60, 84, 20 );
              checkbox3.setLabel( "checkbox3" );
              add( checkbox3 );
              checkbox3.setBounds( 120, 80, 84, 20 );
              button1.setLabel( "button1" );
              button1.addActionListener( new java.awt.event.ActionListener()
                   public void actionPerformed( java.awt.event.ActionEvent evt )
                        button1ActionPerformed( evt );
              add( button1 );
              button1.setBounds( 50, 170, 57, 24 );
              textField1.setText( "textField1" );
              add( textField1 );
              textField1.setBounds( 240, 170, 60, 20 );
              pack();
         private void button1ActionPerformed( java.awt.event.ActionEvent evt )
              // Add your handling code here:
              Component[] components = getComponents();
              int numOfCheckBoxes = 0;
              int numChecked = 0;
              for ( int i = 0; i < components.length; i++ )
                   if ( components[i] instanceof Checkbox )
                        numOfCheckBoxes++;
                        Checkbox checkBox = (Checkbox) components;
                        if ( checkBox.getState() )
                             numChecked++;
              double ratio = (double) numChecked / (double) numOfCheckBoxes;
              textField1.setText( Double.toString( ratio ) );
         /** Exit the Application */
         private void exitForm( java.awt.event.WindowEvent evt )
              System.exit( 0 );
         * @param args the command line arguments
         public static void main( String args[] )
              new Frame().show();
         // Variables declaration - do not modify
         private java.awt.Button button1;
         private java.awt.Checkbox checkbox1;
         private java.awt.Checkbox checkbox2;
         private java.awt.Checkbox checkbox3;
         private java.awt.TextField textField1;
         // End of variables declaration
    I can see from the code that the GUI was generated by a tool. Since you're new to Java programming, I'd recommend ditching the tool and writing everything by hand, otherwise you're not learning much. It's just like when you're learning proofs in Maths, where you start with first principles before making use of the proofs on their own.
    Also, it'll help tremendously if you could spend some time going through the Java Tutorial (http://java.sun.com/docs/books/tutorial/). It's free, and I find it very useful.
    Hth.

Maybe you are looking for

  • ICal View Options

    Am I wrong or, by upgrading to Leopard have I lost the ability to view all appointments from a selected calendar in list format at the bottom of the calendar? Am I just missing something? I loved that!

  • MS Document Explorer - integration with Oracle documentation

    I can not properly install oracle provided documentation concerning ODP.NET and ODT (developers tools for .net) It should automaticaly integrate with documentation viewer used with MS Visual Studio. This is the same viewer that MSDN Library collectio

  • Finding Duplicate Entries in a table

    I have a table with the following fields in Oracle 10g. TABLE_1 account_no | tracking_id | trans_amount Each account_no can have multiple tracking Id's. How do i query out the duplicate entries of account_no where tracking lies between 1 and 1000 ? M

  • AVCHD or HDV..Yet Another Discussion

    Hello all, Yes I am still struggling with this. I have been downloading AVCHD footage and converting to mpeg and for the most part it edits well on my Alien M17 Quad Core, even though it hicups now and then. My biggest struggle is the conversion time

  • There is no networing between gurest and host

    Hi, i installed linux in vmware and vmware on windows 7. now the problem is guest machine is not pining with host machine, and host machines are also not pining amount it's (there are two linux guest machines) i am searching from 2 days for the solut