Help with simple array program

my program compiles and runs but when after i enter in 0 it says that the total cost is 0.0 any help would be great thanks
/**Write a program that asks the user for the price and quantity of up to 10 items. The program accepts input until the user enters a price of 0. 
*The program applies a 7% sales tax and prints the total cost.
Sample
Enter price 1:
1.95
Enter quantity 1:
2
Enter price 2:
5.00
Enter quantity 2:
1
Enter price 3:
0
Your total with tax is 9.52
import java.util.*;
public class Cashregister
static Scanner input = new Scanner(System.in);
static double userinput = 1;
public static void main(String[] args)
  int anykey;
  int howmanyproducts;
  System.out.println("This Program will allow you to enter the price and quanity of a set of items until you press zero, and after you press zero it will put the tax on it and give you the subtotal.");
  int whichproduct = 1;//used to say what
  int whichquanity = 1;
  double beforetax = 0;
  double aftertax = 0;
  double [] finalproduct = new double [9];
  double [] finalquant = new double[9];
  double [] finalanswer = new double[9];
  double taxrate = .07;
  int index = 0;
  while(userinput !=0)
   System.out.println("Enter price " + whichproduct + ":");
   userinput = input.nextDouble();
   whichproduct ++;
   if(userinput != 0)
   finalproduct[index] = userinput;
   System.out.println("Enter quanity " + whichquanity + ":");
   userinput = input.nextInt();
   finalquant[index] = userinput;
   whichquanity ++;
   index ++;
  else
  int [] indecies = new int [index];//used for array.length purposes
   for(int j = 0; j<indecies.length; j++)
     finalanswer[index] = finalproduct[index] * finalquant[index];
  for(int k = 0; k < indecies.length; k++)
     finalanswer[k] = finalanswer[k] + finalanswer[k];
     beforetax = finalanswer[k];
     aftertax = beforetax * taxrate;
  System.out.println("The total cost with tax will be $" + aftertax);
}

I tried ot indent better so it is more readable and i removed the tax out of my loop along with another thing i knew wasnt supposed to be their. Ran it again and i still got the same total coast = 0.0
import java.util.*;
public class Cashregister
static Scanner input = new Scanner(System.in);
static double userinput = 1;
public static void main(String[] args)
  int anykey;
  int howmanyproducts;
  System.out.println("This Program will allow you to enter the price and quanity of a set of items until you press zero, and after you press zero it will put the tax on it and give you the subtotal.");
  int whichproduct = 1;
  int whichquanity = 1;
  double beforetax = 0;
  double aftertax = 0;
  double [] finalproduct = new double [9];
  double [] finalquant = new double[9];
  double [] finalanswer = new double[9];
  double taxrate = .07;
  int index = 0;
  while(userinput !=0)
   System.out.println("Enter price " + whichproduct + ":");
   userinput = input.nextDouble();
   whichproduct ++;
        if(userinput != 0)
                finalproduct[index] = userinput;
                System.out.println("Enter quanity " + whichquanity + ":");
                userinput = input.nextInt();
                finalquant[index] = userinput;
                whichquanity ++;
                index ++;
        else
                int [] indecies = new int [index];
                for(int j = 0; j<indecies.length; j++)
                        finalanswer[index] = finalproduct[index] * finalquant[index];
                for(int k = 0; k < indecies.length; k++)
                       finalanswer[0] = finalanswer[k] + finalanswer[k];
                beforetax = finalanswer[0];
                aftertax = beforetax * taxrate;
                System.out.println("The total cost with tax will be $" + aftertax);
}

Similar Messages

  • Need Help with simple array program!

    Hi, I have just recently started how to use arrays[] in Java and I'm a bit confused and need help designing a program.
    What this program does, it reads in a range of letters specified by the user. The user then enters the letters (a, b or c) and stores these characters into an array, which the array's length is equal to the input range the user would enter at the start of the program. The program is then meant to find how many times (a,b and c) appears in the array and the Index it first appears at, then prints these results.
    Here is my Code for the program, hopefully this would make sense of what my program is suppose to do.
    import B102.*;
    class Letters
         static int GetSize()
              int size = 0;
              boolean err = true;
              while(err == true)
                   Screen.out.println("How Many Letters would you like to read in?");
                   size = Keybd.in.readInt();
                   err = Keybd.in.fail();
                   Keybd.in.clearError();
                   if(size <= 0)
                        err = true;
                        Screen.out.println("Invalid Input");
              return(size);
         static char[] ReadInput(int size)
              char input;
              char[] letter = new char[size];
              for(int start = 1; start <= size; start++)
                   System.out.println("Please enter a letter (a, b or c) ("+size+" max), enter # to stop:");
                   input = Keybd.in.readChar();
                   while((input != 'a') && (input != 'b') && (input != 'c') && (input != '#'))
                        Screen.out.println("Invalid Input");
                        System.out.println("Please enter a letter (a, b or c) ("+size+" max, enter # to stop:");
                        input = Keybd.in.readChar();
                                    while(input == '#')
                                                 start == size;
                                                 break;
                   for(int i = 0; i < letter.length; i++)
                        letter[i] = input;
              return(letter);
         static int CountA(char[] letter)
              int acount = 0;
              for(int i = 0; i < letter.length; i++)
                   if(letter[i] == 'a')
                        acount++;
              return(acount);
         static int CountB(char[] letter)
              int bcount = 0;
              for(int i = 0; i < letter.length; i++)
                   if(letter[i] == 'b')
                        bcount++;
              return(bcount);
         static int CountC(char[] letter)
              int ccount = 0;
              for(int i = 0; i < letter.length; i++)
                   if(letter[i] == 'c')
                        ccount++;
              return(ccount);
         static int SearchA(char[] letter)
              int ia;
              for(ia = 0; ia < letter.length; ia++)
                   if(letter[ia] == 'a')
                        return(ia);
              return(ia);
         static int SearchB(char[] letter)
              int ib;
              for(ib = 0; ib < letter.length; ib++)
                   if(letter[ib] == 'b')
                        return(ib);
              return(ib);
         static int SearchC(char[] letter)
              int ic;
              for(ic = 0; ic < letter.length; ic++)
                   if(letter[ic] == 'c')
                        return(ic);
              return(ic);
         static void PrintResult(char[] letter, int acount, int bcount, int ccount, int ia, int ib, int ic)
              if(ia <= 1)
                   System.out.println("There are "+acount+" a's found, first appearing at index "+ia);
              else
                   System.out.println("There are no a's found");
              if(ib <= 1)
                   System.out.println("There are "+bcount+" b's found, first appearing at index "+ib);
              else
                   System.out.println("There are no b's found");
              if(ic <= 1)
                   System.out.println("There are "+ccount+" c's found, first appearing at index "+ic);
              else
                   System.out.println("There are no c's found");
              return;
         public static void main(String args[])
              int size;
              char[] letter;
              int acount;
              int bcount;
              int ccount;
              int ia;
              int ib;
              int ic;
              size = GetSize();
              letter = ReadInput(size);
              acount = CountA(letter);
              bcount = CountB(letter);
              ccount = CountC(letter);
              ia = SearchA(letter);
              ib = SearchB(letter);
              ic = SearchC(letter);
              PrintResult(letter, acount, bcount, ccount, ia, ib, ic);
              return;
    }     Some errors i get with my program are:
    When reading in the letters to store into the array, I get the last letter I entered placed into the entire array. Also I believe my code to find the Index is incorrect.
    Example Testing: How many letters would you like to read? 3
    Enter letter (a, b or c) (# to quit): a
    Enter letter (a, b or c) (# to quit): b
    Enter letter (a, b or c) (# to quit): c
    It prints "There are no a's'" (there should be 1 a at index 0)
    "There are no b's" (there should be 1 b at index 1)
    and "There are 3 c's, first appearing at index 0" ( there should be 1 c at index 2)
    The last thing is that my code for when the user enters "#" that the input of letters would stop and the program would then continue over to the counting and searching part for the letters, my I believe is correct but I get the same problem as stated above where the program takes the character "#" and stores it into the entire array.
    Example Testing:How many letters would you like to read? 3
    Enter letter (a, b or c) (# to quit): a
    Enter letter (a, b or c) (# to quit): #
    It prints "There are no a's'" (should have been 1 a at index 0)
    "There are no b's"
    and "There are no c's"
    Can someone please help me??? or does anyone have a program simular to this they have done and would'nt mind showing me how it works?
    Thanks
    lou87.

    Without thinking too much...something like this
    for(int start = 0; start < size; start++) {
                System.out.println("Please enter a letter (a, b or c) ("+size+" max), enter # to stop:");
                input = Keybd.in.readChar();
                while((input != 'a') && (input != 'b') && (input != 'c') && (input != '#')) {
                    Screen.out.println("Invalid Input");
                    System.out.println("Please enter a letter (a, b or c) ("+size+" max, enter # to stop:");
                    input = Keybd.in.readChar();
                if(input == '#') {
                        break;
                letter[start] = input;
            }you dont even need to do start = size; coz with the break you go out of the for loop.

  • Need Help with Simple Chat Program

    Hello Guys,
    I'm fairly new to Java and I have a quick question regarding a simple chat program in java. My problem is that I have a simple chat program that runs from its own JFrame etc. Most of you are probably familiar with the code below, i got it from one of my java books. In any case, what I'm attempting to do is integrate this chat pane into a gui that i have created. I attempted to call an instace of the Client class from my gui program so that I can use the textfield and textarea contained in my app, but it will not allow me to do it. Would I need to integrate this code into the code for my Gui class. I have a simple program that contains chat and a game. The code for the Client is listed below.
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.net.*;
    import javax.swing.*;
    public class Client
    extends JPanel {
    public static void main(String[] args) throws IOException {
    String name = args[0];
    String host = args[1];
    int port = Integer.parseInt(args[2]);
    final Socket s = new Socket(host, port);
    final Client c = new Client(name, s);
    JFrame f = new JFrame("Client : " + name);
    f.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent we) {
    c.shutDown();
    System.exit(0);
    f.setSize(300, 300);
    f.setLocation(100, 100);
    f.setContentPane(c);
    f.setVisible(true);
    private String mName;
    private JTextArea mOutputArea;
    private JTextField mInputField;
    private PrintWriter mOut;
    public Client(final String name, Socket s)
    throws IOException {
    mName = name;
    createUI();
    wireNetwork(s);
    wireEvents();
    public void shutDown() {
    mOut.println("");
    mOut.close();
    protected void createUI() {
    setLayout(new BorderLayout());
    mOutputArea = new JTextArea();
    mOutputArea.setLineWrap(true);
    mOutputArea.setEditable(false);
    add(new JScrollPane(mOutputArea), BorderLayout.CENTER);
    mInputField = new JTextField(20);
    JPanel controls = new JPanel();
    controls.add(mInputField);
    add(controls, BorderLayout.SOUTH);
    mInputField.requestFocus();
    protected void wireNetwork(Socket s) throws IOException {
    mOut = new PrintWriter(s.getOutputStream(), true);
    final String eol = System.getProperty("line.separator");
    new Listener(s.getInputStream()) {
    public void processLine(String line) {
    mOutputArea.append(line + eol);
    mOutputArea.setCaretPosition(
    mOutputArea.getDocument().getLength());
    protected void wireEvents() {
    mInputField.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae) {
    String line = mInputField.getText();
    if (line.length() == 0) return;
    mOut.println(mName + " : " + line);
    mInputField.setText("");

    Thanks for ur help!i have moved BufferedReader outside the loop. I dont think i am getting exception as i can c the output once.What i am trying to do is repeat the process which i m getting once.What my method does is first one sends the packet to multicasting group (UDP) and other method receives the packets and prints.

  • Help with an array program

    I can't see how to calculate the lowest hours, highest hours, and average hours worked.
    These three values should be outputted each on a seperate line.
    I just can't figure this out.
    Any help please.
    This program will show the employees
    hours. It will have one
    class.It will use an array to keep
    track of the number of hours the employee
    has worked with the output to the monitor
    of the employees highest, lowest, and the
    average of all hours entered. */
    import java.util.*;
    import java.text.DecimalFormat;
    /*** Import Decimal Formating hours to format hours average. ***/
    public class cs219Arrays
         public static void main(String[] args)
              Scanner scannerObject = new Scanner(System.in);
              int[] employees ={20, 35, 40};
              int employeesHighest = 40;
              int employeesLowest = 20;
              double employeesAverage = 35;
              int[] firstEmployee = new int[1];
              int[] secondEmployee = new int[2];
              int[] thirdEmployee = new int[3];
              System.out.println("This program will accept hours worked for 3 employees.");
              System.out.println("Enter hours worked for employee #: ");
              System.out.println(".\n");
              employeesAverage = scannerObject.nextInt();
              for(int count =20; count <= 40; count++)
                             DecimalFormat df = new DecimalFormat("0.00");
                             System.out.println("pay: " employeesAverage " lowest " employeesHighest " Highest hours " employeesLowest " Lowest hours "+df.format(employeesAverage));
                             System.out.print("\n");
                             employeesAverage++;
    }/* end of body of first for loop */
              for(int count =20; count <= 40; count++)
                                       employeesAverage = employeesAverage + employeesHighest + employeesLowest;
                                       DecimalFormat df = new DecimalFormat("0.00");
                                       System.out.println("pay: $" employeesAverage " lowest " employeesHighest " Highest hours $" +df.format(employeesAverage));
                                       System.out.print("\n");
                                       employeesAverage++;
    }/* end of body of second for loop */
              for(int count =20; count <= 40; count++)
                                       employeesAverage = employeesAverage + employeesHighest + employeesLowest;
                                       DecimalFormat df = new DecimalFormat("0.00");
                                       System.out.println("pay: $" employeesAverage " lowest " employeesHighest " Highest hours $" +df.format(employeesAverage));
                                       System.out.print("\n");
                                       employeesAverage++;
    }/* end of body of third for loop */
              System.out.println("\n");
              DecimalFormat twoDigits = new DecimalFormat("0.00");
              /*** Create new DecimalFormat object named twoDigits ***/
              /*Displays number of hours, employees hours and average hours.*/
              System.out.println("You entered " + employeesAverage + " number of hours.");
              System.out.println("Your number of hours are " + twoDigits.format(employeesAverage));
              System.out.println("\n\n");
    }     /*End of method for data.*/
    {     /*Main method.*/
    }     /*End of main method.*/
    }     /*End of class cs219Arrays.*/

    Want help?
    Use the code formatting tags for starters. http://forum.java.sun.com/help.jspa?sec=formatting

  • Help with simple pong program

    Hi, I'm in APCS and I was wondering if you guys can help me out with my code. I'm designing Pong, except instead of having 2 paddles it will have 4. I think i have 95% of my code down, enough to get the program running. However, my compiler cannot recognize the move methods for my paddles:
    --------------------Configuration: Pong - JDK version 1.6.0_02 <Default> - <Default>--------------------
    F:\Documents\AP Computer Science-Java Applications\Pong\Pong\src\Pong.java:106: cannot find symbol
    symbol : method paddleMove(PingPongBall)
    location: class Paddle
    computerPaddle1.paddleMove( ball );
    ^
    F:\Documents\AP Computer Science-Java Applications\Pong\Pong\src\Pong.java:177: cannot find symbol
    symbol : method paddleMove(int)
    location: class Paddle
    playerPaddle1.paddleMove( mouseY );
    ^
    F:\Documents\AP Computer Science-Java Applications\Pong\Pong\src\Pong.java:178: cannot find symbol
    symbol : method paddleMove(int)
    location: class Paddle
    playerPaddle2.paddleMove( mouseY );
    ^
    Note: F:\Documents\AP Computer Science-Java Applications\Pong\Pong\src\Pong.java uses or overrides a deprecated API.
    Note: Recompile with -Xlint:deprecation for details.
    3 errors
    Process completed.
    And I guess I also use old methods of coding, according to the deprecated API note.
    What do you think could possibly be causing these errors to be thrown? I'm pretty sure I have everything spelled correctly...
    Thanks for all your help. :) Any comments/advice/criticism is welcome.

    1. If you're using an IDE such as NetBeans or Eclipse, do a "Clean Project", then a "Build All". See if that clears up the problem.
    2. If it doesn't, then your Paddle class does not have a paddleMove(PingPongBall) or paddleMove(int) method. If other Paddle class methods are being found okay (i.e., you get no compiler errors where you use them), then it definitely means that your compiler is picking up an older version of your Paddle class, one without those methods defined. If no paddle methods are resolving okay, then that means your compiler can't find your Paddle class at all.
    Open your Paddle class and carefully verify that these two methods exist. If they do, then something is wrong with your IDE configuration/Ant script/whatever you're using to compile, and it's not finding the (correct) Paddle.class file.
    As for the deprecation warning, do what it says: Change your compile command to include the "-Xlint:deprecation" parameter and recompile. It will tell you the line number(s) where you're calling deprecated methods.
    Post back with your results.

  • Need help with an arrays program

    this is the task
    1.instantiate an array to hold integer test scores
    2.determine and print out the total number of scores
    3.determine whether there are any perfect scores (100) and if so print student numbers (who received these scores)
    4.print out only the scores that are greater or equal to 80
    5.calculate the percentage of students that got scores of 80 or above (and print out)
    6.calculate the average of all scores (and print out)
    heres the code that i came up with
    int [] scores = {79, 87, 94, 82, 67, 100, 98, 87, 81, 74, 91, 59, 97, 62, 78, 66, 83, 75, 88, 94, 63, 44, 100, 69, 87, 99, 76, 72};
    int total=scores.length;
    System.out.println("The total number of scores is: "+total);
    for (int i=0;i<=scores.length;i++)
    System.out.println(scores);
    step 2 is as far as i got
    i got stuck at step 3, i cant figure out how to do that
    reply plz, ty

    3.determine whether there are any perfect scores (100) and if so print student numbers (who received these scores)This question strongly suggests that the data contains information about students associated with each of the test scores. As you have illustrated it, part 3 is simply not doable. There must be more to the assignment than you have said.
    Do one thing at a time and make sure your code compiles and runs as you expect before moving on. The code you have posted looks OK for the first couple of steps, but its it's impossible to say unless you post something that's runnable.
    (A small thing - but very much appreciated - can you please post code using the "code" tags? Put {code} at the start of your code and again at the end. That way the code will be nicely formatted by the forum's astounding software.)

  • Help with Simple JAVA program

    I'm a complete novice with Java. I want to write a Java program to run on Windows 2000 servers to write a list of certain files in a directory into a *.txt file. I hope to add complexity once I have this basic part working. Here's the code I have so far:
    //this Java application finds poll* files
    public class FindPollApp
    //Create File Object
    File dir = new File("d:/jda/windss/poll");
    //List directory
    if(dir.isDirectory())
    String[] dirContents = dir.list();
    for (int i=0; i < dirContents.length; i++)
    System.out.println(dirContents);
    //Iterate through files
    I get the following errors:
    C:\JAVA>javac FindPollApp.java
    FindPollApp.java:9: illegal start of type
    if(dir.isDirectory())
    ^
    FindPollApp.java:18: <identifier> expected
    ^
    2 errors
    Thanks.

    I'm a complete novice with Java. I want to write a
    Java program to run on Windows 2000 servers to write
    a list of certain files in a directory into a *.txt
    file. I hope to add complexity once I have this
    basic part working. Here's the code I have so far:
    //this Java application finds poll* files
    public class FindPollApp
    //Create File Object
    File dir = new File("d:/jda/windss/poll");
    //List directory
    if(dir.isDirectory())
    String[] dirContents = dir.list();
    for (int i=0; i < dirContents.length; i++)
    System.out.println(dirContents);
    //Iterate through files
    I get the following errors:
    C:\JAVA>javac FindPollApp.java
    FindPollApp.java:9: illegal start of type
    if(dir.isDirectory())
    ^
    FindPollApp.java:18: <identifier> expected
    ^
    2 errors
    Thanks.
    You need to create a method and insert your if statement in there

  • Help with simple bidding program

    I have a BiddingServer and a BiddingClient, Everytime a client connects it connects twice for some reason, and shows "New Bidder Accepted" twice... Can't work out why, any help appreciated.... I dont know whether the problem is here or in the client and i appreciate its looong so if no one spots a problem here ill post the client....
    import java.io.*;
    import java.net.*;
    import java.text.DecimalFormat;
    import java.util.*;
    public class BiddingServer
         private static ServerSocket servSocket;
         private static final int PORT = 1234;
         public static Scanner keyboard = new Scanner(System.in);
         public static String itemDescripOne = "TV", itemCodeOne = "123";
         public static String itemDescripTwo = "Toaster", itemCodeTwo = "321";
         public static float itemPriceOne = 100, itemPriceTwo = 200;
         public static Calendar deadlineOne;
         public static Calendar deadlineTwo;
         private static int clientCount =0;
         public static void main(String[] args)throws IOException
         Calendar start = Calendar.getInstance();
         int date = start.get(Calendar.DATE);
         int month = start.get(Calendar.MONTH);
         int year = start.get(Calendar.YEAR);
                   System.out.printf("\nEnter First Item's finishing bid time");
                   String timeString = BiddingServer.keyboard.nextLine();
                   String hourString = timeString.substring(0,2);
                   int hour = Integer.parseInt(hourString);
                   String minString = timeString.substring(3,5);
                   int minute = Integer.parseInt(minString);
                   BiddingServer.deadlineOne = Calendar.getInstance();//Set up Calendar object to hold deadline time...
                   BiddingServer.deadlineOne.set(year,month,date,hour,minute,0);
                   System.out.println("\nEnter Second Item's finishing bid time:\n");
                   String timeString1 = BiddingServer.keyboard.nextLine();
                   String hourString1 = timeString1.substring(0,2);
                   int hour1 = Integer.parseInt(hourString1);
                   String minString1 = timeString1.substring(3,5);
                   int minute1 = Integer.parseInt(minString1);
                   BiddingServer.deadlineTwo = Calendar.getInstance();//Set up Calendar object to hold deadline time...
                   BiddingServer.deadlineTwo.set(year,month,date,hour1,minute1,0);
                   System.out.println("Opening port...\n");
                   try
                        servSocket = new ServerSocket(PORT);
                   catch (IOException e)
                        System.out.println("\nUnable to set up port!");
                        System.exit(1);
              do
                   Socket client = servSocket.accept();
                   clientCount++;
                   //Wait for client.
                   System.out.println("\nNew bidder accepted.\n");
                   ClientHandler handler = new ClientHandler(client, clientCount);
                   handler.start();
              }while (true);
         class ClientHandler extends Thread
              private Socket client;
              private Scanner input, keyboard;
              private PrintWriter output;
              int clientNumber;
              public ClientHandler(Socket socket, int count) throws IOException
                   client = socket;
                   clientNumber = count;
                   keyboard = new Scanner(System.in);
                   input = new Scanner(client.getInputStream());
                   output = new PrintWriter(client.getOutputStream(),true);
              public void run()
                   String userInput;
                   float price, priceTwo ;
                   output.println(BiddingServer.itemDescripOne);
                   output.println(BiddingServer.itemCodeOne);
                   output.println(getDateTime(BiddingServer.deadlineOne));
                   output.println(BiddingServer.itemDescripTwo);
                   output.println(BiddingServer.itemCodeTwo);
                   output.println(getDateTime(BiddingServer.deadlineTwo));
                   do
                        userInput = input.nextLine();
                        Calendar now = Calendar.getInstance();
                        if (userInput.startsWith("number of bidders"))
                             System.out.println("Number of Bidders Online " + clientNumber);
                             output.println(clientNumber);
                        else if ((userInput.startsWith(BiddingServer.itemCodeOne)) && (userInput.endsWith("Status")))
                             System.out.println("item price one");
                             output.println(BiddingServer.itemPriceOne);
                        if ((userInput.startsWith(BiddingServer.itemCodeOne)) && (userInput.endsWith("Status")) && (now.after(BiddingServer.deadlineOne)))
                             System.out.println("-1, bidding for item ended");
                             output.println("-1");
                        else if (userInput.startsWith(BiddingServer.itemCodeOne))
                                  price = Float.parseFloat(userInput.substring(BiddingServer.itemCodeOne.length() +1));
                             if ((price > BiddingServer.itemPriceOne) && (now.before(BiddingServer.deadlineOne)))
                                  //bidForItem();
                                  System.out.println("Bid Accepted");
                                  output.println("Bid Accepted");
                                  BiddingServer.itemPriceOne = price;     
                             else if (now.after(BiddingServer.deadlineOne))
                                  System.out.println("Late Bid");
                                  output.println("Late Bid");
                             else if ((price <= BiddingServer.itemPriceOne) && (now.before(BiddingServer.deadlineOne)))
                                  System.out.println("Low Bid");
                                  output.println("Low Bid");
                        if ((userInput.startsWith(BiddingServer.itemCodeTwo)) && (userInput.endsWith("Status")))
                             System.out.println("item price one");
                             output.println(BiddingServer.itemPriceOne);
                        else if ((userInput.startsWith(BiddingServer.itemCodeTwo)) && (userInput.endsWith("Status")) && (now.after(BiddingServer.deadlineTwo)))
                             System.out.println("-1, bidding for item ended");
                             output.println("-1");
                        else if (userInput.startsWith(BiddingServer.itemCodeTwo))
                                  priceTwo = Float.parseFloat(userInput.substring(BiddingServer.itemCodeTwo.length() +1));
                                  if ((priceTwo > BiddingServer.itemPriceTwo) && (now.before(BiddingServer.deadlineTwo)))
                                       System.out.println("Bid Accepted");
                                       output.println("Bid Accepted");
                                       BiddingServer.itemPriceTwo = priceTwo;
                                  else if (now.after(BiddingServer.deadlineTwo))
                                       System.out.println("Late Bid");
                                       output.println("Late Bid");
                                  else if ((priceTwo <= BiddingServer.itemPriceTwo) && (now.before(BiddingServer.deadlineTwo)))
                                       System.out.println("Low Bid");
                                       output.println("Low Bid");
                   }while (true);
         public String getDateTime(Calendar dateTime)
              //Create DecimalFormat object to ensure 2 dec places...
              DecimalFormat decFormat = new DecimalFormat("00");
              //Now extract hours and minutes, each with 2 digits
              //(i.e., with leading zeroes if needed)...
              String hour2Digits =
                   decFormat.format(dateTime.get(Calendar.HOUR_OF_DAY));
              String min2Digits =
                   decFormat.format(dateTime.get(Calendar.MINUTE));
              return(dateTime.get(Calendar.DATE) + "/"
                        + (dateTime.get(Calendar.MONTH)+1) + "/"
                        + dateTime.get(Calendar.YEAR) + " "
                        + hour2Digits + ":" + min2Digits);
         }

    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import javax.swing.*;
    public class BiddingClient extends JFrame implements ActionListener
         private InetAddress host;
         private final int PORT = 1234;
         private Socket link;
         private Scanner networkInput,keyboard;
         private PrintWriter output;
         private JPanel itemInfo, buttonPanel, comboPanel, headingPanel, selectItemPanel,personalPanel,biddingText;
         private JLabel label1,label2,label3, label4, label,label5, labelCode, labelDescrip,
         labelDeadline, labelPrice,bidStatus,label6,label7;
         private JComboBox itemSelection;
         private JButton bidButton, statusButton, noOfBiddersButton, quitButton;
         private JTextField bid;
         String [] code = new String [2];
         String [] desc = new String [2];
         String [] deadline = new String [2];
         public static void main(String[] args) throws IOException
              BiddingClient frame = new BiddingClient();
              frame = new BiddingClient();
              frame.setTitle("Welcome " + System.getProperty("user.name"));
              Dimension screenSize =
                   Toolkit.getDefaultToolkit().getScreenSize();
         int screenWidth = (int)screenSize.getWidth();
         int screenHeight = (int)screenSize.getHeight();
         int frameWidth=430 ,frameHeight=300;
         frame.setSize(frameWidth,frameHeight);
         frame.setLocation((screenWidth-frameWidth)/2,
                        (screenHeight-frameHeight)/2);
         frame.setVisible(true);
         frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
         public BiddingClient () throws IOException
              addWindowListener(
                        new WindowAdapter()
                             public void windowClosing(WindowEvent e)
                                  if (link != null)
                                  try
                                       link.close();
                                  catch (IOException ioEx)
                                       System.out.println(
                                            "\n*** Unable to close link!***\n");
                                       System.exit(1);
                                  System.exit(0);
              try
                   host = InetAddress.getLocalHost();
              catch(UnknownHostException uhEx)
                   System.out.println("\nHost ID not found!\n");
                   System.exit(1);
              personalPanel = new JPanel(new FlowLayout());
              setLayout(new BorderLayout());
              label6 = new JLabel("Welcome... " + System.getProperty("user.name"));
              label6.setFont (new Font("Edwardian Script ITC",Font.PLAIN,26));
              personalPanel.add(label6, BorderLayout.CENTER);
              personalPanel.setBackground(Color.lightGray);
              add(personalPanel, BorderLayout.NORTH);
              comboPanel = new JPanel(new BorderLayout());
              //comboPanel.setBorder(BorderFactory.createLineBorder(Color.red));
              itemSelection = new JComboBox();
              comboPanel.add(itemSelection, BorderLayout.EAST);
              itemSelection.addActionListener(this);
              add(comboPanel, BorderLayout.NORTH);
              selectItemPanel = new JPanel(new BorderLayout());
              label5 = new JLabel("Please Select An Item From The List:");
              selectItemPanel.add(label5, BorderLayout.CENTER);
              add(selectItemPanel, BorderLayout.WEST);
              headingPanel = new JPanel(new FlowLayout());
              String myText4 = "<HTML><b><u>Information On Item</b></u>";
              label = new JLabel(myText4);
              headingPanel.add(label);
              //headingPanel.setBorder(BorderFactory.createLineBorder(Color.white));
              add(headingPanel, BorderLayout.CENTER);
              comboPanel.add(headingPanel, BorderLayout.SOUTH);
              comboPanel.add(selectItemPanel, BorderLayout.WEST);
              comboPanel.add(personalPanel, BorderLayout.NORTH);
              itemInfo = new JPanel(new GridLayout(6,1));
              String myText = "<HTML><b><u>Description</b></u> : ";
              label1 = new JLabel(myText);
              itemInfo.add(label1);
              labelDescrip = new JLabel();
              labelDescrip.setFont (new Font("ComicSans",Font.PLAIN,12));
              itemInfo.add(labelDescrip);
              String myText1 = "<HTML><b><u>Code</b></u> : ";
              label2 = new JLabel(myText1);
              label2.setFont (new Font("Arial Narrow",Font.BOLD,13));
              itemInfo.add(label2);
              labelCode = new JLabel();
              labelCode.setFont (new Font("ComicSans",Font.PLAIN,12));
              itemInfo.add(labelCode);
              String myText2 = "<HTML><b><u>Deadline</b></u> : ";
              label3 = new JLabel(myText2);
              itemInfo.add(label3);
              labelDeadline = new JLabel();
              labelDeadline.setFont (new Font("ComicSans",Font.PLAIN,12));
              itemInfo.add(labelDeadline);
              String myText3 = "<HTML><b><u>Price</b></u> : ";
              label4 = new JLabel(myText3);
              itemInfo.add(label4);
              labelPrice = new JLabel("Click Status To View Price ");
              labelPrice.setFont (new Font("ComicSans",Font.PLAIN,12));
              itemInfo.add(labelPrice);
              bidStatus = new JLabel("");
              itemInfo.add(bidStatus);
              add(itemInfo, BorderLayout.CENTER);
              biddingText = new JPanel(new FlowLayout());
              bid = new JTextField("Enter Bid Here",10);
              bid.addActionListener(this);
              biddingText.add(bid);
              add(biddingText, BorderLayout.SOUTH);
              bidButton = new JButton("Place Bid");
              biddingText.add(bidButton);
              bidButton.addActionListener(this);
              statusButton = new JButton("Status");
              biddingText.add(statusButton);
              statusButton.addActionListener(this);
              noOfBiddersButton = new JButton("No. Of Bidders");
              biddingText.add(noOfBiddersButton);
              noOfBiddersButton.addActionListener(this);
              quitButton = new JButton("Quit");
              biddingText.add(quitButton);
              quitButton.addActionListener(this);
              add(biddingText, BorderLayout.SOUTH);
              link = new Socket(host, PORT);
              networkInput = new Scanner(link.getInputStream());
              output = new PrintWriter(link.getOutputStream(),true);
              keyboard = new Scanner(System.in);
              getItems();
              System.out.println("haha");
         public void getItems()
              for (int i = 0; i <2 ; i++)
                   desc[i] = networkInput.nextLine();
                   code[i] = networkInput.nextLine();
                   deadline[i] = networkInput.nextLine();
                   itemSelection.addItem(code);
         public void actionPerformed(ActionEvent e)
              if (e.getSource()== itemSelection)
              labelDescrip.setText(desc[itemSelection.getSelectedIndex()]);
              labelCode.setText(code[itemSelection.getSelectedIndex()]);
              labelDeadline.setText(deadline[itemSelection.getSelectedIndex()]);
              }else if ((e.getSource()== bidButton) || (e.getSource() == bid))
                   output.println(labelCode.getText() + " " + bid.getText());
                   JOptionPane.showMessageDialog(null,networkInput.nextLine());
                   //bidStatus.setText(networkInput.nextLine());
                   //System.out.println(bidStatus.getText());
              }else if (e.getSource()== statusButton)
                   output.println(labelCode.getText()+ "Status");
                   labelPrice.setText(networkInput.nextLine());
                   if (labelPrice.getText().equals("-1"))
                        labelPrice.setText("Bidding Time Is Up On This Item");
                   else
                        labelPrice.setVisible(true);
              }else if (e.getSource()== noOfBiddersButton)
                   output.println("number of bidders");
                   JOptionPane.showMessageDialog(null,"Number Of Bidders Online\n "+ networkInput.nextLine()
                                                      ,"Information", JOptionPane.INFORMATION_MESSAGE);
              }else if (e.getSource() == quitButton)
                   try
                        JOptionPane.showMessageDialog(this,"Closing down connection...",
                                  "Warning", JOptionPane.WARNING_MESSAGE);
                        System.out.println("*Connection Closed*");
                        link.close();
                        System.exit(0);
                   catch(IOException ioex)
                        System.out.println("***Disconnection problem!***");
                        System.exit(1);

  • Need help on with simple email program

    i have been set a task to create a simple email program that has the variables of the sender the recipient the subject the content and a date object representing when the email was sent (this is just to be set to the current system date)
    It also needs to include a constructor with four String arguments, i.e the sender, receiver, subject and content. The constructor has to initialise the date of the email then transfer the values of the input parameters to the relevant attributes. If any values of the strings aren'nt given, the string �Unknown� should be set as the value.
    I was given a java file to test the one i am to create, but some of the values are not given, if anyone could be of anyhelp or just point me in the right direction then i would be very greatfull, ive posted the code for the test file i have been given below, thanks.
    public class SimpleEmailTest {
         public static void main( String[] args ) {
              SimpleEmail email;     // email object to test.
              String whoFrom;          // sender
              String whoTo;          // recipient
              String subject;          // subject matter
              String content;          // text content of email
              static final String notKnown = "Unknown";
              email = new SimpleEmail
    (notKnown, notKnown, notKnown, notKnown);
              System.out.println( "SimpleEmail: " +
    "\n    From: " + email.getSender() +
    "\n      To: " + email.getRecipient() +
    "\n Subject: " + email.getSubject() +
    "\n    Date: " + 
    email.getDate().toString() +
    "\n Message: \n" + email.getContent() + "\n";
              email.setSender( "Jimmy Testsender");
              email.setRecipient( "Sheena Receiver");
              email.setSubject( "How are you today?");
              email.setContent( "I just wrote an email class!");
              System.out.println( "SimpleEmail: " +
    "\n    From: " + email.getSender() +
    "\n      To: " + email.getRecipient() +
    "\n Subject: " + email.getSubject() +
    "\n    Date: " + 
    email.getDate().toString() +
    "\n Message: \n" + email.getContent() + "\n";
         }

    Start by writing a class named SimpleEmail, implement a constructor with four arguments in it, and the methods that the test code calls, such as the get...() and set...() methods. The class probably needs four member variables too.
    public class SimpleEmail {
        // ... add member variables here
        // constructor
        public SimpleEmail(String whoFrom, String whoTo, String subject, String content) {
            // ... add code to the constructor here
        // ... add get...() and set...() methods here
    }

  • Problem with simple drawing program - please help!

    Hi,
    I've only just started using Java and would appreciate some help with a drawing tool application I'm currently trying to write.
    The problem is that when the user clicks on a button at the bottom of the frame, they are then supposed to be able to produce a square or circle by simply clicking on the canvas.
    Unfortunately, this is not currently happening.
    Please help!
    The code for both classes is as follows:
    1. DrawToolFrame Class:
    import java.awt.*;
    import java.awt.event.*;
    public class DrawToolFrame extends Frame
    implements WindowListener
    DrawToolCanvas myCanvas;
    public DrawToolFrame()
    setTitle("Draw Tool Frame");
    addWindowListener(this);
    Button square, circle;
    Panel myPanel = new Panel();
    square = new Button("square"); square.setActionCommand("square");
    circle = new Button("circle"); circle.setActionCommand("circle");
    myPanel.add(square); myPanel.add(circle);
    add("South", myPanel);
    DrawToolCanvas myCanvas = new DrawToolCanvas();
    add("Center", myCanvas);
    square.addMouseListener(myCanvas);
    circle.addMouseListener(myCanvas);
    public void windowClosing(WindowEvent event) { System.exit(0); }
    public void windowOpened(WindowEvent event) {}
    public void windowIconified(WindowEvent event) {}
    public void windowDeiconified(WindowEvent event) {}
    public void windowClosed(WindowEvent event) {}
    public void windowActivated(WindowEvent event) {}
    public void windowDeactivated(WindowEvent event) {}
    2. DrawToolCanvas Class:
    import java.awt.*;
    import java.awt.event.*;
    public class DrawToolCanvas
    extends Canvas
    implements MouseListener, ActionListener {
    String drawType="square";
    Point lastClickPoint=null;
    public void drawComponent(Graphics g) {
    if (lastClickPoint==null) {
    g.drawString("Click canvas first",20,20);
    } else {
    if (drawType.equals("square")) {
    square(g);
    else if (drawType.equals("circle")) {
    circle(g);
    public void actionPerformed(ActionEvent event) {
    if (event.getActionCommand().equals("square"))
    drawType="square";
    else if (event.getActionCommand().equals("circle"))
    drawType="circle";
    repaint();
    public void mouseReleased(MouseEvent e) {
    lastClickPoint=e.getPoint();
    public void square(Graphics g) {
    g.setColor(Color.red);
    g.fillRect(lastClickPoint.x, lastClickPoint.y, 40, 40);
    g.setColor(Color.black);
    public void circle(Graphics g) {
    g.setColor(Color.blue);
    g.fillOval(lastClickPoint.x, lastClickPoint.y, 40, 40);
    g.setColor(Color.black);
    public void mouseEntered(MouseEvent e) {}
    public void mouseExited(MouseEvent e) {}
    public void mousePressed(MouseEvent e) {}
    public void mouseClicked(MouseEvent e) {}
    Any help would be appreciated!

    Some of the problems:
    1) nothing calls drawComponent(Graphics g)
    2) Paint(Graphics g) has not been overriden
    3) myCanvas is declared twice: once as an instance variable to DrawToolFrame, and once local its constructor. Harmless but distracting.

  • Help with simple programming

    Hello everyone.
    First time posting, i hope someone would be able to help me out. There are 5 classes that i have to do, but i only need help with one of them. I've been stuck on this one pretty long and can't continue without it.
    Instructions:
    •     Has boolean data member face, either HEADS or TAILS.
    •     Has a Random data member flipper which is instantiated in the constructor.
    •     Class constructor has no parameters and randomly chooses the result HEADS or TAILS. (See method flip())
    •     Method getFace() returns the face showing on the coin.
    •     void method flip() randomly selects HEADS or TAILS.
    package coinflip;
    import java.util.Random;
    * @author Blank
    public class Coin {
        boolean face = false;
        int flip_coin;
        Random flipper = new Random();
        int getFace() {
            return flip_coin;
          Coin() {
            if (flip_coin == 0) {
                face = true;
            } else {
                face = false;
        public void flip() {
            flip_coin = flipper.nextInt(2);
    }i really don't know why the random isn't working. I hope someone would be able to find my errors and instruct me on how to fix them. I would be able to continue the rest of the classes as soon as i got this figured out.
    Oh and can someone teach me how to import this class into a main one? So i can test it out. This is what i have for it.public class Main {
         * @param args the command line arguments
        public static void main(String[] args) {
         Coin flipCoin = new Coin();
         for(int i=0;i<6;i++){
         System.out.println(flipCoin.getFace());
    }Many Thanks!
    Edited by: Java_what on Feb 16, 2009 2:26 PM

    Constructors are only executed once. What im confused about is:
    • Class constructor has no parameters and randomly chooses the result HEADS or TAILS. (See method flip())
    I thought i would flip() into the constructor. Mind helping me out on the whole class because it seems i am clueless about this whole class.
    Edit:
    public class Coin {
        boolean face = false;
        int flip_coin;
        Random flipper = new Random();
        int getFace() {
            flip();
            return flip_coin;
        Coin() {
           //flip();
        public void flip() {
            flip_coin = flipper.nextInt(2);
    }K i reread what you wrote about the constructor and method. So i placed flip() method in getFace(); because its being called in the main(it gives me random numbers). The problem now is following the directions.
    I just dont understand this description. • Class constructor has no parameters and randomly chooses the result HEADS or TAILS. (See method flip())
    What do you think it means.
    Edited by: Java_what on Feb 16, 2009 4:14 PM

  • Help with parallel arrays of different data types

    Hello all, I am having an issue with parallel arrays. My program requires me to read information from a text file into 4 parallel arrays (2 String and 2 double). My text file needs to look something like this:
    John Johnson
    0000004738294961
    502.67
    1000.000
    Jane Smith
    0000005296847913
    284.51
    1000.000
    ...and so on
    Where the first thing is the name (obviously), an account number, the balance in the account, and the credit limit. I just cant figure out how to read everything into the arrays. We havent learned anything too heavy, and this seems a little too advanced for my class, but I guess we will manage. Any help will be appreciated. Thanks guys.
    Casey

    Man this is a dumb homework assignment. The requirements scream out for a class along the lines of
    public class Account{
      private String name, number;
      private double balance,creditlimit;
       // more code here
    }and then to use a List of Account objects.
    Anyway what's your actual problem. There's nothing very hard about it. A loop. So....
    You should consider posting (formatted) code showing what you have done and where exactly you are stuck.

  • Help with a java program

    Hello. I'm posting in these forums because I really don't know where else to go. I have been trying for the past several days to figure out how to go about writing my program but to no avail. The project requires reading many lines each containing several different elements from a datafile named "DATA". A few examples of some lines from that file:
    Department number/Number of units received/Date on which the shipment arrived/Expiration date/Name of Object
    0 78 02/03/2001 02/12/2001 apples
    0 26 06/03/2001 06/10/2001 lemons
    3 62 03/06/2001 03/14/2001 hamburger
    What we have to do with this data is read all of it from the file, separate all the different elements, and based on input from the user, sort everything and print it out to the screen. If the user enters 03, the program will show everything that arrived and expired within the month of March, sorted by date.
    It is a pretty basic program, but my problem is that I have no idea how to go about reading in this data, putting it into a vector (probably the easiest method) or separating the different elements. I've gone to websites and looked through my textbooks but they didn't help much. If anyone has any resources that could help for writing such a program, or if anyone could offer help in writing the program, I would really appreciate it. I can also show what I've managed to write so far, or more details on how the program should work. Thanks in advance.
    Matt

    since im not a pro like some of the guys on here :),
    and believe me thiers people here, who could write your whole app in a hour.
    anyways my advice , would be to do a search on the forums for useing.bufferReader()
    i think you would need to read the file in with bufferreader then split up each line useing the stringTokenizer and then use some algorithm to compare
    the values and split them up into your vector arrays as needed.
    thier is also fileinputStream i think you can use that too.

  • Need Help With D&D Program

    Hi, I'm not sure if I'm allowed to post questions on this forum but I can't find anywhere to talk to helpful people about programming.
    I'm making a dnd interface for JComponents. So far I've made a simple program that has a Component that can be lifted from a container and braught to the glass pane then later moved to anywhere on the screen and dropped into the container below it. Here's where my problems come:
    1) Rite now my 'Movable Component' is a JPanel which is just colored in. I want to either take a Graphic2d from a JComponent/Component and draw it on the JPanel or change the JPanel to the component I want to paint and disable the component.
    The problem with getting the Graphics2d is that if the component isn't on the screen it doesn't make a graphic object. I tried messing with the ui delicate and overriding parental methods for paintComponent, repaint, and that repaintChildren(forget name) but I haven't had luck getting a good graphics object. I was thinking of, at the beginning of running the program, putting 1 of each component onto the screen for a second then removing it but I'd rather not. I'd also like to change the graphics dynamicly if someone stretches the component there dropping and what not.
    The problem with disabling is that it changes some of the visual features of Components. I want to be able to update the Component myself to change how it looks and I don't want disabling to gray out components.
    I mainly just dont want the components to do any of there normal fuctions. This is for a page builder, by the way.
    Another problem I'm having is that mouseMotionListener is allowing me to select 2 components that are on top of one another when there edges are near each other. I don't know if theres a fix to this other than changing the Java Class.
    My next problem is a drop layout manager, but I'm doing pretty good with that rite now. It'll problem just move components out of the way of the falling component.
    One last thing I need help with is that I don't want the object that's being carried to go across the menu bar and certain areas. When I'm having the object being carried I have it braught up to the glass pane which allows it to move anywhere. Does anyone have any idea how I could prevent the component from being over the menu bars and other objects? I might have to make 1 panel is the movable area that can then be broken down into the 'component bank', 'building page' and whatever else I'm gonna need.
    This is all just test code to get together for when I make the real program but I need to make sure it'll be possible without a lot of hacking of code.
    Sorry for the length. Thanks for any help you can give.

    The trick to making viewable components that have no behaviour, is to render them onto an image of some sort (eg a BufferedImage). You can then display the Image on a JLabel that can be dragged around the desktop.
    Here is a piece of code that does the component rendering for you. This particular example uses a fixed component size, but you can modify that as you choose of course...public class JComponentImage
         private static GraphicsConfiguration gConfig;
         private static Dimension compSize = new Dimension(80, 22);
         private static Image image = null;
         public static Image getImage(Class objectClass)
              if (gConfig == null)
                   GraphicsEnvironment gEnv = GraphicsEnvironment.getLocalGraphicsEnvironment();
                   GraphicsDevice gDevice = gEnv.getDefaultScreenDevice();
                   gConfig = gDevice.getDefaultConfiguration();
              image = gConfig.createCompatibleImage(compSize.width, compSize.height);
              JComponent jc = (JComponent) ObjectFactory.instantiate(objectClass);
              jc.setSize(compSize);
              Graphics g = image.getGraphics();
              g.setColor(Color.LIGHT_GRAY);
              g.fillRect(0, 0, compSize.width, compSize.height);
              g.setColor(Color.BLACK);
              jc.paint(g);
              return image;
    }And here is the class that makes the dragable JLabel using the class above...public class Dragable extends JLabel
         private static DragSource dragSource = DragSource.getDefaultDragSource();
         private static DragGestureListener dgl = new DragMoveGestureListener();
         private static TransferHandler th = new ObjectTransferHandler();
         private Class compClass;
         private Image image;
         Dragable(Class compClass)
              this.compClass = compClass;
              image = JComponentImage.getImage(compClass);
              setIcon(new ImageIcon(image));
              setTransferHandler(th);
              dragSource.createDefaultDragGestureRecognizer(this,
                                                          DnDConstants.ACTION_COPY,
                                                          dgl);
         public Class getCompClass()
              return compClass;
    }Oh and here is ObjectFactory which simply instantiates Objects of a given class and sets their text to their classname (very crudely)...public class ObjectFactory
         public static Object instantiate(Class objectClass)
              Object o = null;
              try
                   o = objectClass.newInstance();
              catch (Exception e)
                   System.out.println("ObjectFactory#instantiate: " + e);
              String name = objectClass.getName();
              int lastDot = name.lastIndexOf('.');
              name = name.substring(lastDot + 1);
              if (o instanceof JLabel)
                   ((JLabel)o).setText(name);
              if (o instanceof JButton)
                   ((JButton)o).setText(name);
              if (o instanceof JTextComponent)
                   ((JTextComponent)o).setText(name);
              return o;
    }Two more classes required by this codepublic class ObjectTransferHandler extends TransferHandler {
         private static DataFlavor df;
          * Constructor for ObjectTransferHandler.
         public ObjectTransferHandler() {
              super();
              try {
                   df = new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType);
              } catch (ClassNotFoundException e) {
                   Debug.trace(e.toString());
         public Transferable createTransferable(JComponent jC) {
              Transferable t = null;
              try {
                   t = new ObjectTransferable(((Dragable) jC).getCompClass());
              } catch (Exception e) {
                   Debug.trace(e.toString());
              return t;
         public int getSourceActions(JComponent c) {
              return DnDConstants.ACTION_MOVE;
         public boolean canImport(JComponent comp, DataFlavor[] flavors) {
              if (!(comp instanceof Dragable) && flavors[0].equals(df))
                   return true;
              return false;
         public boolean importData(JComponent comp, Transferable t) {
              JComponent c = null;
              try {
                   c = (JComponent) t.getTransferData(df);
              } catch (Exception e) {
                   Debug.trace(e.toString());
              comp.add(c);
              comp.validate();
              return true;
    public class ObjectTransferable implements Transferable {
         private static DataFlavor df = null;
         private Class objectClass;
         ObjectTransferable(Class objectClass) {
              try {
                   df = new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType);
              } catch (ClassNotFoundException e) {
                   System.out.println("ObjectTransferable: " + e);
              this.objectClass = objectClass;
          * @see java.awt.datatransfer.Transferable#getTransferDataFlavors()
         public DataFlavor[] getTransferDataFlavors() {
              return new DataFlavor[] { df };
          * @see java.awt.datatransfer.Transferable#isDataFlavorSupported(DataFlavor)
         public boolean isDataFlavorSupported(DataFlavor testDF) {
              return testDF.equals(df);
          * @see java.awt.datatransfer.Transferable#getTransferData(DataFlavor)
         public Object getTransferData(DataFlavor arg0)
              throws UnsupportedFlavorException, IOException {
              return ObjectFactory.instantiate(objectClass);
    }And of course the test class:public class DragAndDropTest extends JFrame
         JPanel leftPanel = new JPanel();
         JPanel rightPanel = new JPanel();
         Container contentPane = getContentPane();
         Dragable dragableJLabel;
         Dragable dragableJButton;
         Dragable dragableJTextField;
         Dragable dragableJTextArea;
          * Constructor DragAndDropTest.
          * @param title
         public DragAndDropTest(String title)
              super(title);
              dragableJLabel = new Dragable(JLabel.class);
              dragableJButton = new Dragable(JButton.class);
              dragableJTextField = new Dragable(JTextField.class);
              dragableJTextArea = new Dragable(JTextArea.class);
              leftPanel.setBorder(new EtchedBorder());
              BoxLayout boxLay = new BoxLayout(leftPanel, BoxLayout.Y_AXIS);
              leftPanel.setLayout(boxLay);
              leftPanel.add(dragableJLabel);
              leftPanel.add(dragableJButton);
              leftPanel.add(dragableJTextField);
              leftPanel.add(dragableJTextArea);
              rightPanel.setPreferredSize(new Dimension(500,500));
              rightPanel.setBorder(new EtchedBorder());
              rightPanel.setTransferHandler(new ObjectTransferHandler());
              contentPane.setLayout(new BorderLayout());
              contentPane.add(leftPanel, "West");
              contentPane.add(rightPanel, "Center");
         public static void main(String[] args)
              JFrame frame = new DragAndDropTest("Drag and Drop Test");
              frame.pack();
              frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              frame.setVisible(true);
    }I wrote this code some time ago, so it won't be perfect but hopefully will give you some good ideas.
    Regards,
    Tim

  • I need help with 2 arrays

    I need help with this portion of my program, it's supposed to loop through the array and pull out the highest inputted score, currently it's only outputting what is in studentScoreTF[0].      
    private class HighScoreButtonHandler implements ActionListener
               public void actionPerformed(ActionEvent e)
              double highScore = 0;
              int endScore = 0;
              double finalScore = 0;
              String tempHigh;
              String tempScore;
              for(int score = 0; score < studentScoreTF.length; score++)
              tempHigh = studentScoreTF[score].getText();
                    tempScore = studentScoreTF[endScore].getText();
              if(tempHigh.length() <  tempScore.length())
                   highScore++;
                   finalScore = Double.parseDouble(tempScore);
             JOptionPane.showMessageDialog(null, "Highest Class Score is: " + finalScore);This is another part of the program, it's supposed to loop through the student names array and pull out the the names of the students with the highest score, again it's only outputting what's in studentName[0].
         private class StudentsButtonHandler implements ActionListener
               public void actionPerformed(ActionEvent e)
              int a = 0;
              int b = 0;
              int c = 0;
              double fini = 0;
              String name;
              String score;
              String finale;
              String finalName = new String();
              name = studentNameTF[a].getText();
              score = studentScoreTF.getText();
              finale = studentScoreTF[c].getText();
              if(score.length() < finale.length())
                   fini++;     
                   name = finalName + finale;
         JOptionPane.showMessageDialog(null, "Student(s) with the highest score: " + name);
                   } Any help would be appreciated, this is getting frustrating and I'm starting to get a headache from it, lol.
    Edited by: SammyP on Oct 29, 2009 4:18 PM
    Edited by: SammyP on Oct 29, 2009 4:19 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    Heres a working example:
    class Compare {
        public int getHighest(int[] set) {
            int high = set[0];
            for(int i = 0; i < set.length; i++) {
                if(set[i] > high) {
                    high = set;
    return high;

Maybe you are looking for