New to Java and I guess a scope question.

Hello and thank you for taking the time to read this. I am not a real programmer, everything I have ever done was a total hack, or written without a full understanding of how I was doing it. One thing about Java is that you might have like 20 classes (or interfaces or whatever), and that code is "all over" (which means to me not on one big page). My comment statements may look odd to others, but the program is for me alone and well, only I need to understand them.
Through some hacking, I wrote/copied/altered the following code:
import java.io.*;
import java.util.*;
public class readDataTest
     public static void main(String[] args)
          /* get filename from user, will accept and work with drive name
          e.g. c:\java\data.txt, if it is the same drive as the compiler
          does not need the directory. however, it always needs the extension.
          userInput is created by me, File, StringBuffer, BufferReader
          are part of java.io */
          userInput fileinput = new userInput();
          String filename = fileinput.getUserInput("What is the file's name");
          File file = new File(filename);
          StringBuffer contents = new StringBuffer();
          BufferedReader reader = null;
          //try to read the data into reader
          try
               reader = new BufferedReader(new FileReader(file));
               String text = null;
               while((text = reader.readLine()) !=null)
                    //create a really big string, seems inefficient
                    contents.append(text).append(System.getProperty("line.separator"));
               //close the reader
               reader.close();
          catch (IOException e)
               System.out.println(e);
          //take the huge string and parse out all the carriage returns
          String[] stringtext = contents.toString().split("\\r");
          //create mmm to get take the individual string elements of stringtext
          String mmm;
          //create ccc to create the individual parsed array for the ArrayList
          String[] ccc = new String[2];
          //create the arraylist to store the data
          ArrayList<prices> data = new ArrayList<prices>();
          /*go through the carriage returned parsed array and feed the data elements
          into appropriate type into the arraylist, note the parse takes the eof as an
          empty cell*/
          //prices pricestamp = new prices();
          for(int c=0; c < stringtext.length-1; c++)
               prices pricestamp = new prices();
               mmm=stringtext[c];
               /*trims the extra text created by the carriage return, if it is not
               trimmed, the array thinks its got an element that is "" */
               mmm=mmm.trim();
               //whitespace split the array
               ccc=mmm.split("\\s");
               pricestamp.time=Integer.parseInt(ccc[0]);
               pricestamp.price=Double.parseDouble(ccc[1]);
               //System.out.println(ccc[1]);
               data.add(pricestamp);
               //System.out.println(data.get(c).price);
               //pricestamp.time=0;
               //pricestamp.price=0;
               pricestamp=null;
          //pricestamp=null;
          //System.out.println(pricestamp.price);
          System.out.println(data.size());
          double totalprice=0;
          for(int c=0; c<data.size(); c++)
               //System.out.println(data.get(c).price);
               totalprice+=data.get(c).price;
          System.out.println("This is the total price: " + totalprice);
public class prices
     int time;
     double price;
public class evenOdd
     public int isEven(double number)
          int evenodd;
          double half = number/2;
          int half2 = (int) half;
          if(half == half2)
               evenodd = 1;
          else
               evenodd = 0;
          return evenodd;
So the program works and does what I want it to do. I am very sure there are better ways to parse the data, but thats not my question. (For argument's sake lets assume the data that feeds this is pre-cleaned and is as perfect as baby in its mother's eyes). My question is actually something else. What I originally tried to do was the following:
prices pricestamp = new prices();
          for(int c=0; c < stringtext.length-1; c++)
               mmm=stringtext[c];
               mmm=mmm.trim();
               ccc=mmm.split("\\s");
               pricestamp.time=Integer.parseInt(ccc[0]);
               pricestamp.price=Double.parseDouble(ccc[1]);
               data.add(pricestamp);
however, when I did this, this part:
for(int c=0; c<data.size(); c++)
               //System.out.println(data.get(c).price);
               totalprice+=data.get(c).price;
          System.out.println("This is the total price: " + totalprice);
would only use the last price recorded in data. So each iteration was just the last price added to totalprice. I spent hours trying to figure out why and trying different ways of doing it to get it to work (as you probably can tell from random commented out lines). I am completely dumbfounded why it doesn't work the other way. Seems inefficient to me to keep creating an object (I think thats the right terminology, i equate this to dim in VB) and then clearing it, instead of just opening it once and then just overwriting it). I really would appreciate an explanation of what I am missing.
Thank you.
Rich

prices pricestamp = new prices();
for(int c=0; c < stringtext.length-1; c+)
mmm=stringtext[c];
mmm=mmm.trim();
ccc=mmm.split("\\s");
pricestamp.time=Integer.parseInt(ccc[0]);
pricestamp.price=Double.parseDouble(ccc[1]);
data.add(pricestamp);
}This is definitely wrong. You have only created one instance of pricestamp and you just keep overwriting it with new values. You need to put the new inside the loop to create a new instance for each row.
Also I doubt you really mean .length - 1, that doesn't include the last row.
Style wise:
Class names should always start with capital letters, fields and variable always with lower case letters. These conventions aren't imposed by the compiler but are established practice, and make your code a lot easier to follow. Use "camel case" to divide you names into words e.g. priceStamp
When using single letter names for integer indices people tend to expect i through n. This is a historical thing, dating back to FORTRAN.

Similar Messages

  • Im new to java and hope somebody can help me with my question

    Hi!
    Im quite new to java and I just have some simple questions..
    can someone please tell what kinds of error are considered as language violation for java? where can I find more info about these errors?
    can someone give me a simple example on a kind of error that cannot be caught in both compilation and runtime? I hope someone can help me out. Thanks in advance!!

    knightz211 wrote:
    Im just asking about errors that might go against the language definition but cant be detected.. If it "goes against the language defintion," it will be detected by the compiler. That's half of the compiler's job is to tell you what you've done that violates the language spec.
    because it confuses me when they say that such errors might occur so I just want to know what might these errors be.. sorry for that..Who's "they"? What exactly* did "they" say about "such errors"? It sounds to me like you're just confused, and you think there's something mysterious and inexplicable going on but you don't know what and don't even know what you're asking.
    I would suggest not worrying about hypothetical problems that you can't even put into words and focussing on learning Java. Along the way, if you encounter real, specific, actual problems, ask about them, and you'll probably get answers about the problems themselves and the language or theory behind them.

  • Hello, I am new to java and I am trying to something cool

    Hello I am new to Java and I am trying to do something cool. I have written some code and it compiles nicely. Basically what I am trying to do is use ActionListeners with JTextArea to change the size of a rectangle thing.
    Here is my code. The problem is that when I push the submit button nothing happens. Any help you could give would be greatly appreciated.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import javax.swing.*;
    class SecondGate extends JFrame implements ActionListener {
         float sxd = 190f;
         float dps = 190f;
         JTextArea Long = new JTextArea(1,3);
         JTextArea Short = new JTextArea(1,3);
         JLabel one = new JLabel("width");
         JLabel two = new JLabel ("Height");
         JButton Submit = new JButton("Submit");
    public SecondGate() {
    super("Draw a Square");
    setSize(500, 500);
         Submit.addActionListener(this);
         setLayout(new BorderLayout());
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         String Width = Float.toString(sxd);
         String Height = Float.toString(dps);
         Rect sf = new Rect(Width, Height);
         JPanel pane = new JPanel();
         pane.add(one);
         pane.add(Long);
         pane.add(two);
         pane.add(Short);
         pane.add(Submit);
         add(pane, BorderLayout.EAST);
         add(sf,BorderLayout.CENTER);
    setVisible(true);
         public void actionPerformed(ActionEvent evt) {
    Object source = evt.getSource();
    if (source == Submit) {
              sxd = Float.parseFloat(Long.getText());
              dps = Float.parseFloat(Short.getText());
         repaint();
         public static void main(String[] arguments) {
    SecondGate frame = new SecondGate();
    class Rect extends JPanel {
         String Width;
         String Height;
    public Rect(String Width, String Height) {
    super();
    this.Width = Width;
    this.Height = Height;
    public void paintComponent(Graphics comp) {
    super.paintComponent(comp);
    Graphics2D comp2D = (Graphics2D)comp;
    comp2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
         BasicStroke pen = new BasicStroke(5F, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND);
    comp2D.setStroke(pen);
         comp2D.setColor(Color.blue);
         BasicStroke pen2 = new BasicStroke();
    comp2D.setStroke(pen2);
    Ellipse2D.Float e1 = new Ellipse2D.Float(235, 140, Float.valueOf(Width), Float.valueOf(Height));
    comp2D.fill(e1);
         GeneralPath fl = new GeneralPath();
         fl.moveTo(100F, 90F);
         fl.lineTo((Float.valueOf(Width) + 100F),90F);
         fl.lineTo((Float.valueOf(Width) + 100F),(Float.valueOf(Height) + 90F));
         fl.lineTo(100F,(Float.valueOf(Height) + 90F));
         fl.closePath();
         comp2D.fill(fl);
         }

    I got it to work. You were right about the method and references. Thank you
    Here is the working code for anyone who is interested in how to do this.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import javax.swing.*;
    class SecondGate extends JFrame implements ActionListener {
    float sxd = 190f;
    float dps = 190f;
    JTextArea Long = new JTextArea(1,3);
    JTextArea Short = new JTextArea(1,3);
    JLabel one = new JLabel("width");
    JLabel two = new JLabel ("Height");
    JButton Submit = new JButton("Submit");
    String Width = Float.toString(sxd);
    String Height = Float.toString(dps);
    Rect sf = new Rect(Width, Height);
         public SecondGate() {
              super("Draw a Square");
              setSize(500, 500);
              Submit.addActionListener(this);
              setLayout(new BorderLayout());
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              JPanel pane = new JPanel();
              pane.add(one);
              pane.add(Long);
              pane.add(two);
              pane.add(Short);
              pane.add(Submit);
              add(pane, BorderLayout.EAST);
              add(sf,BorderLayout.CENTER);
              setVisible(true);
         public void actionPerformed(ActionEvent evt) {
              Object source = evt.getSource();
              if (source == Submit) {
              String Width = Long.getText();
              String Height = Short.getText();          
              sf.Width(Width);
              sf.Height(Height);
                   repaint();
         public static void main(String[] arguments) {
              SecondGate frame = new SecondGate();
         class Rect extends JPanel {
              String Width;
              String Height;
         public Rect(String Width, String Height) {
              super();
              this.Width = Width;
              this.Height = Height;
         String Width (String Width){
              this.Width = Width;
              return this.Width;
         String Height (String Height) {
              this.Height = Height;
              return Height;
         public void paintComponent(Graphics comp) {
              super.paintComponent(comp);
              Graphics2D comp2D = (Graphics2D)comp;
              comp2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
              BasicStroke pen = new BasicStroke(5F, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND);
              comp2D.setStroke(pen);
              comp2D.setColor(Color.blue);
              BasicStroke pen2 = new BasicStroke();
              comp2D.setStroke(pen2);
              Ellipse2D.Float e1 = new Ellipse2D.Float(235, 140, Float.valueOf(Width), Float.valueOf(Height));
              comp2D.fill(e1);
              GeneralPath fl = new GeneralPath();
              fl.moveTo(100F, 90F);
              fl.lineTo((Float.valueOf(Width) + 100F),90F);
              fl.lineTo((Float.valueOf(Width) + 100F),(Float.valueOf(Height) + 90F));
              fl.lineTo(100F,(Float.valueOf(Height) + 90F));
              fl.closePath();
              comp2D.fill(fl);
              }

  • I just got a new iPad 2 and I have lot of questions. I was able to wirelessly link my iPad and iTunes on my PC. I was able to SYNC my email and calendar (new only no history), however I have not been able to SYNC Outlook contacts.

    I just got a new iPad 2 and I have lot of questions. I was able to wirelessly link my iPad and iTunes on my PC. I was able to SYNC my email and calendar (new entries only no history), however I have not been able to SYNC Outlook contacts. Outlook has multiple contact lists. Only one has any data. I can't find a way to delete the others and I can't keep the one I want to use at the top of the list. Any ideas?
    I have a question about email. I have several thousand emails in 10 or so days. How can I select multiple emails for deletion in stead of one at a time? How do I designate emails from a given sender as junk or block certain senders?
    Ron

    the spcs page on this site state which video formats the ipad supports
    I'd suggest converting your old videos to one of those formats
    handbrake is a free program which does this for you
    itunes used to be able to too when I right clicked incompatible media but don't see the option any more
    or maybe it only show when one right click incompatible media and currently my lib don't have any
    about the music then it's odd what formats are they?
    if they are acc protected have you tried to remove the DRM this can be don using itunes as
    apple don't use DRM for music any more

  • I'm new Help user, and i just asked a question, had to go to email and confirmed email address to start the account, now how do i find the question/answer i just asked?

    I'm a new Help user, and i just asked a question, had to go to email and confirmed email address to start the account, now how do i find the question/answer i had just asked/posted?

    Thanks!!! Things are so easy when you know how.

  • I'm new to Java and can't get javac command working

    Ok first of all hello ( i'm new to the forum ), second i'm reading a book about Java and im trying to compile a sample code from the book, but javac command gained life and it's against me. So the book i'm reading is Sams Teach Yourself Java in 21 Days (YAY), and the code i want to compile is an application that works with another bit of code that mimics what a robot could do inside a volcano. So the Volcano program code is the following ( i'll post the robot code at the end of the post):
    1: class VolcanoApp {
    2: public static void main(String[] arguments) {
    3: VolcanoRobot dante = new VolcanoRobot();
    4: dante.status = ?exploring?;
    5: dante.speed = 2;
    6: dante.temperature = 510;
    7:
    8: dante.showAttributes();
    9: System.out.println(?Increasing speed to 3.?);
    10: dante.speed = 3;
    11: dante.showAttributes();
    12: System.out.println(?Changing temperature to 670.?);
    13: dante.temperature = 670;
    14: dante.showAttributes();
    15: System.out.println(?Checking the temperature.?);
    16: dante.checkTemperature();
    17: dante.showAttributes();
    18: }
    19: }
    Ignore the numbers they are used for explaining stuff in the book, and i din't copy the indentation.
    So what i do is that i creat a file with notepad ( no fancy stuff only plain old notepad ) and i copy this code, remove the numbers and make the indents.
    After that i save as .txt file with the apropriate name ( i know it's case sensitive ). After that i open command prompt and write:
    javac VolcanoApp.java
    And it tells me that "javac is not recognized as an internal or external command operable program or batch file".
    I managed to solve that by going to the control panel and by adding to the system variables for my user in the path variable this :
    ;C:\JAVAJDK\bin
    ( C:\JAVAJDK is where JDK is installed)
    And then i modified the system variables like this:
    In the CLASSPATH i entered this .;%JAVA_HOME%\lib\tools.jar
    In JAVA_HOME i entered this C:\JAVAJDK
    Setting the variables like this made the javac error go away but now when i write in command line
    javac VolcanoApp.java
    It gives me this error
    javac: file not found : VolcanoApp.java
    Usage: javac options source files
    use -help for a list of possible options
    And then i read that i can drop my java file directly in the javac file. So i did.
    When i drop my VolcanoApp.java in the javac file it open a command line window and writes a bunch of stuff in like a milisecond and shuts down. And no file is created.
    I wanted to know what was writen in that window so i did it again and took a print screen and pasted it on paint ( it writed so much text that i only got a little bit but enough to see what hapend)
    I read it and in the print screen it said it had 15 errors ( so far ) and then it point the errors with little arrows and there were characters that weren't present in the original code.
    What hapend the compiler added wierd letters?
    SO, my real question is, how the heck do i get javac working and compiling stuff properly?
    Plz help i'm getting mad at this! ; (
    And the code for the "robot":
    1: class VolcanoRobot {
    2: String status;
    3: int speed;
    4: float temperature;
    5:
    6: void checkTemperature() {
    7: if (temperature > 660) {
    8: status = ?returning home?;
    9: speed = 5;
    10: }
    11: }
    12:
    13: void showAttributes() {
    14: System.out.println(?Status: ? + status);
    15: System.out.println(?Speed: ? + speed);
    16: System.out.println(?Temperature: ? + temperature);
    17: }
    18: }
    Again no indents and ignore the numbers. In the book it only said to compile the VolcanoApp.java , and not the VolcanoRobot.java
    Edit:
    I'm using Windows Vista Home Premium 32 bit.
    Edited by: BBlop on Dec 13, 2009 11:29 AM

    guess what it says java file. So yes i'm sure. Sarcasm. Not the best way to encourage a total stranger to help you. Then there's
    Sorry if i wasn't more clear but was that response needed?No it wasn't needed, but I'm not the one asking for help so I have the luxury of not worrying too much about it. It's extremely frustrating trying to drag relevant information out of someone, and makes one less inclined to bother.
    Anyways, there's still nothing in this thread that actually explicitly says "there is a file called VolcanoApp.java in the directory where I'm running javac from" and I really can't be bothered banging my head against the wall any longer. You've made a silly mistake, or a false assumption. We all do it from time to time. My advice is, take a break, go for a walk and re-visit this in a while. You'll probably spot the mistake right away.

  • New to Java and need help with this program..please!

    I'd really appreciate any helpful comments about this program assignment that I have to turn in a week from Friday. I'm taking a class one night a week and completely new to Java. I'd ask my professor for help, but we can't call him during the week and he never answers e-mails. He didn't tell us how to call from other classes yet, and I just can't get the darn thing to do what I want it to do!
    The assignment requirements are:
    1. Change a card game application that draws two cards
    and the higher card wins, to a Blackjack application
    2. Include a new class called Hand
    3. The Hand class should record the number of draws
    4. The application should prompt for a number of draws
    5. The game is played against the Dealer
    6. The dealer always draws a card if the dealer's hand total is <= 17
    7. Prompt the player after each hand if he wants to quit
    8. Display the total games won by the dealer and total and the total games wond by the player after each hand
    9. Display all of the dealer's and player's cards at the
    end of each hand
    10. Player has the option of drawing an additional card after the first two cards
    11. The Ace can have a value of 11 or 1
    (Even though it's not called for in the requirements, I would like to be able to let the Ace have a value of 1 or an 11)
    The following is my code with some comments about a few things that are driving me nuts:
    import java.util.*;
    import javax.swing.*;
    import java.text.*;
    public class CardDeck
    public CardDeck()
    deck = new Card[52];
    fill();
    shuffle();
    public void fill()
    int i;
    int j;
    for (i = 1; i <= 13; i++)
    for (j = 1; j <= 4; j++)
    deck[4 * (i - 1) + j - 1] = new Card(i, j);
    cards = 52;
    public void shuffle()
    int next;
    for (next = 0; next < cards - 1; next++)
    int rand = (int)(Math.random()*(next+1));
    Card temp = deck[next];
    deck[next] = deck[rand];
    deck[rand] = temp;
    public final Card draw()
    if (cards == 0)
    return null;
    cards--;
    return deck[cards];
    public int changeValue()
    int val = 0;
    boolean ace = false;
    int cds;
    for (int i = 0; i < cards; i++)
    if (cardValue > 10)
    cardValue = 10;
    if (cardValue ==1)     {
    ace = true;
    val = val + cardValue;
    if ( ace = true && val + 10 <= 21 )
    val = val + 10;
    return val;
    public static void main(String[] args)
    CardDeck d = new CardDeck();
    int x = 3;
    int i;
    int wins = 1;
    int playerTotal = 1;
    do {
    Card dealer = (d.draw());
    /**I've tried everything I can think of to call the ChangeValue() method after I draw the card, but nothing is working for me.**/
    System.out.println("Dealer draws: " + dealer);
    do {
    dealer = (d.draw());
    System.out.println(" " + dealer);
    }while (dealer.rank() <= 17);
    Card mine = d.draw();
    System.out.println("\t\t\t\t Player draws: "
    + mine);
    mine = d.draw();
    System.out.println("\t\t\t\t\t\t" + mine);
    do{
    String input = JOptionPane.showInputDialog
    ("Would you like a card? ");
    if(input.equalsIgnoreCase("yes"))
         mine = d.draw();
    System.out.println("\t\t\t\t\t\t" + mine);
         playerTotal++;
         else if(input.equalsIgnoreCase("no"))
    System.out.println("\t\t\t\t Player stands");
         else
    System.out.println("\t\tInvalid input.
    Please try again.");
    I don't know how to go about making and calling a method or class that will combine the total cards delt to the player and the total cards delt to the dealer. The rank() method only seems to give me the last cards drawn to compare with when I try to do the tests.**/
    if ((dealer.rank() > mine.rank())
    && (dealer.rank() <= 21)
    || (mine.rank() > 21)
    && (dealer.rank() < 22)
    || ((dealer.rank() == 21)
    && (mine.rank() == 21))
    || ((mine.rank() > 21)
    && (dealer.rank() <= 21)))
    System.out.println("Dealer wins");
    wins++;
         else
    System.out.println("I win!");
    break;
    } while (playerTotal <= 1);
    String stop = JOptionPane.showInputDialog
    ("Would you like to play again? ");
    if (stop.equalsIgnoreCase("no"))
    break;
    if (rounds == 5)
    System.out.println("Player wins " +
    (CardDeck.rounds - wins) + "rounds");
    } while (rounds <= 5);
    private Card[] deck;
    private int cards;
    public static int rounds = 1;
    public int cardValue;
    /**When I try to compile this nested class, I get an error message saying I need a brace here and at the end of the program. I don't know if any of this code would work because I've tried adding braces and still can't compile it.**/
    class Hand()
    static int r = 1;
    public Hand() { CardDeck.rounds = r; }
    public int getRounds() { return r++; }
    final class Card
    public static final int ACE = 1;
    public static final int JACK = 11;
    public static final int QUEEN = 12;
    public static final int KING = 13;
    public static final int CLUBS = 1;
    public static final int DIAMONDS = 2;
    public static final int HEARTS = 3;
    public static final int SPADES = 4;
    public Card(int v, int s)
    value = v;
    suit = s;
    public int getValue() { return value; }
    public int getSuit() { return suit;  }
    public int rank()
    if (value == 1)
    return 4 * 13 + suit;
    else
    return 4 * (value - 1) + suit;
    /**This works, but I'm confused. How is this method called? Does it call itself?**/
    public String toString()
    String v;
    String s;
    if (value == ACE)
    v = "Ace";
    else if (value == JACK)
    v = "Jack";
    else if (value == QUEEN)
    v = "Queen";
    else if (value == KING)
    v = "King";
    else
    v = String.valueOf(value);
    if (suit == DIAMONDS)
    s = "Diamonds";
    else if (suit == HEARTS)
    s = "Hearts";
    else if (suit == SPADES)
    s = "Spades";
    else
    s = "Clubs";
    return v + " of " + s;
    private int value; //Value is an integer, so how can a
    private int suit; //string be assigned to an integer?
    }

    Thank you so much for offering to help me with this Jamie! When I tried to call change value using:
    Card dealer = (d.changeValue());
    I get an error message saying:
    Incompatible types found: int
    required: Card
    I had my weekly class last night and the professor cleared up a few things for me, but I've not had time to make all of the necessary changes. I did find out how toString worked, so that's one question out of the way, and he gave us a lot of information for adding another class to generate random numbers.
    Again, thank you so much. I really want to learn this but I'm feeling so stupid right now. Any help you can give me about the above error message would be appreciated.

  • New to java and having issues trying to modify sample code.

    i was trying to edit the following code to add about 10+ more labels and textfields and save the information to the contacts.dat in the code. it currently displays all the fields i entered, but it only saves the first 7 fields information?? not sure why. also i was trying to just line the fields up using a flowlayout but it just errors. anyone have any suggestions?
    <source code below this line>
    ====================START OF CODE ======================
    // cm.java
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.*;
    // =========================================================
    // Class: cm
    // This class drives the contact manager. It contains the
    // main method which gets called as soon as this application
    // begins to run.
    // =========================================================
    class cm extends Frame implements ActionListener
    // Container of contact objects (one object per business
    // contact).
    private Vector contacts = new Vector (100);
    // List of names component. (Must specify java.awt in
    // front of List to distinguish the List class in the
    // java.awt package from the List class in the java.util
    // package.)
    private java.awt.List names = new java.awt.List ();
    // delete and edit button components.
    private Button delete;
    private Button edit;
    // Default constructor.
    public cm ()
    // Assign Contact Manager to title bar of frame window.
    super ("Customer Manager Version 0.001 BY Pebkac");
    // Add a listener that responds to window closing
    // events. When this event occurs (by clicking on the
    // close box in the title bar), save contacts and exit.
    addWindowListener (new WindowAdapter ()
    public void windowClosing
    (WindowEvent e)
    saveContacts ();
    System.exit (0);
    // Place an empty label in the north part of the frame
    // window. This is done to correct an AWT positioning
    // problem. (One thing that you'll come to realize as
    // you work with the AWT is that there are lots of bugs.)
    Label l = new Label ();
    add ("North", l);
    // Place the names component in the center part of the
    // frame window.
    add ("Center", names);
    // Create a panel object to hold four buttons.
    Panel p = new Panel ();
    Button b;
    // Add an add button to the Panel object and register
    // the current cm object as a listener for button events.
    p.add (b = new Button ("add"));
    b.addActionListener (this);
    // Add a delete button to the Panel object and register
    // the current cm object as a listener for button events.
    p.add (delete = new Button ("delete"));
    delete.addActionListener (this);
    // The delete button should be disabled until there is at
    // least one contact to delete.
    delete.setEnabled (false);
    // Add an edit button to the Panel object and register
    // the current cm object as a listener for button events.
    p.add (edit = new Button ("edit"));
    edit.addActionListener (this);
    // The edit button should be disabled until there is at
    // least one contact to edit.
    edit.setEnabled (false);
    // Add a quit button to the Panel object and register
    // the current cm object as a listener for button events.
    p.add (b = new Button ("quit"));
    b.addActionListener (this);
    // Add the panel object to the frame window container.
    add ("South", p);
    // Set the background of the frame window container to
    // pink (to give a pleasing effect).
    setBackground (Color.pink);
    // Set the size of the frame window container to 400
    // pixels horizontally by 200 pixels vertically.
    setSize (400, 200);
    // Do not allow the user to resize the frame window.
    setResizable (false);
    // Load all contacts.
    loadContacts ();
    // Make sure that the frame window is visible.
    setVisible (true);
    public void actionPerformed (ActionEvent e)
    if (e.getActionCommand ().equals ("delete"))
    delete ();
    else
    if (e.getActionCommand ().equals ("quit"))
    saveContacts ();
    System.exit (0);
    else
    if (e.getActionCommand ().equals ("add"))
    add ();
    else
    edit ();
    public Insets getInsets ()
    // Return an Insets object that describes the number of
    // pixels to reserve as a border around the edges of the
    // frame window.
    return new Insets (10, 10, 10, 10);
    public static void main (String [] args)
    // Create a new cm object and let it do its thing.
    new cm ();
    private void delete ()
    // Obtain index of selected contact item from the names
    // component.
    int index = names.getSelectedIndex ();
    // If no item was selected, index is -1. We cannot edit
    // a contact if no contact item in the names component was
    // selected - because we would have nothing to work with.
    if (index != -1)
    // Remove the contact item from the names component.
    names.remove (index);
    // Remove the Contact object from the contacts Vector
    // object.
    contacts.remove (index);
    // If there are no more contacts ...
    if (contacts.size () == 0)
    delete.setEnabled (false);
    edit.setEnabled (false);
    else
    // Make sure that the first contact item in the names
    // list is highlighted.
    names.select (0);
    private void add ()
    // Create an add data entry form to enter information
    // for a new contact.
    DataEntryForm def = new DataEntryForm (this, "add");
    // If the bOk Boolean flag is set, this indicates the user
    // exited the form by pressing the Ok button.
    if (def.bOk)
    // Create a Contact object and assign information from
    // the form to its fields.
    Contact temp = new Contact ();
    temp.fname = new String (def.fname.getText ());
    temp.lname = new String (def.lname.getText ());
    temp.haddress = new String (def.haddress.getText ());
    temp.maddress = new String (def.maddress.getText ());
    temp.phone = new String (def.phone.getText ());
    temp.wphone = new String (def.wphone.getText ());
    temp.cphone = new String (def.cphone.getText ());
    temp.email = new String (def.email.getText ());
    temp.bdate = new String (def.bdate.getText ());
    temp.comments = new String (def.comments.getText ());
    // Add a new contact item to the names component.
    names.add (temp.lname + ", " + temp.fname);
    // Add the Contact object to the contacts Vector
    // object.
    contacts.add (temp);
    // Make sure that the delete and edit buttons are
    // enabled.
    delete.setEnabled (true);
    edit.setEnabled (true);
    // Destroy the dialog box.
    def.dispose ();
    // Make sure that the first contact item in the names list
    // is highlighted.
    names.select (0);
    // ===========================================================
    // Load all contacts from contacts.dat into the contacts
    // Vector object. Also, make sure that the last name/first
    // name from each contact is combined into a String object and
    // added into the names component - as a contact item.
    // ===========================================================
    private void loadContacts ()
    FileInputStream fis = null;
    try
    fis = new FileInputStream ("contacts.dat");
    DataInputStream dis = new DataInputStream (fis);
    int nContacts = dis.readInt ();
    for (int i = 0; i < nContacts; i++)
    Contact temp = new Contact ();
    temp.fname = dis.readUTF ();
    temp.lname = dis.readUTF ();
    temp.haddress = dis.readUTF ();
    temp.maddress = dis.readUTF ();
    temp.phone = dis.readUTF ();
    temp.wphone = dis.readUTF ();
    temp.cphone = dis.readUTF ();
    temp.email = dis.readUTF ();
    temp.bdate = dis.readUTF ();
    temp.comments = dis.readUTF ();
    names.add (temp.lname + ", " + temp.fname);
    contacts.add (temp);
    if (nContacts > 0)
    delete.setEnabled (true);
    edit.setEnabled (true);
    catch (Exception e)
    finally
    if (fis != null)
    try
    fis.close ();
    catch (Exception e) {}
    // Make sure that the first contact item in the names list
    // is highlighted.
    names.select (0);
    // ========================================================
    // Save all Contact objects from the contacts Vector object
    // to contacts.dat. The number of contacts are saved as an
    // int to make it easy for loadContacts () to do its job.
    // ========================================================
    private void saveContacts ()
    FileOutputStream fos = null;
    try
    fos = new FileOutputStream ("contacts.dat");
    DataOutputStream dos = new DataOutputStream (fos);
    dos.writeInt (contacts.size ());
    for (int i = 0; i < contacts.size (); i++)
    Contact temp = (Contact) contacts.elementAt (i);
    dos.writeUTF (temp.fname);
    dos.writeUTF (temp.lname);
    dos.writeUTF (temp.haddress);
    dos.writeUTF (temp.maddress);
    dos.writeUTF (temp.phone);
    dos.writeUTF (temp.wphone);
    dos.writeUTF (temp.cphone);
    dos.writeUTF (temp.email);
    dos.writeUTF (temp.bdate);
    dos.writeUTF (temp.comments);
    catch (Exception e)
    MsgBox mb = new MsgBox (this, "CM Error",
    e.toString ());
    mb.dispose ();
    finally
    if (fos != null)
    try
    fos.close ();
    catch (Exception e) {}
    private void edit ()
    // Obtain index of selected contact item from the names
    // component.
    int index = names.getSelectedIndex ();
    // If no item was selected, index is -1. We cannot edit
    // a contact if no contact item in the names component was
    // selected - because we would have nothing to work with.
    if (index != -1)
    // Obtain a reference to the Contact object (from the
    // contacts Vector object) that is associated with the
    // index.
    Contact temp = (Contact) contacts.elementAt (index);
    // Create and display an edit entry form.
    DataEntryForm def = new DataEntryForm (this, "edit",
    temp.fname,
    temp.lname,
    temp.haddress,
    temp.maddress,
    temp.phone,
    temp.wphone,
    temp.cphone,
    temp.email,
    temp.bdate,
    temp.comments);
    // If the user pressed Ok...
    if (def.bOk)
    // edit the contact information in the contacts
    // Vector object.
    temp.fname = new String (def.fname.getText ());
    temp.lname = new String (def.lname.getText ());
    temp.haddress = new String (def.haddress.getText ());
    temp.maddress = new String (def.maddress.getText ());
    temp.phone = new String (def.phone.getText ());
    temp.wphone = new String (def.wphone.getText ());
    temp.cphone = new String (def.cphone.getText ());
    temp.email = new String (def.email.getText ());
    temp.bdate = new String (def.bdate.getText ());
    temp.comments = new String (def.comments.getText ());
    // Make sure the screen reflects the edit.
    names.replaceItem (temp.lname + ", " + temp.fname,
    index);
    // Destroy the dialog box.
    def.dispose ();
    // Make sure that the first contact item in the names
    // list is highlighted.
    names.select (0);
    // ========================================================
    // Class: Contact
    // This class describes the contents of a business contact.
    // ========================================================
    class Contact
    public String fname;
    public String lname;
    public String haddress;
    public String maddress;
    public String phone;
    public String wphone;
    public String cphone;
    public String email;
    public String bdate;
    public String comments;
    // ==========================================================
    // Class: DataEntryForm
    // This class provides a data entry form for entering contact
    // information.
    // ==========================================================
    class DataEntryForm extends Dialog implements ActionListener
    // bOk is a boolean flag. When true, it indicates that
    // the Ok button was pressed to terminate the dialog box
    // (as opposed to the Cancel button).
    public boolean bOk;
    // The following components hold the text that the user
    // entered into the visible text fields.
    public TextField fname;
    public TextField lname;
    public TextField haddress;
    public TextField maddress;
    public TextField phone;
    public TextField wphone;
    public TextField cphone;
    public TextField email;
    public TextField bdate;
    public TextField comments;
    public void actionPerformed (ActionEvent e)
    // If the user pressed the Ok button, indicate this
    // by assigning true to bOk.
    if (e.getActionCommand ().equals ("Ok"))
    bOk = true;
    // Destroy the dialog box and return to the point
    // just after the creation of the DataEntryForm object.
    dispose ();
    public DataEntryForm (Frame parent, String title)
    // Call the other constructor. The current constructor
    // is used for add operations. The other constructor
    // is used for edit operations.
    this (parent, title, "", "", "", "", "", "", "", "", "", "");
    public DataEntryForm (Frame parent, String title,
    String fname, String lname,
    String haddress, String maddress,
    String phone,String wphone,
    String cphone,String email,
    String bdate,String comments)
    // Initialize the superclass layer.
    super (parent, title, true);
    // Choose a grid bag layout so that components can be more
    // accurately positioned. (It looks nicer.)
    setLayout (new GridBagLayout ());
    // Add appropriate first name, last name, phone, wphone, and
    // email components to the current DataEntryForm container.
    // (Remember, DataEntryForm is a subclass of Dialog.
    // Dialog is a container. Therefore, DataEntryForm
    // inherits the ability to be a container.)
    addComponent (this, new Label ("First Name: "),0, 0, 1, 1,
    GridBagConstraints.NONE,
    GridBagConstraints.WEST);
    this.fname = new TextField (20);
    addComponent (this, this.fname, 1, 0, 1, 1,
    GridBagConstraints.NONE,
    GridBagConstraints.CENTER);
    if (title.equals ("edit"))
    this.fname.setText (fname);
    addComponent (this, new Label ("Last Name: "), 0, 1, 1, 1,
    GridBagConstraints.NONE,
    GridBagConstraints.WEST);
    this.lname = new TextField (20);
    addComponent (this, this.lname, 1, 1, 1, 1,
    GridBagConstraints.NONE,
    GridBagConstraints.CENTER);
    if (title.equals ("edit"))
    this.lname.setText (lname);
    addComponent (this, new Label ("Home Address: "), 0, 2, 1, 1,
    GridBagConstraints.NONE,
    GridBagConstraints.WEST);
    this.haddress = new TextField (20);
    addComponent (this, this.haddress, 1, 2, 1, 1,
    GridBagConstraints.NONE,
    GridBagConstraints.CENTER);
    if (title.equals ("edit"))
    this.haddress.setText (haddress);
    addComponent (this, new Label ("Mailing Address: "), 0, 3, 1, 1,
    GridBagConstraints.NONE,
    GridBagConstraints.WEST);
    this.maddress = new TextField (20);
    addComponent (this, this.maddress, 1, 3, 1, 1,
    GridBagConstraints.NONE,
    GridBagConstraints.CENTER);
    if (title.equals ("edit"))
    this.maddress.setText (maddress);
    addComponent (this, new Label ("Home Number: "), 0, 4, 1, 1,
    GridBagConstraints.NONE,
    GridBagConstraints.WEST);
    this.phone = new TextField (20);
    addComponent (this, this.phone, 1, 4, 1, 1,
    GridBagConstraints.NONE,
    GridBagConstraints.CENTER);
    if (title.equals ("edit"))
    this.phone.setText (phone);
    addComponent (this, new Label ("Work Number: "), 0, 5, 1, 1,
    GridBagConstraints.NONE,
    GridBagConstraints.WEST);
    this.wphone = new TextField (20);
    addComponent (this, this.wphone, 1, 5, 1, 1,
    GridBagConstraints.NONE,
    GridBagConstraints.CENTER);
    if (title.equals ("edit"))
    this.wphone.setText (wphone);
    addComponent (this, new Label ("Cell Number: "), 0, 6, 1, 1,
    GridBagConstraints.NONE,
    GridBagConstraints.WEST);
    this.cphone = new TextField (20);
    addComponent (this, this.cphone, 1, 6, 1, 1,
    GridBagConstraints.WEST,
    GridBagConstraints.WEST);
    addComponent (this, new Label ("Email Address: "), 0, 7, 1, 1,
    GridBagConstraints.NONE,
    GridBagConstraints.WEST);
    this.email = new TextField (20);
    addComponent (this, this.email, 1, 7, 1, 1,
    GridBagConstraints.NONE,
    GridBagConstraints.WEST);
    addComponent (this, new Label ("Birth Date: "), 0, 8, 1, 1,
    GridBagConstraints.NONE,
    GridBagConstraints.WEST);
    this.bdate = new TextField (20);
    addComponent (this, this.bdate, 1, 8, 1, 1,
    GridBagConstraints.NONE,
    GridBagConstraints.WEST);
    addComponent (this, new Label ("Comments: "), 2, 0, 1, 1,
    GridBagConstraints.NONE,
    GridBagConstraints.WEST);
    this.comments = new TextField (20);
    addComponent (this, this.comments, 2, 1, 1, 1,
    GridBagConstraints.NONE,
    GridBagConstraints.WEST);
    addComponent (this, new Label (""), 0, 9, 1, 1,
    GridBagConstraints.NONE,
    GridBagConstraints.WEST);
    addComponent (this, new Label (""), 1, 9, 1, 1,
    GridBagConstraints.NONE,
    GridBagConstraints.WEST);
    Button b;
    // Add an Ok button to this container.
    addComponent (this, b = new Button ("Ok"), 0, -9, 1, 1,
    GridBagConstraints.NONE,
    GridBagConstraints.CENTER);
    b.addActionListener (this);
    // Add a Cancel button to this container.
    addComponent (this, b = new Button ("Cancel"), 1, -9, 1, 1,
    GridBagConstraints.NONE,
    GridBagConstraints.CENTER);
    b.addActionListener (this);
    // Set the background of the frame window container to
    // pink (to give a pleasing effect).
    setBackground (Color.pink);
    // Set the size of the dialog window to 250 pixels
    // horizontally by 200 pixels vertically.
    setSize (450, 500);
    // Do not allow users to resize the dialog window.
    setResizable (false);
    // Make sure that the dialog window is visible.
    setVisible (true);
    private void addComponent (Container con, Component com,
    int gridx, int gridy,
    int gridw, int gridh, int fill,
    int anchor)
    // Get the current layout manager. It is assumed to
    // be a GridBagLayout object.
    LayoutManager lm = con.getLayout ();
    // Create a GridBagConstraints object to make it
    // possible to customize component positioning.
    GridBagConstraints gbc = new GridBagConstraints ();
    // Assign the x and y grid positions.
    gbc.gridx = gridx;
    gbc.gridy = gridy;
    // Assign the number of grid blocks horizontally and
    // vertically that are occupied by the component.
    gbc.gridwidth = gridw;
    gbc.gridheight = gridh;
    // Specify the component's resize policy (fill) and
    // the direction in which the component is positioned
    // when its size is smaller than available space (anchor).
    gbc.fill = fill;
    gbc.anchor = anchor;
    // Set the new constraints that the grid bag layout
    // manager will use.
    ((GridBagLayout) lm).setConstraints (com, gbc);
    // Add the component to the container.
    con.add (com);
    // ===========================================================
    // Class: MsgBox
    // This class displays a message box to the user. The message
    // is usually an error message. The user must press the Ok
    // button to terminate the message box.
    // ===========================================================
    class MsgBox extends Dialog implements ActionListener
    public void actionPerformed (ActionEvent e)
    // Terminate the dialog box in response to the user
    // pressing the Ok button.
    dispose ();
    public MsgBox (Frame parent, String title, String msg)
    // Initialize the superclass layer.
    super (parent, title, true);
    // Store the msg argument in a Label object and add
    // this object to the center part of the dialog window.
    Label l = new Label (msg);
    add ("Center", l);
    // Create a Button object and add it to the south part
    // of the dialog window.
    Button b = new Button ("Ok");
    add ("South", b);
    // Make the current object a listener to events that
    // occur as a result of the user pressing the Ok
    // button.
    b.addActionListener (this);
    // Make sure that the Ok button has the focus.
    b.requestFocus ();
    // Do not allow users to resize the dialog window.
    setResizable (false);
    // Allow the layout manager to choose an appropriate
    // size for the dialog window.
    pack ();
    // Make sure that the dialog window is visible.
    setVisible (true);
    ====================END OF CODE =======================

    You should first start by formatting the code before
    posting. I lost my interest as I browsed thorugh the
    code.
    Read here -
    http://forum.java.sun.com/help.jspa?sec=formatting
    ...and its way too much code to expect anyone to read. Post a short excerpt of the part you are having trouble with.

  • I'm new to java and need help please

    I have an assignment involves modifying a previous assignment. the code for the previous assigment is shown below.(it was required to be done as an applet this assigment can be an application or an applet) I'm trying to modify this code to read a text file (items.txt) that looks like this:
    item # description price(this line does not appear in the text file)
    001 shaving cream 400.00
    999 razors 30.00
    I need to load the item# and price from the text file into arrays(I have no clue how to use multi-dimensional arrays in java and would prefer not to)
    I need to search the arrays based on the values entered by the user (item # and quantity) calculate the total for that item then create a new text file which has each line item for that order in the form:
    item# quant price per item total(price per item*quant entered)
    also also I need to be able to display the four items listed above after each loop as well as all the previous item number and quantities they selected until they indicate they don't want to select anymore.
    I've been working on this for days and it seems like nothing I try works. My major problems are:
    1. I have no idea how to read the text file and load those 2 items into their respective arrays
    2. I can't seem to create a textfile that looks like text for the output file.
    code]
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.text.*;
    import java.util.Locale;
    public class arraySelection
    extends JApplet {
    //Initialize the applet
    private Container getContentPane=null;
    public void init() {
    String string_item, string_quantity;
    String output = "";
    String description= "";
    int counter= 0;
    int itemNumber= 0;
    double quantity = 0 ;
    double tax_rate=.07;
    double total= 0, price= 0;
    double tax, subtotal;
    double Pretotal= 0;
    double priceArray[] = {1, .5, 3.65, 0.02, 0.09};
    String descriptionArray[] = {"salt", "pepper", "paprika", "garlic", "thyme"};
    // create number format for currency in US dollar format
    NumberFormat moneyFormat = NumberFormat.getCurrencyInstance( Locale.US );
    //format to have the total with two digits precision
    DecimalFormat twoDigits = new DecimalFormat("0.00");
    //Jtextarea to display results
    JTextArea outputArea = new JTextArea ();
    // get applet's content pane
    Container container = getContentPane ();
    //attach output area to container
    container.add(outputArea);
    //set the first row of text for the output area
    output += "Invoice\nItem#\tDescription\tQuant@Price\t Line Total" + "\n";
    do //begin loop structure obtain input from user
    // obtain item number from user
    string_item = JOptionPane.showInputDialog(
    "Please enter an item number 1, 2, 3, 4, or 5:");
    //obtain quantity of each item that user enter
    string_quantity = JOptionPane.showInputDialog("Enter the quantity:");
    // convert numbers from type String to Integer or Double
    itemNumber = Integer.parseInt(string_item);
    quantity = Double.parseDouble(string_quantity);
    switch (itemNumber) {//Determine input from user to assign price and description
    case 10: // user input item =10
    price = priceArray[0];
    description = descriptionArray[0];
    break;
    case 20: // user input item =20
    price = priceArray [1];
    description = descriptionArray[1];
    break;
    case 30: //user input item =30
    price=priceArray[2];
    description = descriptionArray[2];
    break;
    case 40: //user input item =40
    price=priceArray[3];
    description = descriptionArray[3];
    break;
    case 50: //user input item =50
    price=priceArray[4];
    description = descriptionArray[4];
    break;
    default: // user input item is not on the list
    output += "Invalid value entered"+ "\n";
    price=0;
    description= "";
    //Calculates the total for each item number and stores it in subtotal
    subtotal = price * quantity;
    //display input from user
    output += itemNumber + "\t" + description + "\t\t"+ quantity + "@" +
    moneyFormat.format( price) + "\t" + moneyFormat.format( subtotal) + "\n";
    //accumulates the overall subtotal for all items
    Pretotal = Pretotal + subtotal;
    //verifies that the user wants to stop entering data
    string_item = JOptionPane.showInputDialog(" Enter a positive integer to continue or 0 to stop. ");
    itemNumber = Integer.parseInt(string_item);
    // loop termination condition if user's input is 0 .It will end the loop
    } while ( itemNumber!= 0);
    tax = Pretotal * tax_rate; // calculate tax amount
    total = Pretotal + tax; //calculate total = subtotal + tax
    //appends data regarding the subtotal, tax, and total to the output area
    output += "\n" + "Order Subtotal" + "\t" + moneyFormat.format( Pretotal) +
    "\n" + "Tax" + "\t\t" + twoDigits.format( tax ) + "\n" + "Order Total" +
    "\t\t" + moneyFormat.format( total );
    //attaches the data in the output variable to the output area
    outputArea.setText( output );
    } //end init
    }// end applet Invoice
    Any help or sugestions would be greatly appreaciated. I've been working on this for over a week and everything I try goes nowhere.

    item # description price(this
    line does not appear in the text file)
    001 shaving cream 400.00
    999 razors 30.00
    I need to load the item# and price from the text file
    into arrays(I have no clue how to use
    multi-dimensional arrays in java and would prefer not
    to)That's good, because you shouldn't use multidimensional arrays here. You should have a one-dimensional array (or java.util.List) of objects that encapsulate each line.
    I've been working on this for days and it seems like
    nothing I try works. My major problems are:
    1. I have no idea how to read the text file and load
    those 2 items into their respective arrays
    2. I can't seem to create a textfile that looks like
    text for the output file.The java.io package has file reading/writing classes.
    Here's a tutorial:
    http://java.sun.com/docs/books/tutorial/essential/io/index.html

  • I'm new to java and need help please(repost)

    I have an assignment involves modifying a previous assignment. the code for the previous assigment is shown below.(it was required to be done as an applet this assigment can be an application or an applet) I'm trying to modify this code to read a text file (items.txt) that looks like this:
    item # description price(this line does not appear in the text file)
    001 shaving cream 400.00
    999 razors 30.00
    I need to load the item# and price from the text file into arrays(I have no clue how to use multi-dimensional arrays in java and would prefer not to)
    I need to search the arrays based on the values entered by the user (item # and quantity) calculate the total for that item then create a new text file which has each line item for that order in the form:
    item# quant price per item total(price per item*quant entered)
    also also I need to be able to display the four items listed above after each loop as well as all the previous item number and quantities they selected until they indicate they don't want to select anymore.
    I've been working on this for days and it seems like nothing I try works. My major problems are:
    1. I have no idea how to read the text file and load those 2 items into their respective arrays
    2. I can't seem to create a textfile that looks like text for the output file.
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.text.*;
    import java.util.Locale;
    public class arraySelection
        extends JApplet {
      //Initialize the applet
      private Container getContentPane=null;
      public void init() {
           String string_item, string_quantity;
           String output = "";
           String description= "";
           int counter= 0;
           int itemNumber= 0;
           double quantity = 0 ;
           double tax_rate=.07;
           double total= 0, price= 0;
           double tax, subtotal;
           double Pretotal= 0;
           double priceArray[] = {1, .5, 3.65, 0.02, 0.09};
           String descriptionArray[] = {"salt", "pepper", "paprika", "garlic", "thyme"};
         // create number format for currency in US dollar format
         NumberFormat moneyFormat = NumberFormat.getCurrencyInstance( Locale.US );
         //format to have the total with two digits precision
         DecimalFormat twoDigits = new DecimalFormat("0.00");
         //Jtextarea to display results
         JTextArea outputArea = new JTextArea ();
         // get applet's content pane
          Container container = getContentPane ();
          //attach output area to container
          container.add(outputArea);
         //set the first row of text for the output area
        output +=  "Invoice\nItem#\tDescription\tQuant@Price\t Line Total" + "\n";
        do //begin loop structure obtain input from user
               // obtain item number from user
               string_item = JOptionPane.showInputDialog(
                   "Please enter an item number 1, 2, 3, 4, or 5:");
               //obtain quantity of each item that user enter
               string_quantity = JOptionPane.showInputDialog("Enter the quantity:");
               // convert numbers from type String to Integer or Double
               itemNumber = Integer.parseInt(string_item);
               quantity = Double.parseDouble(string_quantity);
                 switch (itemNumber) {//Determine input from user to assign price and description
                    case 10: // user input item =10
                      price = priceArray[0];
                      description = descriptionArray[0];
                      break;
                    case 20: // user input item =20
                      price = priceArray [1];
                      description = descriptionArray[1];
                      break;
                    case 30: //user input item =30
                      price=priceArray[2];
                      description = descriptionArray[2];
                      break;
                    case 40: //user input item =40
                      price=priceArray[3];
                      description = descriptionArray[3];
                      break;
                    case 50: //user input item =50
                      price=priceArray[4];
                      description = descriptionArray[4];
                      break;
                    default: // user input item is not on the list
                    output += "Invalid value entered"+ "\n";
                    price=0;
                    description= "";
             //Calculates the total for each item number and stores it in subtotal
             subtotal = price * quantity;
             //display input from user
             output += itemNumber + "\t" + description + "\t\t"+ quantity + "@" +
                       moneyFormat.format( price) + "\t" + moneyFormat.format( subtotal) + "\n";
             //accumulates the overall subtotal for all items
             Pretotal = Pretotal + subtotal;
            //verifies that the user wants to stop entering data
            string_item = JOptionPane.showInputDialog(" Enter a positive integer to continue or 0 to stop. ");
            itemNumber = Integer.parseInt(string_item);
          // loop termination condition if user's input is 0 .It will end the loop
       } while ( itemNumber!= 0);
        tax = Pretotal * tax_rate; // calculate tax amount
        total = Pretotal + tax; //calculate total = subtotal + tax
        //appends data regarding the subtotal, tax, and total to the output area
        output += "\n" + "Order Subtotal" + "\t" + moneyFormat.format( Pretotal) +
                  "\n" + "Tax" + "\t\t" + twoDigits.format( tax ) + "\n" + "Order Total" +
                  "\t\t" + moneyFormat.format( total );
         //attaches the data in the output variable to the output area
         outputArea.setText( output );
      } //end init
    }// end applet InvoiceAny help or sugestions would be greatly appreaciated. I've been working on this for over a week and everything I try goes nowhere.

    First answer: You shouldn't ask multiple questions in the same thread. Ask a specific question, with an appropriate subject line (optionally, assign the number of Dukes you are willing to give for the help). When question #1 is answered and question #2 arises, it's time for a new thread (don't forget to give out Dukes before moving on).
    Second answer: I think you need a Transfer Object (http://java.sun.com/blueprints/patterns/TransferObject.html). It's whole purpose is to hold/transfer instance data where it is needed. Create a class something like this:
    public class ItemTO
        private String _number;
        private String _description;
        private double _price;
        public ItemTO( String number, String description, double price )
            _number = number;
            _description = description;
            _price = price
        // Getter/Setter methods go here
    }then, in the code where you read in the file do something like this:
    BufferedReader input = null;
    try
        input  = new BufferedReader( new FileReader( "c:\\a.txt" ) );
        List items = new ArrayList();
        String line;
        String itemNumber;
        String itemDescription;
        double itemPrice;
        while ( (line  = input.readLine() ) != null )
         System.out.println( line );
            itemNumber = // Parse it from line
            itemDescription // Parse it from line
            itemPrice = // Parse it from line
            items.add( new ItemTO( itemNumber, itemDescription, itemPrice ) );
    catch ( FileNotFoundException fnfe )
        fnfe.printStackTrace();
    catch ( IOException ioe )
        ioe.printStackTrace();
    finally
        try
            if ( input != null )
                input.close();
        catch ( Exception e )
            e.printStackTrace();
    }As for how to parse the line of the file, I'll leave that to you for now. Are the three values delimited with any special characters?
    jbisotti

  • Brand New to Java and Programming

    I'm brand new, ( RAW ) to software programming at this time. I'm starting from scratch, I work on a Help Desk for the government so I can perform some software functionality but nothing as far as programming.. I would like recommendations for someone starting out brand new.. Books to read (JAVA for Dummies?) any beginner courses? What steps would you take if you were starting out brand new as I am myself.. Thanks..
    PS, I plan on taking courses after I get the beginning stuff out of the way, just don't want to go in with no knowledge base..

    For a nice list of stock answers: The One to Torment Newbies with
    Sun's basic Java tutorial
    Sun's New To Java Center. Includes an overview of what Java is, instructions for setting up Java, an intro to programming (that includes links to the above tutorial or to parts of it), quizzes, a list of resources, and info on certification and courses.
    http://javaalmanac.com . A couple dozen code examples that supplement The Java Developers Almanac.
    jGuru. A general Java resource site. Includes FAQs, forums, courses, more.
    JavaRanch. To quote the tagline on their homepage: "a friendly place for Java greenhorns." FAQs, forums (moderated, I believe), sample code, all kinds of goodies for newbies. From what I've heard, they live up to the "friendly" claim.
    Bruce Eckel's Thinking in Java (Available online.)
    Joshua Bloch's Effective Java
    Bert Bates and Kathy Sierra's Head First Java.
    James Gosling's The Java Programming Language. Gosling is
    the creator of Java. It doesn't get much more authoritative than this.

  • New to Java and trying to make a game

    I'm really new to Java so please try not to roll over laughing at the following code. At the moment, as you can hopefully pick up from the code, i'm trying to get a shape(Polygon) to respond to keyboard events and i'm trying to make the object primarily respond to the cursor keys and to move the Polygon in the corresponding directions of the cursors. I'm stuck and i think i have initialised everything but i can't get the shape to move. I'm pretty sure i'm missing required code in the paint method.
    <code>
    import java.awt.*;
    import java.awt.Event.*;
    import java.applet.*;
    import java.io.*;
    public class PlodInvaders extends Applet implements Runnable {
    Point start, end, fire, shield, target;
    int co_x, x, y;
    int co_y;
    int current_x, current_y;
    char current_key;
    Font theFont;
    Thread th;
    Image ship;
    Polygon p;
    public void init() {
    setBackground(Color.black);
    // mouse co-oridnates
    co_x = this.size().width + 5;
    co_y = this.size().height + 5;
    theFont= new Font("Courier", Font.BOLD, 24);
    current_x = 150;
    current_y = 100;
    public void start() {
    th = new Thread(this);
    th.start();
    public boolean KeyDown(Event evt, int key) {
    switch(key) {
    case Event.LEFT: current_x = current_x - 10; break;
    case Event.RIGHT: current_x = current_x +10; break;
    case Event.UP: current_y = current_y + 10; break;
    case Event.DOWN: current_y = current_y - 10; break;
    default: current_key = (char) key;
    start = new Point(x, y);
    repaint();
    return true;
    public boolean MouseDown(Event evt, int x, int y) {
    fire = new Point(x, y);
    return true;
    public boolean MouseUp(Event evt, int x, int y) {
    target = new Point(x, y);
    repaint();
    return true;
    public void run() {
    public void paint(Graphics g){
    Polygon p = new Polygon();
    g.setColor(Color.white);
    p.addPoint(20,20);
    p.addPoint(50,25);
    p.addPoint(50,50);
    p.addPoint(25,50);
    p.addPoint(20,20);
    g.fillPolygon(p);
    </code>

    this is not prefect and it is not a applet, but it will make you start. you can email if you have any qeustions
    import java.awt.*;
    import java.awt.event.*;
    public class MoveP extends Frame implements KeyListener
         Polygon po = new Polygon();
            int ix=0;
         int iy=0;
    public MoveP()  
         addWindowListener(new WindowAdapter()
        {     public void windowClosing(WindowEvent ev)
              {     dispose();
                   System.exit(0);
         addKeyListener(this);
         setSize(300,372);
         po.addPoint(20,20);
         po.addPoint(50,25);
         po.addPoint(50,50);
         po.addPoint(25,50);
         po.addPoint(20,20);
         setVisible(true); 
    public void paint(Graphics g)
         g.setColor(Color.black);
         for (int i=0; i < po.npoints; i++)
              po.xpoints[i]+=ix;
              po.ypoints[i]+=iy;
         g.fillPolygon(po);
    public void keyTyped(KeyEvent e)
    public void keyPressed(KeyEvent e)
         ix = 0;
         iy = 0;
         int k = e.getKeyCode();
         if (k == 40) iy++;
         if (k == 38) iy--;
         if (k == 39) ix++;
         if (k == 37) ix--;
         repaint();
    public void keyReleased(KeyEvent e)
    public static void main (String[] args)
         new MoveP();
          Noah

  • New to Java and stuck on alert ticker issue

    Hi, I'm a newbee so go easy on me. Here's the issue. The company I am interning for monitors its networks using a console called WhatsUp Gold. The program creates alerts to inform of any issues on the network or when thresholds are close to being reached. This is done using some form of Java which I can view by opening the source files. They have asked me to try and create a scrolling ticker that automatically updates in real time along with the WhatsUp program. I have downloaded INSCRO (a ticker creator) but when I try to direct the feed to the URL on WhatsUp, the ticker scrolls the Java script and not the text that I need it to. Any ideas on how to get it to pull the text vs the source file?
    Thanks in advance!

    First, you need to get straight the difference between Java and JavaScript. They're related only by having similar names. If you're doing "View Source" in a web browser, what you're seeing is JavaScript, NOT Java. If this is where your question lies, you need to find a JavaScript forum.

  • New to Java and already have difficulties

    Alright, I'm running under NetBeans IDE 4.0. I'm taking it through the quick start guide and am now having problems. I am down to the LibClass.java and Main.java. LibClass.java is done without problems that I can see. Main.java is telling me theres a problem in one of my lines.
    The Guide asked me to type in "String result = Li" and then hit "ctrl + space" to bring up code completion and look for LibClass which I cannot find, so I chose to finish the code myself and just typed "String result = LibClass and went on, but its telling me that the line is incorrect. Could anyone help me figure out why its telling me this?

    You know what? Don't touch Netbeans. Delete it and
    get UltraEdit or Textpad or whatever. And then read
    these and the following tutorials:
    http://java.sun.com/docs/books/tutorial/getStarted/cup
    ojava/index.htmlWhat Ceci is suggesting is that you are trying to learn the java language, but by using NetBeans (or any other IDE), you are facing two learning curves .... one for Java, and one for the IDE. This can be very confusing. Instead, use any text editor you are comfortable with, and compile using the command line compiler (javac). The tutorial for your operating system (most likely windows) will help you get started. That way, you are only struggling with learning Java.
    Rene, I hope I have interpreted your post into noobSpeak acceptably.
    � {�                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Help!! I am new to Java and just don't know enough to complete my project!!

    Hi, I need help! Below is listed my code for a bar code scanning project that my company has asked me to write. I want to read a barcode, make sure that it is not already in my file, if not in file write to file(this part works - the write to file), if in file pop up an error message. I am reading barcodes off pallets of boxes and need to reset the current pallet after it is complete but don't reset the total pallets until exit. Could you please look at my code -- the first half of the code is the GUI -- and make suggestions. My vectors are not working and I have not completed the error handeling. I need to finish by Friday. Tall order for someone who has only had the basics and this is my first project. Sorry I don't have any Duke dollars left -- so this one is for free.
    //-------------------Buffalo Offline Scan Program------------
    //This program will allow the Buffalo user to continue scanning cases on pallets
    //when the AS\400 is down. The scans will be sent to a flat file that will be
    //FTPed to the AS\400 when it is back up and update the proper files.
    //Program Author: Susan Riggin and Dean Smith
    //RFSS # 01080701
    package javalab;
    import javabook.*;
    import javalab.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.applet.*;
    import java.io.*;
    import java.io.File.*;
    import java.util.*;
    public class Bscan extends Applet implements ActionListener//, TextListener
    //               Data Members
         //Variables
         private int scanCount = 0;
         private int sessionCount = 0;
         //Labels
         private Label buffaloLabel = new Label();
         private Label scanLabel = new Label();
         private Label cPalletLabel = new Label();
         private Label cCountLabel = new Label();
         private Label tPalletLabel = new Label();
         private Label tCountLabel = new Label();
         private Label rButtonLabel = new Label();
         private Label eButtonLabel = new Label();
         private Label caseCountLabel = new Label();
         private Label pButtonLabel = new Label();
         private Label errorLabel = new Label();
         //TextFields
         private TextField scanTextField = new TextField();
         private TextField caseCount = new TextField("0");
         //Buttons
         private Button eButton = new Button("Exit");
         //Text Areas
         private TextArea cTextArea = new TextArea();
         private TextArea tTextArea = new TextArea();
         String scanText = scanTextField.getText();
         Vector v = new Vector(24,5);
         Vector v2 = new Vector(24,5);
    //               Constructor
    public Bscan()
         //Attach the GUI objects so they will appear on the screen.
         setLayout (null);
         buffaloLabel.setBounds(203, 5, 300, 27);
         buffaloLabel.setFont(new Font ("dialog",Font.BOLD, 18));
         buffaloLabel.setAlignment(Label.CENTER);
         buffaloLabel.setBackground(Color.red);
         buffaloLabel.setText("Buffalo OffLine Scan");
         cPalletLabel.setBounds(18, 60, 341, 23);
         cPalletLabel.setFont(new Font ("dialog", Font.BOLD, 14));
         cPalletLabel.setAlignment(Label.CENTER);
         cPalletLabel.setText("Current Pallet");
         cPalletLabel.setBackground(Color.cyan);
         tPalletLabel.setBounds(372, 62, 341, 23);
         tPalletLabel.setFont(new Font ("dialog", Font.BOLD, 14));
         tPalletLabel.setAlignment(Label.CENTER);
         tPalletLabel.setText("Total Pallets");
         tPalletLabel.setBackground(Color.yellow);
         eButton.setBounds(542, 485, 56, 23);
         eButton.setBackground(Color.yellow);
         eButton.setLabel("Exit");
         cCountLabel.setBounds(18, 88, 341, 23);
         cCountLabel.setFont(new Font("dialog", Font.BOLD, 12));
         cCountLabel.setAlignment(Label.CENTER);
         cCountLabel.setText("Current Pallet Case Count = " + scanCount);
         cCountLabel.setBackground(Color.lightGray);
         tCountLabel.setBounds(372, 88, 341, 23);
         tCountLabel.setFont(new Font("dialog", Font.BOLD, 12));
         tCountLabel.setAlignment(Label.CENTER);
         tCountLabel.setText("Total Pallet Case Count = " + sessionCount);
         tCountLabel.setBackground(Color.lightGray);
         scanLabel.setBounds(360, 33, 160, 23);
         scanLabel.setFont(new Font("dialog", Font.BOLD, 14));
         scanLabel.setBackground(Color.red);
         scanLabel.setAlignment(Label.CENTER);
         scanLabel.setText(" Current Barcode Scan: ");
         caseCountLabel.setBounds(18, 33, 200, 23);
         caseCountLabel.setFont(new Font("dialog", Font.BOLD, 14));
         caseCountLabel.setBackground(Color.red);
         caseCountLabel.setAlignment(Label.CENTER);
         caseCountLabel.setText("#Parts in Case:");
         caseCount.setBounds(250, 34, 58, 23);
         caseCount.setBackground(Color.white);
         scanTextField.setBounds(545, 34, 88, 23);
         scanTextField.setBackground(Color.white);
         eButtonLabel.setBounds(372, 460, 341, 23);
         eButtonLabel.setAlignment(Label.CENTER);
         eButtonLabel.setBackground(Color.yellow);
         eButtonLabel.setText("Press Exit to end Program.");
         rButtonLabel.setBounds(18, 460, 341, 23);
         rButtonLabel.setAlignment(Label.CENTER);
         rButtonLabel.setBackground(Color.cyan);
         rButtonLabel.setText("Scan Reset barcode for next pallet scan.");
         pButtonLabel.setBounds(200, 485, 315, 23);
         pButtonLabel.setAlignment(Label.CENTER);
         pButtonLabel.setFont(new Font ("dialog", Font.BOLD, 12));
         pButtonLabel.setBackground(Color.green);
         pButtonLabel.setText("Scan Partial Case Bar Code to enter correct # parts.");
         errorLabel.setBounds(18, 500, 682, 25);
         errorLabel.setAlignment(Label.CENTER);
         errorLabel.setFont(new Font ("dialog", Font.BOLD, 16));
         errorLabel.setBackground(Color.red);
         errorLabel.setText("Error - Barcode already scanned - scan next box!!!");
         cTextArea.setBounds(18, 118, 341, 333);
         cTextArea.setBackground(Color.cyan);
         tTextArea.setBounds(372, 118, 341, 333);
         tTextArea.setBackground(Color.yellow);
         //Place the GUI objects on the applet.
         add(buffaloLabel);
         add(scanLabel);
         add(cPalletLabel);
         add(cCountLabel);
         add(tCountLabel);
         add(tPalletLabel);
         add(cCountLabel);
         add(rButtonLabel);
         add(eButtonLabel);
         add(pButtonLabel);
         add(caseCountLabel);
         add(scanTextField);
         add(caseCount);
         add(eButton);
         add(cTextArea);
         add(tTextArea);
         //Add applet as an action listener.
         //caseCount.addTextListener(this);
         caseCount.addActionListener(this);
         scanTextField.addActionListener(this);
         eButton.addActionListener(this);
    //               Methods that make the program work
    //-------method adds the Abbott "A" and Buffalo to the screen--
         //Adds the Abbott "A" & Buffalo to the screen
         public void paint(Graphics g){
         Toolkit kit = Toolkit.getDefaultToolkit();
         Image imageA = kit.getImage("c:\\\\javaproj\\javalab\\abbott.gif");
         Image imageB = kit.getImage("c:\\\\javaproj\\javalab\\bison.gif");
         g.drawImage(imageA, 650, 5, 50, 50, this);
         g.drawImage(imageB, 713, 5, 50, 50, this);
    //---------method for action performed and action event---------
         public void actionPerformed(ActionEvent event)
         String scanText,caseb, cTime, cDate, pCount;
         scanText = scanTextField.getText();
         caseb = caseCount.getText();
         caseCount.setText("0");
         //tests the barcode to see if reset or count needed
         if (event.getSource() == eButton) exit();
         else     
         if (scanText.equals ("99999999999999")) reset();
         else
         if (scanText.equals ("88888888888888")) count();
         else
         checker();
         //scanText = scanTextField.getText();
         Clock myClock = new Clock();
         cTime = myClock.getCurrentTime();
         cDate = myClock.getCurrentDate();
         ++scanCount;
         ++sessionCount;
         pCount = caseb;
         File scan = new File ("\\\\beast2\\riggisl\\scan", "scan.txt");
         cTextArea.append(scanCount+"->"+scanText+" "+cDate+" "+cTime+" "+pCount);
         cCountLabel.setText("Current Pallet Case Count = " + scanCount);
         cTextArea.append("\r\n");
         tTextArea.append(sessionCount+"->"+scanText+" "+cDate+" "+cTime+" "+pCount );
         tCountLabel.setText("Total Pallet Case Count = " + sessionCount);
         tTextArea.append("\r\n");
         write();
         scanTextField.setText("");
    //-------------method for pressing the exit button---------------
         private void exit()
         v.clear();
         System.exit(0);
    //------------method for pressing the reset button---------------
         private void reset()
         scanCount = 0;
         scanTextField.setText("");
         cTextArea.setText("");
         cCountLabel.setText("Current Pallet Case Count = " + scanCount);
         scanTextField.requestFocus();
         v.clear();     
    //------------method for writing to the file---------------------
         private void write ()
         String cTime, cDate;
         Clock myClock = new Clock();
         cTime = myClock.getCurrentTime();
         cDate = myClock.getCurrentDate();
         String pCount = caseCount.getText();     
              try
         //FileWriter outputFile = new FileWriter("\\\\bfpscr01\\ftpdata\\scan\\scan.txt", true);
         //FileWriter outputFile = new FileWriter("c:\\\\javaproj\\javalab\\scan.txt", true);
         FileWriter outputFile = new FileWriter("\\\\beast2\\riggisl\\scan\\scan.txt", true);
         outputFile.write(scanTextField.getText());
         outputFile.write(myClock.getCurrentDate());
         outputFile.write(myClock.getCurrentTime());
         outputFile.write(pCount);
         outputFile.write("\r\n");
         outputFile.close();
    catch (IOException e)
         scanTextField.setText("");
    //               method for partial case count
         public void count()
         String caseb, scanText;
         caseCount.setText("");
         scanTextField.setText("");
         caseb = caseCount.getText();
         scanText = scanTextField.getText();
         checker();
    //               method for error
         public void error()
         add(errorLabel);
    //               method for checking barcode
         public void checker()
         String barcode = scanText;
         v.add(barcode);
         if(v == v2)
         error();
         else
         v2.add(barcode);
    }     

    I have a feeling you've already figured it out but I'll give a quick example. I didn't see where you're actually reading from the scan.txt file so I'm assuming that you're starting from scratch every time. It seems to me that you only need one Vector too - the one that contains all of the previously scanned codes.
    Let's rename v to scannedList.
    public void checker() {
      String barcode = scanText;
      if (scannedList.contains(barcode)) {
        error();
      else {
        scannedList.add(barcode);
        // write barcode to file
    }You might want to read the scan.txt file on program startup and fill the scannedList with the codes already there:
    Vector scannedList = new Vector();
    BufferedReader f = new BufferedReader(new FileReader("scan.txt"));
    String line;
    while ((line = f.readLine()) != null) {
      scannedList.add(line);
    f.close();

Maybe you are looking for