Need help with a class project

I'm new to Java and I'm having problems converting a small program to be more functional. Here is my original codeimport java.util.Arrays;
public class Product
// initialize arrays
   private int cdNums[] = { 0,0,0,0 };
   private String cdNames[] = { "null", "null", "null", "null" };
   private int cdUnits[] = { 0,0,0,0 };
   private double cdValue[] = { 0.0, 0.0, 0.0, 0.0 };
   private double inventoryValue[] = { 0.0, 0.0, 0.0, 0.0 };
// initialize instance variable
   private double totalValue = 0;
   private int count;
   public Product( int invNumber[], String albumName[], int invUnits[], double invValue[] )
         cdNums = invNumber;  // store inventory number
         cdNames = albumName;  //store album name
         cdUnits = invUnits;  //store number of units
         cdValue = invValue; // store unit price
   public double calcInventoryValue()
         // calculate Inventory value
            for ( int count = 0; count < cdNums.length; count++ )
                   totalValue =0; // initialize totalValue
                   totalValue =( cdUnits[ count ] * cdValue [ count ] );
           System.out.printf( "%s%d%s%s%s%d%s%.2f%s%.2f\n", "Item #", cdNums[ count ], " is: ", cdNames[ count ], " with ", cdUnits [ count ], " units priced at $", cdValue [ count ], " gives value of $", totalValue );
         return totalValue;
      } // end calcinventoryValue method
} // end classand the test application: import java.util.Arrays;
public class ProductTest
   public static void main( String args[] )
        int invNumber [] = { 1,2,3,4 };
        String albumName[] = { "Wish You Were Here", "Abacab", "Animals", "Security" };
        int invUnits[] = { 200, 150, 50, 500 };
        double invValue[] = { 14.99, 9.99, 23.49, 12.99 };
     Product myProduct = new Product (invNumber, albumName, invUnits, invValue );       
        myProduct.calcInventoryValue();
     } // end main
} // end class ProductTestWhat I want to do is convert it to read in user input instead of static lists. Here is what I have so far:
import java.util.Arrays;
public class Product
// initialize arrays
   private int cdNums[];
   private String cdNames[];
   private int cdUnits[];
   private double cdValue[];
   private double inventoryValue[];
// initialize instance variable
   private double runValue = 0;
   private double totalValue = 0;
   private int count;
   public Product( int invNumber[], String albumName[], int invUnits[], double invValue[] )
         cdNums = invNumber;  // store inventory number
         cdNames = albumName;  //store album name
         cdUnits = invUnits;  //store number of units
         cdValue = invValue; // store unit price
   public double calcInventoryValue()
         // calculate Inventory value
            totalValue = 0; // Initialize totalValue variable
            for ( int count = 0; count < cdNums.length; count++ )
                   runValue =0; // initialize runValue
                   runValue =( cdUnits[ count ] * cdValue [ count ] );
           System.out.printf( "%s%d%s%s%s%d%s%.2f%s%.2f\n", "Item #", cdNums[ count ], " is: ", cdNames[ count ], " with ", cdUnits [ count ], " units priced at $", cdValue [ count ], " gives value of $", runValue );
                 totalValue = totalValue += runValue;
          calcTotalValue( totalValue );
         return totalValue;
      } // end calcinventoryValue method
    public double calcTotalValue( double totalValue )
         System.out.printf( "%s%.2f\n", "The total value of the inventory is: $", totalValue );
          return totalValue;
       } // end calcTotalValue method
} // end classand the new test application:
import java.util.Arrays;
import java.util.Scanner;
public class ProductTest
   public static void main( String args[] )
        double totalValue = 0;
      do 
        { //  open dowhile
         int count = 0; // initialize counter
         Scanner input = new Scanner( System.in ); // call scanner to get input
         for ( int count = 0; count > 0; count++ )
           {  // open for loop
                     System.out.printf ( "%s%d%s\n", "Please enter the inventory # of Item ", count, " or 0 to quit: " );  // prompt for inventory number or sentinel value
                      int invNumber[ count ] = input.nextInt();  // get user input of Item Number
             if ( invNumber[ count ] != 0 )  // check for sentinel
               {  // open if
                     System.out.printf ( "%s%d\n","Please enter the album name of Item #", invNumber[ count ] );  // prompt for album name
                     String albumName[ count ] = input.nextLine();  // get input album name
                     System.out.printf ( "%s%d\n", "Please enter the number of units in stock for Item #", invNumber[ count ] );  // prompt for number of units in stock
                     int invUnits[ count ] = input.nextint();  // input rate of payment
                     System.out.printf ( "%s%.2f\n", "Please enter the unit price for Item #", invNumber[ count ] );  // prompt for unit price
                     double unitValue = input.nextDouble();  // input rate of payment
                     System.out.println();  // print blank line for readability
               } // close if
            else
               {  // open else
                  Product myProduct = new Product (invNumber, albumName, invUnits, invValue );       
                     myProduct.calcInventoryValue();
               } // close else
           } // close for loop           
       } while ( invNumber != 0 );  // loop back to inputting employee name and close dowhile
    } // end main
} // end class ProductTestthe compiler is telling me for ProductTest that it is expecting "]" for the following line: int invNumber[ count ] = input.nextInt();Do I need to store the data in a variable first and then feed it into the array? What do I need to do to complete this code?

OK, yeah. Change the Product constructor so that it takes scalar values (as opposed to arrays) -- a single int for units in stock, and single String for name, etc.
Then you can create multiple objects of that class, one for each CD or whatever.
It makes sense to hardcode values in the ProductTest class, but not really in the Product class. Your ProductTest class is almost there. You know how in the main method you create a single Product object with those arrays? Change it so that you have a loop. Loop through the prices, album names, etc., and create a Product for each set of values. Then put the Product objects in an array, or better yet (and if you've covered it in class) into a Collection like a java.util.HashSet or a java.util.ArrayList.
You said you wanted to make it take values from user input, rather than hardcoded lists. Once you've made the above change, move on to doing that. You can read user input with a java.util.Scanner. Or you can use a java.io.BufferedReader. Did the prof say to use one particular method or another?

Similar Messages

  • I need help with my hangman project

    I'm working on a project where we are developing a text based version of the game hangman. For every project we add a new piece to the game. Well for my project i have to test for a loser and winner for the game and take away a piece of the game when the user guesses incorrectly. these are the instrcutions given by my professor:
    This semester we will develop a text based version of the Game Hangman. In each project we will add a new a piece to the game. In project 4 you will declare the 'figure', 'disp', and 'soln' arrays to be attributes of the class P4. However do not create the space for the arrays until main (declaration and creation on separate lines). If the user enters an incorrect guess, remove a piece of the figure, starting with the right leg (looking at the figure on the screen, the backslash is the right leg) and following this order: the left leg (forward slash), the right arm (the dash or minus sign), the left arm (the dash or minus sign), the body (vertical bar), and finally the head (capital O).
    Not only will you need to check for a winner, but now you will also check to see if all the parts of the figure have been removed, checking to see if the user has lost. If the user has lost, print an error message and end the program. You are required to complete the following operations using for loops:
    intializing appropriate (possible) variables, testing to see if the user has guessed the correct solution, testing to see if the user has guessed a correct letter in the solution, and determining / removing the next appropriate part of the figure. All other parts of the program will work as before.
    Declare figure, disp, and soln arrays as attributes of the class
    Creation of the arrays will remain inside of main
    Delete figure parts
    Check for loss (all parts removed)
    Implement for loops
    Init of appropriate arrays
    Test for winner
    Test if guess is part of the solution
    Removal of correct position from figure
    Output must be
    C:\jdk1.3.1\bin>java P3
    |
    |
    O
    -|-
    Enter a letter: t
    |
    |
    O
    -|-
    t _ _ t
    Enter a letter: a
    |
    |
    O
    -|-
    t _ _ t
    Enter a letter: e
    |
    |
    O
    -|-
    t e _ t
    Enter a letter: l
    |
    |
    O
    -|-
    t e _ t
    Enter a letter: s
    |
    |
    O
    -|-
    t e s t
    YOU WIN!
    C:\jdk1.3.1\bin>java P3
    Pete Dobbins
    Period 5, 7, & 8
    |
    |
    O
    -|-
    Enter a letter: a
    |
    |
    O
    -|-
    Enter a letter: b
    |
    |
    O
    -|-
    Enter a letter: c
    |
    |
    O
    -|
    Enter a letter: d
    |
    |
    O
    |
    Enter a letter: e
    |
    |
    O
    |
    _ e _ _
    Enter a letter: f
    |
    |
    O
    _ e _ _
    Enter a letter: g
    |
    |
    _ e _ _
    YOU LOSE!
    Well i have worked on this and come up with this so far and am having great dificulty as to i am struggling with this class. the beginning is just what i was suppose to comment out. We are suppose to jave for loops for anything that can be put into a for loop also.
    /* Anita Desai
    Period 5
    P4 description:
    1.Declare figure, disp, and soln arrays as attributes of the class
    2.Creation of the arrays will remain inside of main
    3.Delete figure parts
    4.Check for loss (all parts removed)
    5.Implement for loops
    A.Init of appropriate arrays
    B.Test for winner
    C.Test if guess is part of the solution
    D.Removal of correct position from figure
    //bringing the java Input / Output package
    import java.io.*;
    //declaring the program's class name
    class P4
    //declaring arrays as attributes of the class
    public static char figure[];
    public static char disp[];
    public static char soln[];
    // declaring the main method within the class P4
    public static void main(String[] args)
    //print out name and period
    System.out.println("Anita Desai");
    System.out.println("Period 5");
    //creating the arrays
    figure = new char[6];
    soln = new char[4];
    disp = new char[4];
    figure[0] = 'O';
    figure[1] = '-';
    figure[2] = '|';
    figure[3] = '-';
    figure[4] = '<';
    figure[5] = '>';
    soln[0] = 't';
    soln[1] = 'e';
    soln[2] = 's';
    soln[3] = 't';
    //for loop for disp variables
    int i;
    for(i=0;i<4;i++)
    disp='_';
    //Using a while loop to control program flow
    while(true)
    //drawing the board again!
    System.out.println("-----------");
    System.out.println(" |");
    System.out.println(" |");
    System.out.println(" " + figure[0]);
    System.out.println(" " + figure[1] + figure[2] + figure[3]);
    System.out.println(" " + figure[4] + " " + figure[5]);
    System.out.println("\n " + disp[0] + " " + disp[1] + " " + disp[2] + " " + disp[3]);
    //getting input
    System.out.print("Enter a letter: ");
    //declaring a string variable
    String data = " ";
    // call the readString method
    data = readString();
    //retrieves the character at position zero
    char temp;
    temp=data.charAt(0);
    int h;
    for(h=0;h<4;h++)
    if(temp==soln[h])
    disp[h]=soln[h];
    return;
    if(disp[h]==soln[h])
    System.out.println("You Win");
    else
    for(h=0;h<6;h++)
    if(temp!=soln[h])
    figure[h] = ' ';
    return;
    if(disp[h]!=soln[h])
    System.out.println("You Lose");
    ///Test if statements to replace user input with soln if correct
    int j;
    for(j=0;j<4;j++)
    if(temp==soln[j])
    disp[j]=soln[j];
    //declared the readString method, we specified that it would
    //be returning a string
    public static String readString()
    //make connection to the command line
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    //declaring a string variable
    String s = " ";
    //try to do something that might cause an error
    try
    //reading in a line from the user
    s = br.readLine();
    catch(IOException ex)
    //if the error occurs, we will handle it in a special way
    //give back to the place that called us
    //the string we read in
    return s;
    If anyone cann please help me i would greatly appreciate it. I have an exam coming up on wednesday also so i really need to understand this material and see where my mistakes are. If anyoone knows how to delete the parts of the hangman figure one by one each time user guessesincorrectly i would appreciate it greatly. Any other help in solving this program would be great help. thanks.

    Hi thanks for responding. Well to answer some of your questions. The professors instructions are the first 2 paragraphs of my post up until the ende of the output which is You lose!. I have to have the same output as the professor stated which is testing for a winner and loser. Yes the program under the output is what i have written so far. This is the 3rd project and in each we add a little piece to the game. I have no errors when i run the program my problem is when it runs it just prints the hangman figure, disp and then asks user ot enter a letter. Well once i enter a letter it just prints that letter to the screen and the prgram ends.
    As far as the removal of the parts. the solution is TEST. When the user enters a letter lets say Tthen the figure should display again with the disp and filled in solution with T. Then ask for a letter again till user has won and TEST has been guessed correctly. Well then we have to test for a loser. So lets the user enters a R, well then the right leg of the hangman figure should be blank indicating a D the other leg will be blank until the parts are removed and then You lose will be printed to the screen.
    For the program i am suppose to use a FOR LOOPto test for a winner, to remove the parts one at a time, and to see if the parts have been removed if the user guesses incorrectly.
    so as u can see in what i have come up with so far i have done this to test for a winner and loser:
    //declaring a string variable
    String data = " ";
    // call the readString method
    data = readString();
    //retrieves the character at position zero
    char temp;
    temp=data.charAt(0);
    int h;
    for(h=0;h<4;h++)
    if(temp==soln[h])
    disp[h]=soln[h];
    return;
    if(disp[h]==soln[h])
    System.out.println("You Win");
    else
    for(h=0;h<6;h++)
    if(temp!=soln[h])
    figure[h] = ' ';
    return;
    if(disp[h]!=soln[h])
    System.out.println("You Lose");
    Obviously i have not writtern the for loops to do what is been asked to have the proper output. the first for loop i am trying to say if the user input is equal to the soln thencontinue till all 4 disp are guessed correctly and if all the disp=soln then the scrren prints you win.
    then for the incorrect guesses i figured if the user input does not equal the soln then to leave a blank for the right leg and so on so i have a blank space for the figure as stated
    :for(h=0;h<6;h++)
    if(temp!=soln[h])
    figure[h] = ' ';
    well this doesnt work and im not getting the output i wanted and am very confused about what to do. I tried reading my book and have been trying to figure this out all night but i am unable to. I'm going to try for another hr then head to bed lol its 4am. thanks for your help. Sorry about posting in two different message boards. I wont' do it again. thanks again, anita

  • Need help with a Class.

    Ok hey guys i got A project for school and i need help. I asked my teacher and he num so yea. here it is
    this is my blog class
    /* Project Name: .java
                 Name:
                Class: Programing 2 #0047-02 Pds 5&6
      Variable List:
                   Info:
    import java.util.Scanner;
    import java.util.Date;
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    public class blog
         String date2;
         String user;
         String Entry;
         public void GetInfo(String Iuser,String IEntry)
              DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
              Date date = new Date();
              date2 = dateFormat.format(date);
              user = Iuser;
              Entry = IEntry:
         public void ShowInfo()
              System.out.println(date2 + " " + user + " Said: " + Entry);
    }This is my test class
    /* Project Name: .java
                 Name: Josh
                Class: Programing 2 #0047-02 Pds 5&6
      Variable List:
                   Info:
    import java.util.Scanner;
    public class test
         String user;
         String Entry;
         public static void main (String[] args)
         {     System.out.println("Welcome Please Eneter UserName");
              Scanner kb = new Scanner(System.in);
              user = kb.next();
              System.out.println("Please Enter Your Entry");
              Entry = kb.next();
              blog info = new blog();
              blog.GetInfo(user,Entry);
              blog.ShowInfo();
    }So what is sopost to do in the test it ask user to import user name and entery. It send it to blog Class, then it send it out. Here is my errors
    G:\VOC T2\Java\Chap4\test.java:21: non-static variable user cannot be referenced from a static context
              user = kb.next();
              ^
    G:\VOC T2\Java\Chap4\test.java:25: non-static variable Entry cannot be referenced from a static context
              Entry = kb.next();
              ^
    G:\VOC T2\Java\Chap4\test.java:29: non-static variable user cannot be referenced from a static context
              blog.GetInfo(user,Entry);
                           ^
    G:\VOC T2\Java\Chap4\test.java:29: non-static variable Entry cannot be referenced from a static context
              blog.GetInfo(user,Entry);
                                ^
    G:\VOC T2\Java\Chap4\test.java:29: GetInfo(java.lang.String,java.lang.String,java.lang.String) in blog cannot be applied to (java.lang.String,java.lang.String)
              blog.GetInfo(user,Entry);
                  ^
    G:\VOC T2\Java\Chap4\test.java:31: non-static method ShowInfo() cannot be referenced from a static context
              blog.ShowInfo();
                  ^
    6 errors
    Tool completed with exit code 1 Plez help

    -- "non-static X cannot be referenced from a static context" --
    You get this error because static members don't require an instance of the object to be accessed; they belong to the class. But a non-static member belongs to an instance (an individual object). There's no way for the static method to know which instance's variable to use or method to call, and thus, the compiler happily tells you that you can't access an instance member (non-static) from a class context (static).
    [The Java? Tutorial - Understanding Instance and Class Members|http://java.sun.com/docs/books/tutorial/java/javaOO/classvars.html]
    ~

  • Need help with lost iMovie project.

    I was creating an iMovie project for school and needed to save it on a USB, so I clicked on 'Export Movie' from the 'Share' options menu in iMovie. I chose the type I wanted it saved in (viewing for computers) and then a smaller screen in iMovie popped up saying it was exporting the movie, or something like that. It took about a good 30 minutes and my project was a 7 minute movie with film clips, music, transitions, ect. I exported this project to my USB but when it finished it wasn't on there and when I finally found it on the Mac somewhere, I went to drag it into my USB but it said it was full. I then dragged the project onto my desktop and tried to open it to see if it worked. When I did the iMovie icon jumped once and stopped. I clicked on iMovie and it was still there in the projects screen. I then decided to close iMovie and open the project again from my desktop to see if it would play like a normal movie but once I clicked it the iMovie icon jumped again, opened but my project that I was trying to open was not there anymore and wouldn't open from my desktop file. I cannot open it at all and view it, it has been lost from my iMovie. Is there a way that I can get it back? Really need some help with this.

    What version of iMovie are you using?
    Matt

  • Need Help with new Classes / methods

    Hi, I need to create a class called Proposition. It include a Proposition object with 3 variables
    Name, Description, Value
    This is the constructor I wrote:
    private String name;
    private String description;
    private boolean value;
    public Proposition(){
              name = "name";
              description = "description";
              value = false;
    }Now I need a method that give values to the 3 variables in the proposition object:
         public Proposition setProp(String line){
              StringTokenizer ST1 = new StringTokenizer(line, ".");
              String ValidLine = ST1.nextToken()+".";
              StringTokenizer ST2 = new StringTokenizer(ValidLine, "=");
              name = CutSpace(ST2.nextToken());
              description = (ST2.nextToken()).trim();
              value = false;
              return name;
              return description;
              return value;
         }An example of String line is: v = we are in Vancouver.
    When I run the program, I got error message with the 3 return statements saying found String/Boolean while Proposition is needed. I'm not quite sure how to write the return statements. Can any1 help?
    Thx!

    Your setProp() method should not be returning anything. After all it is setting not getting. So just declare it as
    public void setProp(String line){and remove the return statements.

  • Need help with JComponent class

    Hi,
    I'm trying to create a class that has all the characteristics of several GUI components such as JButton, JLabel, JRadioButton .... combined into one big class. But when I run the codes, the object of this new class is not visible on a frame like a JButton or a JLabel would be. Someone, please give me some hints. Thanks.
    The ButtonWrapper class extends JButton and the CheckBoxWrapper class extends JCheckBox and they both work without any problems. The GuiWrapper class (listed below) is the class that has the visibility problem when added to a container of a frame.
    import java.awt.*;
    import javax.swing.*;
    public class GuiWrapper extends JComponent{
      public GuiWrapper(String ptype, String p2, String p3) {
         if(ptype.toLowerCase() == "button"){
           ButtonWrapper b = new ButtonWrapper(p2, p3);
         if(ptype.toLowerCase() == "checkbox"){
           CheckBoxWrapper c = new CheckBoxWrapper(p2, p3);
    }

    Okay, so, for starters, I think this is a Really Bad Idea. If your developers can't handle using the API/tutorial to learn how the components work, your project will fail. This UberClass will not help in the long run. It will also almost certainly turn into a maintainence nightmare for you.
    Of course, since you're going to do it anyway... I suspect your issue lies with paintComponent. If I recall correctly, paintComponent doesn't render anything by default for a JComponent. You'll need to override paintComponent and have it invoke the renderer for the relevant child component.

  • Need help with saving my project

    When I try to export and save my project, iMovie answers that I need more storage space to go on and that I need to end and restart the program. What can I do to save my project? There is lots of work in it. Thank you.

    If iMovie is only preventing you from sharing/exporting your movie, your project itself should still be OK.
    If you have everything on your internal drive it is probably getting too full (you can check with finder).   You need to free up some space or get an external hard drive.  An external drive is almost essential if you are going to do a lot of video work since file are so large.
    Geoff.

  • Need help with an array project please =)

    I'm having trouble figuring out where to start. My project is to create an applet that accepts 20 numbers from a text field one by one and adds them to an array. The numbers have to be between 10 and 50 or else the applet shouldn't include them in the 20 but duplicates should be included in the 20. The applet then has to display all the numbers except for duplicates. example:
    user inputs:
    10,11,12,13,14,15,16,16,16,17,18,19,20,20,20,21,23,24,25,26
    applet detects that 20 numbers have been entered and displays them exluding duplicates:
    10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 23, 24, 25, 26
    If the user imputs a number like 72 I need to make it alert them that the number was not in the 10-50 range and not add that number to the total 20.
    I'm not asking anyone to do this for me, I'm just asking for tips on where to get a good start.
    Thanks!

    //i haven't tryed that code, and it might not work
    // anyhow, just in case, i'll also say that this is not an applet
    public class NoDublicates {
    public static void main(String[] args) {
      if (args.length < 20) {
       System.out.println("usage:\njava NoDublicates "
         + "<and 20 space separated numbers from 10 to 50 here>");
       System.exit(1);
      byte[] nums = new byte[args.length];
      int i = 0;
      for (int j = 0; j < args.length; j++) {
       try {
        int temp = Integer.parseInt(args[j]);
        if (temp <= 50 && temp >= 10) {
         nums[i++] = temp;
       } catch (NumberFormatException nfe) {
        // very bad exception, i think i'll ignore it
      if (i != 20) {
       System.out.println("it seems that i didn't get exactly 20 "
        + "parseable numbers as arguments, let's exit now.");
       System.exit(1);
      java.util.Arrays.sort(nums);
      int old = 0;
      for (int j = 0; j < 20; j++) {
       if (nums[j] != old) {
        System.out.print(nums[j] + " ");
       old = nums[j];
    }

  • Need help with Runtime class in UNIX

    I am attempting to kick off a C++ executable from within java. This class is called through a UI.
    The executable runs in the form of the exec followed by name=value pairs, ie [path/exec] [n=v] [n=v] ... and runs fine from the command line.
    Examples: These don't kick it off, but don't error either.
    String cmd[] = {"/bin/sh","-c","[path]/[exec] [n=v]};
    String cmd[] = new String[3];
    cmd[0] = "[path]/[exec]";
    cmd[1] = "[n=v]";
    cmd[2] = "[n=v]";
    Process p = Runtime.getRuntime().exec(cmd);
    I'm thinking it may be an environment issue, ie env vars not set because the only way I can get this to work is to put the command in a shell script that sets the env vars and kicks off the executable. Like:
    String cmd[] = {"/bin/sh","-c","/[path]/test.sh"};
    I'd prefer to kick this off from the java code. It sounds like I need to find a way to shell out, run our script to set env vars, then kick off the exec. This is my first attempt w/ using Runtime, so maybe I'm missing something.
    Thanks in advance for the help.

    I think this sort of thing will depend upon the shell you're in. When you use Runtime.exec you (might) lose your "parent" shell's environment variables - this question shows up here now and again, here's one thread that might help:
    http://forum.java.sun.com/thread.jspa?threadID=468648&messageID=2172572
    You might find some enlightenment on Roedy's Java Glossary here: http://mindprod.com/jgloss/exec.html
    Hope that helped
    Lee

  • Need help with generic class with comparable type

    Hi. I'm at University, and I have some coursework to do on writing a generic class which offers ordered binary trees of items which implement the comparable interface.
    I cant get the code to compile which I have written.
    I get the error: OBTComparable.java uses unchecked or unsafe operations
    this is the more detailed information of the error when I compile with -Xlint:unchecked
    OBTComparable.java:62: warning: [unchecked] unchecked call to insert(OBTType) as
    a member of the raw type OBTComparable
    left.insert(insertValue);
    ^
    OBTComparable.java:64: warning: [unchecked] unchecked call to insert(OBTType) as
    a member of the raw type OBTComparable
    right.insert(insertValue);
    ^
    OBTComparable.java:75: warning: [unchecked] unchecked call to find(OBTType) as a
    member of the raw type OBTComparable
    return left.find(findValue);
    ^
    OBTComparable.java:77: warning: [unchecked] unchecked call to find(OBTType) as a
    member of the raw type OBTComparable
    return right.find(findValue);
    ^
    and here is my code for the class
    public class OBTComparable<OBTType extends Comparable<OBTType>>
      // A tree is either empty or not
      private boolean empty;
      // If the tree is not empty then it has
      // a value, a left and a right.
      // These are not used it empty == true
      private OBTType value;
      private OBTComparable left;
      private OBTComparable right;
      // Create an empty tree.
      public OBTComparable()
        setEmpty();
      } // OBTComparable
      // Make this tree into an empty tree.
      private void setEmpty()
        empty = true;
        value = null; // arbitrary
        left = null;
        right = null;
      } // setEmpty
      // See if this is an empty (Sub)tree.
      public boolean isEmpty()
      { return empty; }
      // Get the value which is here.
      public OBTType getValue()
      { return value; }
      // Get the left sub-tree.
      public OBTComparable getLeft()
      { return left; }
      // Get the right sub-tree.
      public OBTComparable getRight()
      { return right; }
      // Store a value at this position in the tree.
      private void setValue(OBTType requiredValue)
        if (empty)
          empty = false;
          left = new OBTComparable<OBTType>(); // Makes a new empty tree.
          right = new OBTComparable<OBTType>(); // Makes a new empty tree.
        } // if
        value = requiredValue;
      } // setValue
      // Insert a value, allowing multiple instances.
      public void insert(OBTType insertValue)
        if (empty)
          setValue(insertValue);
        else if (insertValue.compareTo(value) < 0)
          left.insert(insertValue);
        else
          right.insert(insertValue);
      } // insert
      // Find a value
      public boolean find(OBTType findValue)
        if (empty)
          return false;
        else if (findValue.equals(value))
          return true;
        else if (findValue.compareTo(value) < 0)
          return left.find(findValue);
        else
          return right.find(findValue);
      } // find
    } // OBTComparableI am unsure how to check the types of OBTType I am comparing, I know this is the error. It is the insert method and the find method that are causing it not to compile, as they require comparing one value to another. How to I put the check in the program to see if these two are of the same type so they can be compared?
    If anyone can help me with my problem that would be great!
    Sorry for the long post, I just wanted to put in all the information I know to make it easier for people to answer.
    Thanks in advance
    David

    I have good news and undecided news.
    First the good news. Your code has compiled. Those are warnings not errors. A warning is the compiler's way of saying "I understand what you are asking but maybe you didn't fully think through the consequences and I just thought I would let you know that...[something] "
    In this case it's warning you that you aren't using generics. But like I said this isn't stopping it from compiling.
    The undecided news is the complier is warning you about not using generics. Are you supposed to use generics for this assignment. My gut says no and if that's true then you have no problem. If you are supposed to use generics well then you have some more work.

  • Need Help with my JSF-Project - ResultSet to List to DataTable/c:foreach

    Hello!
    I am struggeling heavily with JSF and JSTL and JSPs...
    I want to show a list of names from a database in my JSF-Document.
    I have the following bean "Category":
    package de.fh_offenburg.audiodb.webapp;
    import java.sql.Connection;
    import java.sql.ResultSet;
    import java.sql.Statement;
    import java.util.ArrayList;
    import java.util.List;
    import javax.servlet.jsp.jstl.sql.Result;
    public class Category {
         String name = "";
         String creationDate = "";
         int id_kategorie = 0;
         ResultSet resultset;
         Result result;
         Connection con;
         String query = "";
         List result_list;
         Category() {
              result_list = new ArrayList();
              try{
                   con = new ConnectDB().connect();
                   Statement statement = con.createStatement();
                   query = "SELECT * FROM Category WHERE isUKat = '0'";
                   resultset = statement.executeQuery(query);
                   while (resultset.next()) {
                     // Get the data from the row using the column index
                     String name = resultset.getString("name");
                     // create an object for each row (yes, it is hibernate biased) ;-)
                     Cat cat = new Cat();
                     cat.setName(name);
                     cat.setId_kategorie(id_kategorie);
                     // Add the object to the list
                     result_list.add(cat);
              } catch(Exception hcat){
                   System.out.println("HCat-Problem: "+hcat.getMessage());
         public java.lang.String getCreationDate() {
              return creationDate;
         public void setCreationDate(java.lang.String creationDate) {
              this.creationDate = creationDate;
         public int getId_kategorie() {
              return id_kategorie;
         public void setId_kategorie(int id_kategorie) {
              this.id_kategorie = id_kategorie;
         public java.lang.String getName() {
              return name;
         public void setName(java.lang.String name) {
              this.name = name;
         public java.sql.ResultSet getResultset() {
              return resultset;
         public void setResult_cat(java.sql.ResultSet result_cat) {
              this.resultset = result_cat;
         public void setResult(Result result) {
              this.result = result;
         public Result getResult() {
              return result;
         public List getResult_list() {
              return result_list;
         public void setResult_list(ArrayList result_list) {
              this.result_list = result_list;
         }This Bean is registered in my faces-config.xml like this:
    <managed-bean>
      <managed-bean-name>category</managed-bean-name>
      <managed-bean-class>de.fh_offenburg.audiodb.webapp.Category</managed-bean-class>
      <managed-bean-scope>application</managed-bean-scope>
      <managed-property>
       <property-name>creationDate</property-name>
       <property-class>java.lang.String</property-class>
       <value/>
      </managed-property>
      <managed-property>
       <property-name>id_kategorie</property-name>
       <property-class>int</property-class>
       <value/>
      </managed-property>
      <managed-property>
       <property-name>name</property-name>
       <property-class>java.lang.String</property-class>
       <value/>
      </managed-property>
      <managed-property id="result">
       <property-name>result</property-name>
       <property-class>javax.servlet.jsp.jstl.sql.Result</property-class>
       <value/>
      </managed-property>
      <managed-property id="resultset">
       <property-name>resultset</property-name>
       <property-class>java.sql.ResultSet</property-class>
       <value/>
      </managed-property>
      <managed-property id="result_list">
       <property-name>result_list</property-name>
       <property-class>java.util.List</property-class>
       <value/>
      </managed-property>
    </managed-bean>Now I try to read the list of Cats out in my JSF:
                                                      <h:dataTable value="#{category.result_list}" var="result">
                                                           <h:column>
                                                                          <h:outputText value="#{result.name}" />
                                                           </h:column>
                                                      </h:dataTable>... but that doesnt work... I got an error:
    javax.servlet.ServletException: Cannot get value for expression '#{category.result_list}'
         javax.faces.webapp.FacesServlet.service(FacesServlet.java:152)
         org.ajax4jsf.framework.ajax.xmlfilter.BaseXMLFilter.doXmlFilter(BaseXMLFilter.java:96)
         org.ajax4jsf.framework.ajax.xmlfilter.BaseFilter.doFilter(BaseFilter.java:220)
         org.apache.myfaces.webapp.filter.ExtensionsFilter.doFilter(ExtensionsFilter.java:144)
    root cause So what am I doing wrong?
    I did try to do the same with an JSTL-Syntax (which would be better for me, because I want to layout with DIVs not with a Table...):
                                                      <c:forEach items="#{category.result_list}" var="result">
                                                           <div class="div_mini_kat"><c:out value="#{result.name}"/></div>
                                                      </c:forEach>But that doesnt work out neigther...
    Could someone please tell me what I am doing wrong? I am trying this for days now and I am feeling like a bumble-bee in a glasshouse with one small open doorway which I dont see and thousands of m^2 to crash with...
    Thanks to everyone who answers in advance!!!
    Fuchur

    Hello!
    I am struggeling heavily with JSF and JSTL and JSPs...
    I want to show a list of names from a database in my JSF-Document.
    I have the following bean "Category":
    package de.fh_offenburg.audiodb.webapp;
    import java.sql.Connection;
    import java.sql.ResultSet;
    import java.sql.Statement;
    import java.util.ArrayList;
    import java.util.List;
    import javax.servlet.jsp.jstl.sql.Result;
    public class Category {
         String name = "";
         String creationDate = "";
         int id_kategorie = 0;
         ResultSet resultset;
         Result result;
         Connection con;
         String query = "";
         List result_list;
         Category() {
              result_list = new ArrayList();
              try{
                   con = new ConnectDB().connect();
                   Statement statement = con.createStatement();
                   query = "SELECT * FROM Category WHERE isUKat = '0'";
                   resultset = statement.executeQuery(query);
                   while (resultset.next()) {
                     // Get the data from the row using the column index
                     String name = resultset.getString("name");
                     // create an object for each row (yes, it is hibernate biased) ;-)
                     Cat cat = new Cat();
                     cat.setName(name);
                     cat.setId_kategorie(id_kategorie);
                     // Add the object to the list
                     result_list.add(cat);
              } catch(Exception hcat){
                   System.out.println("HCat-Problem: "+hcat.getMessage());
         public java.lang.String getCreationDate() {
              return creationDate;
         public void setCreationDate(java.lang.String creationDate) {
              this.creationDate = creationDate;
         public int getId_kategorie() {
              return id_kategorie;
         public void setId_kategorie(int id_kategorie) {
              this.id_kategorie = id_kategorie;
         public java.lang.String getName() {
              return name;
         public void setName(java.lang.String name) {
              this.name = name;
         public java.sql.ResultSet getResultset() {
              return resultset;
         public void setResult_cat(java.sql.ResultSet result_cat) {
              this.resultset = result_cat;
         public void setResult(Result result) {
              this.result = result;
         public Result getResult() {
              return result;
         public List getResult_list() {
              return result_list;
         public void setResult_list(ArrayList result_list) {
              this.result_list = result_list;
         }This Bean is registered in my faces-config.xml like this:
    <managed-bean>
      <managed-bean-name>category</managed-bean-name>
      <managed-bean-class>de.fh_offenburg.audiodb.webapp.Category</managed-bean-class>
      <managed-bean-scope>application</managed-bean-scope>
      <managed-property>
       <property-name>creationDate</property-name>
       <property-class>java.lang.String</property-class>
       <value/>
      </managed-property>
      <managed-property>
       <property-name>id_kategorie</property-name>
       <property-class>int</property-class>
       <value/>
      </managed-property>
      <managed-property>
       <property-name>name</property-name>
       <property-class>java.lang.String</property-class>
       <value/>
      </managed-property>
      <managed-property id="result">
       <property-name>result</property-name>
       <property-class>javax.servlet.jsp.jstl.sql.Result</property-class>
       <value/>
      </managed-property>
      <managed-property id="resultset">
       <property-name>resultset</property-name>
       <property-class>java.sql.ResultSet</property-class>
       <value/>
      </managed-property>
      <managed-property id="result_list">
       <property-name>result_list</property-name>
       <property-class>java.util.List</property-class>
       <value/>
      </managed-property>
    </managed-bean>Now I try to read the list of Cats out in my JSF:
                                                      <h:dataTable value="#{category.result_list}" var="result">
                                                           <h:column>
                                                                          <h:outputText value="#{result.name}" />
                                                           </h:column>
                                                      </h:dataTable>... but that doesnt work... I got an error:
    javax.servlet.ServletException: Cannot get value for expression '#{category.result_list}'
         javax.faces.webapp.FacesServlet.service(FacesServlet.java:152)
         org.ajax4jsf.framework.ajax.xmlfilter.BaseXMLFilter.doXmlFilter(BaseXMLFilter.java:96)
         org.ajax4jsf.framework.ajax.xmlfilter.BaseFilter.doFilter(BaseFilter.java:220)
         org.apache.myfaces.webapp.filter.ExtensionsFilter.doFilter(ExtensionsFilter.java:144)
    root cause So what am I doing wrong?
    I did try to do the same with an JSTL-Syntax (which would be better for me, because I want to layout with DIVs not with a Table...):
                                                      <c:forEach items="#{category.result_list}" var="result">
                                                           <div class="div_mini_kat"><c:out value="#{result.name}"/></div>
                                                      </c:forEach>But that doesnt work out neigther...
    Could someone please tell me what I am doing wrong? I am trying this for days now and I am feeling like a bumble-bee in a glasshouse with one small open doorway which I dont see and thousands of m^2 to crash with...
    Thanks to everyone who answers in advance!!!
    Fuchur

  • Need help with Calendar class

    I am writing a class that does the following:
    Uses JComboBoxes so that the user can select Day, Month, and Year. I have the months set up January through December. When I choose a month, I wrote a subclass that gets the chosen month and enters the correct number of days in the Day ComboBox.
    Here is some sample code:
    // This code is in the main class
    monthList.addActionListener(new SelectedMonth());
    // This code is in the SelectedMonth subclass
    selected = monthList.getSelectedIndex();
    switch(selected) {
    case 0: // for January
    dayList.removeAllItems();
    g.set(Calendar.MONTH, selected);
    max = g.getActualMaximum(Calendar.DAY_OF_MONTH);
    for(int i = 1; i <= max; i++) {
    dayList.addItem(new Integer(i));
    This code is repeated for Cases 1 through 11 to cover the other months.
    After Day, Month, and Year are selected, I click an OK button and then want to send the chosen Day, Month, and Year to a database. So, I have another subclass which uses ActionListener and gets the data from the Month, Day, and Year ComboBoxes.
    However, I get runtime errors when retrieving the chosen Day using the following command:
    String fromDay = (String)dayList.getSelectedItem();
    Because the Days were put put into the Day JComboBox in a subclass, this doesn't want to work.
    Does anybody have a solution? Any help would be greatly appreciated.
    If you would like to look at all of my code, leave your e-mail address and I'll let you have a look.

    Hi,
    i got solution for ur problem, here u copy the following code and paste in some editor and try to run to see the results.
    import java.io.*;
    import java.awt.*;
    import java.util.Calendar;
    import java.awt.event.*;
    import javax.swing.*;
    public class CalExample extends JFrame
         private String months[]={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};
         private     JComboBox monthList=new JComboBox(months);
         private     JComboBox dayList=new JComboBox();
         private JButton button=new JButton();
         private int selectedMonth=1;
         private int selectedDay=1;
         public static void main(String[] args)
                        CalExample pe=new CalExample();
         public CalExample()
              JPanel panel=new JPanel();
              panel.setBackground(Color.blue);
              panel.setLayout(null);
              // Month Combo Box related init Stuff
              monthList.setBounds(100,30,100,20);
              monthList.setBackground(Color.white);
              // Day Combo Box related init Stuff
              dayList.setBounds(220,30,100,20);
              dayList.setBackground(Color.white);
              // Output textbox init stuff
              button.setBounds(340,30,100,20);
              button.setText(" Click Me ");
              panel.add(monthList);
              panel.add(dayList);
              panel.add(button);
              getContentPane().add(panel);
              setSize(500,300);
              setVisible(true);
              // Adding Listeners
              monthList.addActionListener
                        new ActionListener()
                                  public void actionPerformed(ActionEvent ae)
                                            selectedMonth=monthList.getSelectedIndex();
                                            showDays(selectedMonth);
              button.addActionListener
                        new ActionListener()
                                  public void actionPerformed(ActionEvent ae)
                                            selectedDay=dayList.getSelectedIndex();
                                       JOptionPane.showMessageDialog(null,"You Selected Month : "+(months[selectedMonth])+",--> Day : "+(selectedDay+1));
              addWindowListener(new WindowAdapter()
                   public void windowClosing(WindowEvent we)
                        System.out.println( " Exiting ...");
                        System.exit(0);
              fillCurrentDate();
         public void showDays(int selectedMonth)
              Calendar cal=Calendar.getInstance();
              cal.set(Calendar.MONTH,selectedMonth);
              int maxDays=cal.getActualMaximum(Calendar.DAY_OF_MONTH);
              dayList.removeAllItems();
              for(int i=1;i<=maxDays;i++)
                   dayList.addItem(String.valueOf(i));
         public void fillCurrentDate()
                   Calendar cal=Calendar.getInstance();
                   showDays(cal.get (Calendar.DAY_OF_MONTH));
    HAPPY CODING...
    regards
    Bandi
    mail : [email protected], [email protected]
    ****************** Think Green, Save Green ***************************

  • Need help with adding classes

    for the moment ihave to create a program that will add accountants to contracts.
    now from within contract i want to be able to be able to create a contract and then have a method to add an accountant to the contract...could u look at my contract class and c what im doing wrong please and also u can only have one accountant on each contract
    im getting error....cannot find symbol Accountant(Accountant)
    public class Contract
        // instance variables - replace the example below with your own
        private Accountant anAccountant;
        //the number of days
        private double duration;
        private double rateOfContract;
        private static final double vat= 0.21;
        private boolean complete;
        private String type;
        private boolean occupied;
         * Constructor for objects of class Contract
        public Contract(double duration, String type )//Accountant anAccountant, double duration)
            //this.anAccountant = anAccountant;
            this.duration = duration;
            rateOfContract = 0 ;
            complete = false;
            this.type = type;
            occupied = false;
         * a method to get the accountant
       public Accountant getAccountant()
            return anAccountant;
         * a method to get the rate of the contract
        public double getRateOfContract()
            return rateOfContract;
         * a method to check if the contract is complete
        public boolean getComplete()
            return complete;
         * a method to set if the contract to complete
        public void isComplete()
            complete = true ;
         * add an accountant to the contract if his expertise matches
         * the type of contract
        public void addAccountant(Accountant anAccountant)
          if(anAccountant.getExpertise().equals(type))
                if(occupied = false)
                    //add the accountant to the contract
                    anAccountant = Accountant(anAccountant);
                    System.out.println("an accountant has been added to the contract");
                    rateOfContract = anAccountant.getDailyRate() * duration;
                    occupied = true;
                }else{
            }else{
         * a method to check accupied
        public boolean getOccupied()
            return occupied;
    }Message was edited by:
    molleman

    yes off course i have `and i also have a controller class called firm...but i just want the accountant to be added to the contract....and i just cant do it
    public class Accountant
        // instance variables
        protected String name;
        protected String expertise;
        protected double dailyRate;
        protected boolean isActive;
         * Constructor for objects of class Accountant
        public Accountant(String name, String expertise, double dailyRate)
            this.name = name;
            this.expertise = expertise;
            this.dailyRate = dailyRate;
            isActive = false;
         * a method to get the accountants name name
        public String getName()
            return name;
         * a metohd  to get the acvccontats expertise
        public String getExpertise()
            return expertise;
         * a method to get the accountants daily rate
        public double getDailyRate()
            return dailyRate;
         * a method to check if the accountant is active
        public boolean getIsActive()
            return isActive;
         * a method to set the accountant to active or not
        public void setIsActive(boolean active)
            active = isActive;
    }

  • Please need help with Inner Classes

    Hi! I have the following inner class, but it is not an "explicit" inner class:
    import java.util.*;
    public class EXTERIOR_NOEXPLICITA {
         private Vector i;
         public void llena_Vector(int a){
              i = new Vector();
              for(int z=0;z<=a;z++)
                   i.addElement(""+z);
         public Enumeration test() {
              return new Enumeration(){
                   int item = i.size()-1;
                   public boolean hasMoreElements(){
                        return(item >= 0);
                   public Object nextElement(){
                        if(!hasMoreElements())
                             throw new NoSuchElementException();
                        else
                             return i.elementAt(item--);
    My question is, how can I put it in an explicyt inner class?
    Plese help me! =)
    Raul

    I am not entirely sure what you mean by explicit inner class. If you mean converting your anonymous class into a nested class, then it is quite easy:
    import java.util.*;
    public class EXTERIOR_NOEXPLICITA {
      private Vector i;
      public void llena_Vector(int a) {
        i = new Vector();
        for (int z = 0; z <= a; z++)
          i.addElement("" + z);
      private final class MyEnumeration implements Enumeration {
        int item = i.size() - 1;
        public boolean hasMoreElements() {
          return (item >= 0);
        public Object nextElement() {
          if (!hasMoreElements())
            throw new NoSuchElementException();
          else
            return i.elementAt(item--);
      public Enumeration test() {
        return new MyEnumeration();

  • Need help with a class file!

    How do you decompress or decompile a class file??? I just can't seem to get it...

    One program is called JAD...
    Also the jedit program has a plugin to decompile class files.
    http://www.jedit.org
    Uwe

Maybe you are looking for

  • What do I need to do when I receive the message ". . . your startup disc is full, you need to make some room by deleting some files"

    I hope I'm in the right place since I was sort of redirected here Recently I have been receiving the message that my startup disc is full and that I need to make room by deleting files.  At first I received the message when I left my computer unatten

  • How can i delete a corrupted sparsebundle file

    My TimeCapsule sparsebundle file is corrupt and cannot be opened by TimeMachine anymore. However I cannot delete it either, error message: "The process could not be completed as the object "bands" is in use." (my translation from my German original:

  • Close a trip in Travel Management

    Hi, team, I have a question about travel management. In PR05 there is some trips that the user'd like to close without FI posting. But no deleting or cancelling the trip, only close it. Is it possible? Thanks a lot and regards, L

  • Error retrieving Clob

    Here's my code: Statement stmt= conn.createStatement(); String sql= "select clob from table"; ResultSet rs= stmt.executeQuery(sql); while (rs.next()) { Clob clob= ((ResultSet)rs).getClob("clob"); String tmpClob= clob.getSubString(1, 1500); System.out

  • Data extraction very slow

    Hello All, I am trying to extract data from init 2lis_11_vaitm. But, extraction is very very slow. Total data in init set-up table are only 200k. One thing I noticed is that we changed the extractor to increase a no. of fields to 225. All these field