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

Similar Messages

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

  • Need Help with a JAVA programming assignment

    How do I write a JAVA program that could be used as the start of an MS-DOS/Windows simulation of the IEEE 802.3 protocol? I am to only code the parts necessary to build the 802.3 frame. For the initial implementation, the Checksum function need not be a CRC function, and the Destination and Source addresses wil be in input, stored, and output, and in dotted-decimal format.
    I need:
    1. A record to describe the frame, with each field being a (byte-) string of the required size, except that the Data field is of variable size. Although the "Source address" and "Destination address" would be 6 bytes for a real implementation, for this first implementation you can either assume they'll be text strings in the usual "dotted decimal" form (e.g. "14.04.05.18.01.25" as a typical example--from Tanenbaum, p. 429), or 6 hex digits.
    2. Suitable constant declarations for values such as the standard "Preamble" and "Start of Frame" values.
    3. Suitable functions to Get the three variable values "Destination address", "Source address", and "Data" from the standard input device.
    4. A suitable function to display each of the fields of a given frame in a format such as:
    Preamble: ...
    StartofFrame: ...
    Destination: ...
    etc.
    5. A suitable function to generate a "Pad" field if necessary.
    6. A "dummy" Checksum-generating function which just takes the first 32 bits (4 bytes) of the Data (or Data+Pad, if necessary) rather than an actual CRC algorithm.
    I have no experience with Java. Can you help me or start me in the right direction?
    Thanks...........TK

    If you have no experience with Java, then it seems to me your first step should be to start learning the language. But it's difficult to advise how, since we don't know anything about your background. There are many good books available on Java, some are for beginners and some are for advanced programmers, so I'd suggest you go somewhere that has a large selection and start looking for something that doesn't seem completely over your head.

  • Need Help with a Java program

    Hey
    I am doing a bachelor of Multimedia and for some reason I was forced to do Programming 1 which is just Java programing.I have been doing pretty well but we have the final exam coming up on Thursday and they told us to learn how to do this question but I have no idea how to do it, could someone please help me?
    Write a program that reads a file containing a list of students' student numbers and names, and then writes out another file in which the students have been formed into project groups.
    Sample input file:
    96439530 Naranek, Kosh
    08532109 Ivanova, Susan
    87642078 Sheridan, John
    44327889 Varner, Dell
    98100023 Kotto, Vir
    66345689 Sinclair, Jeffrey
    77421009 Garibaldi, Michael
    88775544 Winters, Talia
    54321098 Alexander, Lyta
    12345098 Mollari, Londo
    03465499 Takashima, Laurel
    88765432 Kyle, Benjamin
    08876500 Keffer, Warren
    07687878 Cole, Marcus
    For the project course: no group should have more than 5 members; and it is desireable that all groups have as close to 5 members as possible; and that students be allocated to groups alphabetically by family name, as in this sample output file:
    Group 1:
    Lyta Alexander (54321098)
    Susan Ivanova (08532109)
    Benjamin Kyle (88765432)
    John Sheridan (87642078)
    Dell Varner (44327889)
    Group 2:
    Marcus Cole (07687878)
    Warren Keffer (08876500)
    Londo Mollari (12345098)
    Jeffrey Sinclair (66345689)
    Talia Winters (88775544)
    Group 3:
    Michael Garibaldi (77421009)
    Vir Kotto (98100023)
    Kosh Naranek (96439530)
    Laurel Takashima (03465499)
    Students' names are first sorted (Alexander, Cole, Garibaldi, Ivanova, ...), then allocated to the tutes in rotation (Alexander to 1, Cole to 2, Garibaldi to 3, Ivanova to 1, ...).
    Note also that the student's details are written in a different format from the input. You may make the (usually wrong!) assumption that each student has a simple one-word family name and one other name.

    I'm sorry too annoy you again but I don't know how to implement what you told me. Here is my current code:
    import java.io.*;
    import java.util.*;
    class DetailSortTest {
         public void run() {
              try {
                   BufferedReader in = new
                   BufferedReader(new FileReader ("Data.txt"));
                   String line = in.readLine();
                   String[] names = new String [10];
                   int i = 0;
                   PrintWriter FileOut = new
                   PrintWriter(new FileWriter ("Data 2.txt"));
                   processFilesTest(in, FileOut);
                   in.close();
                   FileOut.close();
              } catch (FileNotFoundException f) {
                   System.out.println("Could Not Open The File");
              } catch (IOException i){
                   System.out.println(i.getMessage());
         public void processFilesTest (BufferedReader in, PrintWriter FileOut)
         throws IOException {
              String data[] = new String[100];
              List dList = new ArrayList();
              String NLine = in.readLine();
              FileOut.println(NLine);
         public static void main(String[] args) {
              DetailSortTest anObject = new
              DetailSortTest();
              anObject.run();
    How would I do it I tried:
    NLine.split(data[2]+""+data[1]+""+data[0]);
    But all that displays is null, null, null
    I know I am probably so stupid but I really appreciate the help

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

  • Help with some Java Programs

    Hi all ..
    i am a new in Java and i need some help with my School Project ,,,
    Will you help me ??
    regards,
    Toota

    People here will answer questions and comment on your code, but don't ecpect them to debug your source nor do your homework for you.

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

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

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

  • Need help with basic Java programming

    I'm having a little bit of trouble with my code. For the sake of argument, I've removed the code I'm having trouble with, because I know it was inaccurate. I'm trying to create a loop so that this program will keep going through and through until the user enters an invalid variable. I thought the default after the case statements was supposed to make the system exit and output my message. Those two problems, the loop and the default, are what I'm really having problems with. My code is posted below.
    import javax.swing.JOptionPane;
    import java.util.Locale;
    import java.text.NumberFormat;
    public class Retail
    public static void main(String args[])
    String firstNum;
    String secondNum;
    String result;
    int prodNum;      //first number to input
    double quantity; //second number to input
    double total = 0.0;     //total of Prod * Quantity Sold for all items
    // To use American Dollar
    NumberFormat moneyFormat = NumberFormat.getCurrencyInstance( Locale.US );
    // first number entered as string
    firstNum = JOptionPane.showInputDialog( "Enter product number 1-5" );
    // second number entered as string
    secondNum = JOptionPane.showInputDialog( " Enter quantity of items sold" );
    // convert values to type double or int from type string
    prodNum = Integer.parseInt( firstNum );
    quantity = Double.parseDouble( secondNum);
    result="";
    if ( prodNum >=1 && prodNum <=5 ) {
    switch (prodNum)
    case 1: // 1st product
    total = 2.98 * quantity;
    break;
    case 2: // 2nd product
    total = 4.50 * quantity;
    break;
    case 3: // 3rd product
    total = 9.98 * quantity;
    break;
    case 4: //4th product
    total = 4.49 * quantity;
    break;
    case 5:
    total = 6.87 * quantity;
    break;
    default: JOptionPane.showMessageDialog( null, "Wrong product number entered" );
    JOptionPane.showMessageDialog( null, moneyFormat.format(total), "Total Price of Items Purchased", JOptionPane.INFORMATION_MESSAGE );
    System.exit(0);
    ***I know I need to put something in the user input message to state that any value other than 1-5 entered will cause the program to skip to the output, I'll put that in later.***

    When you post code, please use [code] and [/code] tags as described in Formatting Help on the message entry page. It makes it much easier to read and prevents accidental markup from array indices like [i].

  • Need Help with a Java programming exercise.

    I have to Write a program that reads two times in military format (0900, 1730) and prints the number of hours and minutes between two times. Supply your own test program. Here are two sample runs. User inputs are the numbers.
    Please enter the first time: 0900
    Please enter the second time: 1730
    8 hours 30 minutes
    Please enter the first time: 1730
    Please enter the second time: 0900
    15 hours 30 minutes
    Test Program I can write up myself. But the entire constructor I have no idea how to start. This is basic Java Coding. no C++ no importing anything.
    So far this is what I got and I'm sure it's wrong:
    public class TimeInterval
    private double hours;
    private double minutes;
    public TimeInterval(double Time1, double Time2)
    hours =
    minutes =
    }

    tad2382 wrote:
    Jverd,
    I'm guessing that in your early days on this forum you must have spent a lot of time explaining constructors, object creation, etc. Now, after some 40K posts to the forum, you figure newbies should just go and read the documentation. Is that what a lot of veteran posters feel?Perhaps the OP is not aware of the fact the Sun has a good deal of high quality study material published on their website. What's wrong with posting it in a thread? Why should one copy the same thing over and over again? If after reading that tutorial, the OP still has some questions about it, s/he is free to post a follow up question. I am sure that many of the regulars here are more than happy to answer them.
    Also note that the OP's problem description is rather vague. A "I don't know where to start" is IMO best answered by a link to a comprehensive tutorial or a beginners book.
    Being one of the (relatively) novice posters on the forum, I still feel the need to customize posts,Well, by all means: do so.
    trying to see things from the poster's side. Maybe after a few thousand posts, I'll just keep throwing the same documentation at newbies, instead of detailed customized responses, heh.IMO, that's a load of cr@p.

  • Help!  Simple Java Program.

    Here is the problem: Write a program that creates a loan amortization table. The user of the program will supply values for Initial Loan Principal, Annual Percentage Rate and Monthly Payment. The program should print out the appropriate amortization table including the number of Monthly Payments and the Total Interest paid for the life of the loan. The program should allow multiple
    runs (up to 4 different versions) of the table process and should allow the
    user to compare runs in a tabular format.
    This is what I have so far and should work one I completely debug it. I am really new to Java, and I thinks it is somthing to do with the Array. I recently switched from C++ to Java, so I don't think I have the syntax down correctly. Thanks.
    import javax.swing.JOptionPane;
    public class Program_01
         public static void main(String [] args)
              int Runs;
              do{
                        String Run_Question = JOptionPane.showInputDialog(null, "How many times,would you like to run" + 
                        " the program? (Up to four runs only!)", "Run Question", JOptionPane.QUESTION_MESSAGE);
                         Runs = Integer.parseInt(Run_Question);
                        if( Runs < 0 || Runs > 4)
                             JOptionPane.showMessageDialog(null, "The number is not valid, try again!", "Error",
                             JOptionPane.INFORMATION_MESSAGE);
                   }while(Runs < 0 || Runs > 4);
                   Questions(Runs);
         public static void Questions(int Runs)
              for(int index = 0;index < Runs;index ++)
                   String Loan_Principle_String = JOptionPane.showInputDialog(null, "What is the Loan Principle?", "Loan Amount",
                                                         JOptionPane.QUESTION_MESSAGE);     
                   String Percentage_Rate_String = JOptionPane.showInputDialog(null, "What is the Annual Percentage Rate?",
                                                           "Interest Rate", JOptionPane.QUESTION_MESSAGE);
                   String Monthly_Payment_String = JOptionPane.showInputDialog(null, "What is the Monthly Payment", "Payment",
                                                           JOptionPane.QUESTION_MESSAGE);
                   double Loan_Principle = Double.parseDouble(Loan_Principle_String);
                   double Percentage_Rate = Double.parseDouble(Percentage_Rate_String);
                   double Monthly_Payment = Double.parseDouble(Monthly_Payment_String);
                   Calculate(Loan_Principle, Percentage_Rate, Monthly_Payment);
         public static void Calculate (double Loan, double Percentage, double Monthly)
              double[] Principle = new double[]{0,0};
              double[] Interest = new double[]{0,0};
              double[] Remain = new double[]{0,0};
              double Monthly_Percent = Percentage/12;
              double MPR = ((int)((Monthly_Percent + .005) * 100.) / 100.);
              boolean Over = true;          
              double Borrowed = Loan;          
              int Month = 0;
              for (int index = 0; Over != false; index++)
                   double Rate = MPR * Loan;
                   double decimalRate = ((int)((Rate + .005) * 100.) / 100.);
                   Interest[index] = decimalRate;
                   double Prince = Monthly - decimalRate;
                   double decimalPrince = ((int)((Prince + .005) * 100.) / 100.);
                   Principle[index]= decimalPrince;
                   double Rmn = Borrowed - decimalPrince;
                   Borrowed = Rmn;
                   double decimalRmn = ((int)((Rmn + .005) * 100.) / 100.);
                   Remain[index] = decimalRmn;
                   if(Monthly > Remain[index] && Remain[index] > 0)
                        Monthly = Remain[index];
                        Over = false;
                   Month += 1;
              System.out.println("I am here!" + Month);
              System.out.println("Payment #" + " " + "Principle" + " " + "Payment" + " " + "APR" + " " + "MPR" +
               " " + "Interest Payment" + " " + "Principle Payment");
              System.out.println("------------------------------------------------------------------------");
              for(int index = 0; index < Month; index++)
                   System.out.println((index + 1) + "\t" + Remain[index] + "\t" + Percentage + "\t" + MPR + "\t" + Interest[index]
                    + "\t" + Principle[index]);
    }

    Okay, here is my updated code. I am having trouble outputting my formate to align with each category.
    import javax.swing.JOptionPane;
    import java.text.DecimalFormat;
    public class Program_01
         public static void main(String [] args)
              int Runs;
              do
                   String Run_Question = JOptionPane.showInputDialog(null, "How many times would you like to run" + 
                   " the program? (Up to four runs only!)", "Run Question", JOptionPane.QUESTION_MESSAGE);
                    Runs = Integer.parseInt(Run_Question);
                   if( Runs < 0 || Runs > 4)
                        JOptionPane.showMessageDialog(null, "The number is not valid, try again!", "Error",
                        JOptionPane.INFORMATION_MESSAGE);
              }while(Runs < 0 || Runs > 4);
                   Questions(Runs);
         public static void Questions(int Runs)
              for(int index = 0;index < Runs;index ++)
                   String Loan_Principle_String = JOptionPane.showInputDialog(null, "What is the Loan Principle?", "Loan Amount",
                                                         JOptionPane.QUESTION_MESSAGE);     
                   String Percentage_Rate_String = JOptionPane.showInputDialog(null, "What is the Annual Percentage Rate?",
                                                           "Interest Rate", JOptionPane.QUESTION_MESSAGE);
                   String Monthly_Payment_String = JOptionPane.showInputDialog(null, "What is the Monthly Payment", "Payment",
                                                           JOptionPane.QUESTION_MESSAGE);
                   double Loan_Principle = Double.parseDouble(Loan_Principle_String);
                   double Percentage_Rate = Double.parseDouble(Percentage_Rate_String);
                   double Monthly_Payment = Double.parseDouble(Monthly_Payment_String);
                   Calculate(Loan_Principle, Percentage_Rate, Monthly_Payment);     
         public static void Calculate (double Loan, double Percentage, double Monthly)
              double[] Principle = new double[100];
              double[] Interest = new double[100];
              double[] Remain = new double[100];
              double[] Payment = new double[100];
              DecimalFormat Decimal = new DecimalFormat(".00");
              double Total_Interest = 0;
              double T_Interest;          
              double Monthly_Percent = (Percentage/12)/100;
              double MPR = Monthly_Percent;
              boolean Over = true;          
              double Borrowed = Loan;
              double Deposit = Monthly;          
              int Month = 0;
              for (int index = 0; Over = true; index++)
                   double Rate = MPR * Borrowed;
                   double decimalRate = round(Rate,2);
                   Interest[index] = decimalRate;
                   Remain[index] = Borrowed;
                   Month += 1;     
                   if(Monthly > Remain[index ] && Remain[index ] > 0)
                        for(int count = 0; count <= Month; count++)
                             Total_Interest += Interest[count];     
                        T_Interest = round(Total_Interest,2);
                        Payment[index] = T_Interest;
                        Deposit = T_Interest;     
                   else
                        Payment[index] = Deposit;     
                   double Prince = Deposit - decimalRate;
                   double decimalPrince = round(Prince,3);
                   Principle[index]= decimalPrince;
                   System.out.println("I am here!" + decimalPrince);
                   double Rmn = Borrowed - decimalPrince;
                   double decimalRmn = round(Rmn,2);
                   Borrowed = decimalRmn;
                   if(Monthly > Remain[index ] && Remain[index ] > 0)
                        Over = false;
                        break;
              System.out.println("Payment #" + " " + "Principle" + " " + "Payment" + " " + "Percentage" + " " + "MPR" +
               " " + "Interest Payment" + " " + "Principle Payment");
              System.out.println("----------------------------------------------------------------------------");
              for(int index = 0; index < Month; index++)
                   System.out.println("   " + (index + 1) + "\t   " + Decimal.format(Remain[index]) + "   " +
                   Decimal.format(Payment[index]) + "   " + Decimal.format(Percentage) + "     " + MPR +
                   "\t" + Decimal.format(Interest[index]) + "\t\t" + Decimal.format(Principle[index]));     
              T_Interest = ((int)((Total_Interest + .005) * 100.) / 100.);
              System.out.println("\n\t\t\t" + "Total Interest Paid \t" + T_Interest + "\n");
              for(int index = 0; index < Month; index++)
                   System.out.printf("%f %f\n", Principle[index],Remain[index]);
         public static double round(double val, int places) {
         long factor = (long)Math.pow(10,places);
         // Shift the decimal the correct number of places
         // to the right.
         val = val * factor;
         // Round to the nearest integer.
         long tmp = Math.round(val);
         // Shift the decimal the correct number of places
         // back to the left.
         return (double)tmp / factor;
    }

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

  • Help with inventory Java program

    Hello,
    I've been working on this and couldn't get what's the problem is :(
    Can somebody explain to me what would be the problems?
    import java.util.Scanner;
    public class Product
         public static void main(String[] args)
                   Scanner s = new Scanner(System.in);
                   System.out.print("Enter the item number: ");
                   int item = s.nextInt();
                   System.out.print("Enter the product name: ");
                   String product = s.next();
                   System.out.print("Enter the unit: ");
                   int unit = s.nextInt();
                   System.out.print("Enter the price for each unit: ");
                   double price = s.nextDouble();
                   product p = new product(item, product, unit, price);
                   System.out.println("You entered: ");
                   System.out.print("Item: " + p.getItemNumber() + "\nProduct: " + p.getProductName() + "\nUnits: " + p.getUnits() + "\nPricePerUnit: " + p.getPriceUnit() + "\n");
                   System.out.println("Here is the value of inventory :" + p.getPriceInventory());
    class Inventory1
         private int itemNumber;
         private String productName;
         private int Unit;
         private double priceUnit;
         public Inventory1(int itemNumber, String productName, int Unit, double priceUnit)
              this.itemNumber = itemNumber;
              this.productName = productName;
              this.Unit = Unit;
              this.priceUnit = priceUnit;
         public int getItemNumber()
              return itemNumber;
         public void setItemNumber(int itemNumber)
              this.itemNumber = itemNumber;
         public double getPriceUnit()
              return priceUnit;
         public void setPriceUnit(double priceUnit)
              this.priceUnit = priceUnit;
         public String getProductName()
              return productName;
         public void setProductName(String productName)
              this.productName = productName;
         public int getUnit()
              return Unit;
         public void setUnit(int Unit)
              this.Unit = Unit;
         public double getPriceInventory()
              double number = getUnit() * getPriceUnit();
              return number;
    }Build output:
    --------------------Configuration: <Default>--------------------
    java:10: class Product is public, should be declared in a file named Product.java
    public class Product
           ^
    TestProduct.java:23: cannot find symbol
    symbol  : class product
    location: class Product
                product p = new product(item, product, unit, price);
                ^
    TestProduct.java:23: cannot find symbol
    symbol  : class product
    location: class Product
                product p = new product(item, product, unit, price);
                                ^
    3 errors
    Process completed.General output:
    java.lang.NoClassDefFoundError: Product
    Caused by: java.lang.ClassNotFoundException: Product
        at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:276)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
        at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
    Exception in thread "main"
    Process completed.Help!!
    Thank you in advance

    I adjusted and this time it says:
    Build Output
    --------------------Configuration: <Default>--------------------
    16: cannot find symbol
    symbol  : variable product
    location: class Product
                Product p = new Product(item, product, unit, price);
                                              ^
    16: internal error; cannot instantiate Product.<init> at Product to ()
                Product p = new Product(item, product, unit, price);
                            ^18: cannot find symbol
    symbol  : method getItemNumber()
    location: class Product
                System.out.print("Item: " + p.getItemNumber() + "\nProduct: " + p.getProductName() + "\nUnits: " + p.getUnits() + "\nPricePerUnit: " + p.getPriceUnit() + "\n");
                                             ^
    18: cannot find symbol
    symbol  : method getProductName()
    location: class Product
                System.out.print("Item: " + p.getItemNumber() + "\nProduct: " + p.getProductName() + "\nUnits: " + p.getUnits() + "\nPricePerUnit: " + p.getPriceUnit() + "\n");
                                                                                 ^
    18: cannot find symbol
    symbol  : method getUnits()
    location: class Product
                System.out.print("Item: " + p.getItemNumber() + "\nProduct: " + p.getProductName() + "\nUnits: " + p.getUnits() + "\nPricePerUnit: " + p.getPriceUnit() + "\n");
                                                                                                                    ^
    18: cannot find symbol
    symbol  : method getPriceUnit()
    location: class Product
                System.out.print("Item: " + p.getItemNumber() + "\nProduct: " + p.getProductName() + "\nUnits: " + p.getUnits() + "\nPricePerUnit: " + p.getPriceUnit() + "\n");
                                                                                                                                                        ^
    19: cannot find symbol
    symbol  : method getPriceInventory()
    location: class Product
                System.out.println("Here is the value of inventory :" + p.getPriceInventory());
                                                                         ^
    7 errors
    Process completed.General Output
    --------------------Configuration: <Default>--------------------
    java.lang.NoClassDefFoundError: Product
    Caused by: java.lang.ClassNotFoundException: Product
        at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:276)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
        at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
    Exception in thread "main"
    Process completed.(>_<)
    I forgot to mention...
    That I need to create a product class that holds the item number, the name of the product, the number of units in stock and the price of each unit (I think I got this part)
    I need to create a Java application that displays the product number, the name of the product, the number of units in stock, the price of each unit, and the value of the inventory (the number of units in stock multiplied by the price of each unit).
    Edited by: yodartas on Sep 27, 2008 7:54 PM

  • A simple Java program to be compiled with ojc and executed with java.exe

    Hi ,
    This thread is relevant to Oracle Java Compiler (file ojc) and jave.exe file.
    I have written a simple java program which consists of two simple simple classes and using the JDev's 10.1.3.2 ojc and java files , i'm trying to execute it after the successful compilation....
    The problem is that trying to run it... the error :
    Exception in thread "main" java.lang.NoClassDefFoundError: EmployeeTest
    appears.
    How can i solve this problem...????
    The program is as follows:
    import java.util.*;
    import corejava.*;
    public class EmployeeTest
    {  public static void main(String[] args)
       {  Employee[] staff = new Employee[3];
          staff[0] = new Employee("Harry Hacker", 35000,
             new Day(1989,10,1));
          staff[1] = new Employee("Carl Cracker", 75000,
             new Day(1987,12,15));
          staff[2] = new Employee("Tony Tester", 38000,
             new Day(1990,3,15));
          int i;
          for (i = 0; i < 3; i++) staff.raiseSalary(5);
    for (i = 0; i < 3; i++) staff[i].print();
    class Employee
    {  public Employee(String n, double s, Day d)
    {  name = n;
    salary = s;
    hireDay = d;
    public void print()
    {  System.out.println(name + "...." + salary + "...."
    + hireYear());
    public void raiseSalary(double byPercent)
    {  salary *= 1 + byPercent / 100;
    public int hireYear()
    {  return hireDay.getYear();
    private String name;
    private double salary;
    private Day hireDay;
    For compilation... i use :
    D:\ORACLE_UNZIPPED\JDeveloper_10.1.3.2\jdev\bin\ojc -classpath D:\E-Book\Java\Sun_Java_Book_I\Corejava EmployeeTest.java
    For execution , i issue the command:
    D:\ORACLE_UNZIPPED\JDeveloper_10.1.3.2\jdk\bin\java EmployeeTest
    NOTE:I tried to use the jdk of Oracle database v.2 but the error :
    Unable to initialize JVM appeared....
    Thanks , a lot
    Simon

    Hi,
    Thanks god....
    I found a solution without using Jdev.....
    C:\oracle_files\Java\Examples>SET CLASSPATH=.;D:\E-Book\Java\Sun_Java_Book_I\Corejava
    C:\oracle_files\Java\Examples>D:\ORACLE_UNZIPPED\JDeveloper_10.1.3.2\jdk\bin\javac EmployeeTest.java
    C:\oracle_files\Java\Examples>D:\ORACLE_UNZIPPED\JDeveloper_10.1.3.2\jdk\bin\java EmployeeTest
    What does Ant has to do with this?Sorry, under the Ant tree a classpath label is found....I'm very new to Java and JDev...
    You need to include the jar file that has the Day method in it inside project properties->libraries.I have not .jar file.. just some .java files under the corejava directory.... By the way , I have inserted the corejava directory to the project pressing the button Add Jar/Directory.... , but the problem insists..
    Thanks , a lot
    Simon

Maybe you are looking for

  • Difference in S_ALR_87012172 & FAGLL03

    Hi Gurus,  We have an issue that total balance of the two reports S_ALR_87012172 & FAGLL03 are not matching.  This is because of alternative recon.account maintained with respect to GL maintained in customer master. Therefore, whenever posting done f

  • Index page CS4 doesn't display properly for google chrome users

    index page CS4/ Dreamweaver doesn't display properly for google chrome users, shows as a blue page /  version of Chrome is 17.0.963.56 m. version of flash is 11.1.102.62.  Operating system is Version 6.1 (Build 7601, Service Pack 1).  Javascript vers

  • OpenDocument and token timeout

    Hello, I am using openDocument URL method to display webi and crystal reports. I am reusing the same token that has been generated by SDK to show multiple reports. I am not able to check whether token is valid or not. Once token or the session that c

  • IOS7 Problem mit Benachrichtigungen in der Zentrale

    Hallo ich bekomme unter iOS7 mit meinem iPhone 4s keine Push Benachrichtigungen von Apps & dem Kalender in der Mitteilungszentrale angezeigt obwohl entsprechende Optionen aktiviert sind. Nur Push von Whats App & Emails werden angezeigt. Rücksetzen  &

  • Synchronization issue (apps and contacts affected)

    I have a Verizon iPhone 4, and my understanding has been that iTunes doesn't back up contacts. So I tried to back up my contacts to my Google account by going to devices > info > synch contacts with google contacts. I hadn't changed any settings for