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.

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.

  • 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 an arrays program

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

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

  • Need Help With D&D Program

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

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

  • I need help with 2 arrays

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

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

  • Need help with my addressbook program

    hi,
    i need help with my program here. this one should works as:
    - saves user input into a txt file
    - displays name of the saved person on the jlist whenever i run the program
    - displays info about the person when clicked via textboxes given by reading the txt file where the user inputs are
    - should scroll when the list exceeds the listbox
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.JList;
    import java.awt.event.ActionListener;
    import java.io.*;
    import javax.swing.event.*;
    import java.io.FilterInputStream;
    public class AddressList extends JPanel implements ActionListener
         JTextField txt1 = new JTextField();
         JTextField txt2 = new JTextField();
         JTextField txt3 = new JTextField();
         DefaultListModel mdl = new DefaultListModel();
         JList list = new JList();
         JScrollPane listScroller = new JScrollPane(list);
         ListSelectionModel listSelectionModel;
         File fob = new File("Address3.txt");
         String name;
         char[] chars;     
         public void ListDisplay()
              try
                   RandomAccessFile rand = new RandomAccessFile(fob,"rw");
                   BufferedReader br = new BufferedReader(new FileReader("Address3.txt"));
                   if(fob.exists())
                         while((name = rand.readLine()) != null)
                              chars = name.toCharArray();
                              if(chars[0] == '*')
                                   mdl.addElement(name);
                                   list.setModel(mdl);
                              if(chars[0] == '#')
                                   continue;
                    else
                        System.out.println("No such file..");
              catch(IOException a)
                         System.out.println(a.getMessage());
         public AddressList()
              this.setLayout(null);
              listSelectionModel = list.getSelectionModel();
            listSelectionModel.addListSelectionListener(new ListInfo());
              list.setBounds(10,40,330,270);
              listScroller.setBounds(320,40,20,100);
              add(list);
              add(listScroller);
              JLabel lbl4 = new JLabel("Name: ");
              lbl4.setBounds(400,10,80,30);
              add(lbl4);
              JLabel lbl5 = new JLabel("Cellphone #: ");
              lbl5.setBounds(400,50,80,30);
              add(lbl5);
              JLabel lbl6 = new JLabel("Address: ");
              lbl6.setBounds(400,90,80,30);
              add(lbl6);
              JLabel lbl7 = new JLabel("List ");
              lbl7.setBounds(10,10,100,30);
              add(lbl7);
              txt1.setBounds(480,10,200,30);
              add(txt1);
              txt2.setBounds(480,50,200,30);
              add(txt2);
              txt3.setBounds(480,90,200,30);
              add(txt3);
              JButton btn1 = new JButton("Add");
              btn1.setBounds(480,130,100,30);
              btn1.addActionListener(this);
              btn1.setActionCommand("Add");
              add(btn1);
              JButton btn2 = new JButton("Save");
              btn2.setBounds(480,170,100,30);
              btn2.addActionListener(this);
              btn2.setActionCommand("Save");
              add(btn2);
              JButton btn3 = new JButton("Cancel");
              btn3.setBounds(480,210,100,30);
              btn3.addActionListener(this);
              btn3.setActionCommand("Cancel");
              add(btn3);
              JButton btn4 = new JButton("Close");
              btn4.setBounds(480,250,100,30);
              btn4.addActionListener(this);
              btn4.setActionCommand("Close");
              add(btn4);
         public static void main(String[]args)
              JFrame frm = new JFrame("Address List");
              AddressList panel = new AddressList();
              frm.getContentPane().add(panel,"Center");
              frm.setSize(700,350);
              frm.setVisible(true);
              panel.ListDisplay();
         public void actionPerformed(ActionEvent e)
              String cmd;
              cmd = e.getActionCommand();
              if(cmd.equals("Add"))
                   txt1.setText("");
                   txt2.setText("");
                   txt3.setText("");
              else if(cmd.equals("Save"))
                   mdl.addElement(txt1.getText());
                   list.setModel(mdl);
                   try
                   RandomAccessFile rand = new RandomAccessFile(fob,"rw");
                   BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
                   LineNumberReader line = new LineNumberReader(br);
                    if(fob.exists())
                              rand.seek(fob.length());
                              rand.writeBytes("* " + txt1.getText());
                              rand.writeBytes("\r\n" + "# " + txt2.getText());
                              rand.writeBytes("\r\n" + "# " + txt3.getText() + "\r\n");
                    else
                         System.out.println("No such file..");
                        txt1.setText("");
                        txt2.setText("");
                        txt3.setText("");
                    catch(IOException a)
                         System.out.println(a.getMessage());
              else if(cmd.equals("Cancel"))
                   txt1.setText("");
                   txt2.setText("");
                   txt3.setText("");
              else if(cmd.equals("Close"))
                   System.exit(0);
    class ListInfo implements ListSelectionListener
         public void valueChanged(ListSelectionEvent e)
              ListSelectionModel lsm = (ListSelectionModel)e.getSource();
              int minIndex = lsm.getMinSelectionIndex();
            int maxIndex = lsm.getMaxSelectionIndex();
              try //*this one should display the info of the person whenever i click the person's name at the list box via textbox.. but i cant seem to get it right since it always display the info of the first person inputed.. i tried to get the program to display them whenever it reads lines with * on them....
                   File fob = new File("Address3.txt");
                   RandomAccessFile rand = new RandomAccessFile(fob,"rw");
                   BufferedReader br = new BufferedReader(new FileReader("Address3.txt"));
                   LineNumberReader line = new LineNumberReader(br);
                   if(fob.exists())
                              for(int i = minIndex; i<=maxIndex; i++)
                                   if(lsm.isSelectedIndex(i))
                                        while((name = rand.readLine()) != null)
                                             chars = name.toCharArray();
                                             if(chars[0] == '#')
                                                  continue;
                                             if(chars[0] == '*')
                                                  txt1.setText(rand.readLine());
                                                 txt2.setText(rand.readLine());
                                                 txt3.setText(rand.readLine());
                    else
                              System.out.println("No such file..");
              catch(IOException a)
                         System.out.println(a.getMessage());
    }the only problem now is about how it should display the right info about the person whenever i click its name on the list.. something about file reading or something, i just cant figure it out.
    and also about how to make it scroll once it exceeds the list.. i cant make it work, maybe something about wrong declaration..
    thanks in advance..
    Edited by: syder on Mar 14, 2008 2:26 AM

    Like said before, do one thing at a time. At startup, something like:
    //put all the content in a list
    ArrayList<String> lines = new ArrayList<String>();
    while(String line=rand.readLine()!=null) {
        lines.add(line);
    }If you follow the good advice to create a class to encapsulate the entries, you could populate a list of such entries like this:
    static final int ENTRY_SIZE = 3;//you have 3 fields now, better to have a constant if that changes
    ArrayList<Entry> entries = new ArrayList<Entry>();
    for(int i=0; i<lines.size(); i+=ENTRY_SIZE) {
        Entry entry = new Entry(lines.get(i), lines.get(i+1), lines.get(i+2);
        entries.add(newEntry);
    }You could also do both of the above in one run, but I think you will understand better what's happening if you do one thing at a time.
    If you don't want to put the entries in an encapsulating class, you can still access this without looping:
    int listStartIdx = <desired_entry_index>*ENTRY_SIZE;
    String att1 = lines.get(listStartIdx).substring(1);
    String att2 = lines.get(listStartIdx+1).substring(1);
    String att3 = lines.get(listStartIdx+2).substring(1);

  • Need help with a rudimentary program

    I'm sort of new at this so i need help with a few things... I'm making a program to compile wages and i need answers with three things: a.) what are the error messages im getting meaning? b.) How can i calculate the state tax as 2% of my gross pay with the first $200 excluded and c.) how can i calculate the local tax as a flat $10 with $2 deducted for each dependant. any help is appreciated
    Here is what i have so far:
    public class WagesAsign1
              public static void main(String[] args)
                   int depend=4;
                   double hrsWork=40;
                   double payRate=15;
                   double grossPay;
                   grossPay=payRate*hrsWork;
                   double statePaid;
                   double stateTax=2.0;
                   statePaid=grossPay*(stateTax/100);
                   double localPaid;
                   double localTax=10.0;
                   localPaid=grossPay*(localTax/100);
                   double fedPaid;
                   double fedTax=10.0;
                   double taxIncome;
                   fedPaid=taxIncome*(fedTax/100);
                   taxIncome=grossPay-(statePaid+localPaid);
                   double takeHome;
                   System.out.println("Assignment 1 Matt Foraker\n");
                   System.out.println("Hours worked="+hrsWork+" Pay rate $"+payRate+" per/hour dependants: "+depend);
                   System.out.println("Gross Pay $"+grossPay+"\nState tax paid $"+statePaid+"\nLocal tax paid $"+localPaid+"\nFederal tax paid $"+fedPaid);
                   System.out.println("You take home a total of $"+takeHome);
    and these are the error messages so far:
    WagesAsign1.java:23: variable taxIncome might not have been initialized
                   fedPaid=taxIncome*(fedTax/100);
    ^
    WagesAsign1.java:29: variable takeHome might not have been initialized
                   System.out.println("You take home a total of $"+takeHome);
    ^

    edit: figured it out... please delete post
    Message was edited by:
    afroryan58

  • Hello guys need help with reverse array

    Need help reversing an array, i think my code is correct but it still does not work, so im thinking it might be something else i do not see.
    so far the input for the array is
    6, 25 , 10 , 5
    and output is still the same
    6 , 25 , 10 , 5
    not sure what is going on.
    public class Purse
        // max possible # of coins in a purse
        private static final int MAX = 10;
        private int contents[];
        private int count;      // count # of coins stored in contents[]
         * Constructor for objects of class Purse
        public Purse()
           contents = new int[MAX];
           count = 0;
         * Adds a coin to the end of a purse
         * @param  coinType     type of coin to add
        public void addCoin(int coinType)
            contents[count] = coinType;
            count = count + 1;
         * Generates a String that holds the contents of a purse
         * @return     the contents of the purse, nicely formatted
        public String toString()
            if (count == 0)
                return "()";
            StringBuffer s = new StringBuffer("(");
            int i = 0;
            for (i = 0; i < count - 1; ++i)
                s.append(contents[i] + ", "); // values neatly separated by commas
            s.append(contents[i] + ")");
            return s.toString();
         * Calculates the value of a purse
         * @return     value of the purse in cents
        public int value()
            int sum = 0; // starts sum at zero
            for( int e : contents) // sets all to e
                sum = sum + e; //finds sum of array
            return sum; //retur
         * Reverses the order of coins in a purse and returns it
        public void reverse()
           int countA = 0;
           int x = 0;
           int y = countA - 1;                                          // 5 - 1 = 4
           for (int i = contents.length - 1; i >=0 ; i--)                        // 4, 3 , 2, 1, 0
                countA++;                                             // count = 5
            while ( x < y)
                int temp = contents[x];
                contents[x] = contents [y];
                contents [y] = temp;
                y = y- 1;                                         // 4 , 3 , 2, 1 , 0
                x = x + 1 ;                                             // 0 , 1,  2  , 3 , 4
    }

    ok so i went ahead and followed what you said
    public void reverse()
          int a = 0;
          int b = contents.length - 1;
          while (b > a)
              int temp = contents[a];
              contents[a] = contents;
    contents [b] = temp;
    a++;
    b--;
    }and its outputting { 0, 0, 0, 0}
    im thinking this is because the main array is has 10 elements with only 4 in use so this is a partial array.
    Example
    the array is { 6, 25, 10, 5, 0, 0, 0, 0, 0, 0,}
    after the swap
    {0, 0 , 0 , 0, 0 , 0 , 5 , 10 , 25, 6}
    i need it to be just
    { 5, 10, 25, 6}
    so it is swapping the begining and end but only with zeroes the thing is i need to reverse the array without the zeroes                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Need Help With Simple ABAP Code

    Hello,
    I'm loading data from a DSO (ZDTBMAJ) to an Infocube (ZCBRAD06). I need help with ABAP code to some of the logic in Start Routine. DSO has 2 fields: ZOCTDLINX & ZOCBRDMAJ.
    1. Need to populate ZOCPRODCD & ZOCREFNUM fields in Infocube:
        Logic:-
        Lookup /BI0/PMATERIAL, if /BIC/ZOCBRDMAJ = /BIC/OIZOCBRDMAJ
        then /BIC/ZOCPRODCD = ZOCPRODCD in Infocube
               /BIC/ZOCREFNUM = ZOCREFNUM in Infocube         
    2. Need to populate 0G_CWWTER field in Infocube:
        Logic:
        Lookup /BIC/PZOCTDLINX, if /BIC/ZOCTDLINX = BIC/OIZOCTDLINX
        then G_CWWTER = 0G_CWWTER in Infocube.
    I would need to read single row at a time.
    Thanks!

    I resolved it.

  • Need help with accessing the program.

    I need help with accessing my adobe creative cloud on my windows 8.1 laptop. I have an account but do not have an app. I need this for my online classes. Please help!

    Link for Download & Install & Setup & Activation may help
    -Chat http://www.adobe.com/support/download-install/supportinfo/

  • Need help with spell checker program

    Hi
    I am writing a spell checker program and need help for a simple logic.I have "List" of correctly spelled words and a String array of wrong spelled words.How can I compare both and tell that for eg xyz word is not spelled correctly.

    BigDaddyLoveHandles wrote:
    To learn more about Map, take the collection tutorial: [http://java.sun.com/docs/books/tutorial/collections/index.html]
    (Actually, to me it sounds like you have a Set of correctly spelled words and another Set of words which may or may not be correctly spelled, and you want the difference...)That is what it sounds like to me also, and that is easy.
    JSG

  • Beginner needs help with simple code.

    I just statrted learnind java, and I need some help with this simple program. For some reason everytime I enter my Farenheit value, the Celsius conversion returns as 0.0. Would really appreciate the help. Thanks.
    Here's the code:
    public class TempConverter
    public static void main(String[] args)
    double F = Double.parseDouble(args[0]);
    System.out.println("Temperature in Farenheit is: " + F);
    double C = 5 / 9;
    C *= (F - 32);
    System.out.println("Temperature in Celsius is: " + C);
    }

    double C = 5 / 9This considers "5" and "9" to be integers and does an integer division, discarding the remainder. The result of that division is 0. Trydouble C = 5.0/9.0;

  • I need help with simple problems. im a student.

    i'd like to be advanced with my studies so i will post questions.. i need help on how to answer. thank you.
    1. create a java program that will evaluate if the value entered is a positive, negative, vowel, consonant and special characters.
    im actually done with the positive and negative using if else statements.. i used an integer data type. now my question is how do conjoin the characters when i need to evaluate a vowel and a consonant. i cant use char either. please help. i dont know what to do yet.
    2. create java program that will translate the input from numbers to words. e.g. input:123 output: one hundred twenty-three.
    i have an idea to use a switch case statement. but i have no idea on how will i be able to do it. so if you guys can help me.. well then thankies..

    Welcome to the Sun forums. First, please note that you have posted in the wrong forum. This forum is for topics related to Sun's JavaHelp product. You should post your questions in the New to Java forum.
    As part of your learning, you will have to develop the ability to select an approach to a problem, create a design that reflects that approach, and then implement the design with code that you create.
    So, it's inappropriate for us to take the problem statement that you have been given and short-circuit your learning process by giving you the implemented problem solution. We can comment on the individual questions that you may have, and point out problems and errors that we see in the code that you develop.
    As a hint, when you are stuck, forget about Java and programming. Just start with a sheet of paper and a pencil, and figure out how to layout the task on paper. The consider how to translate that to programming.
    If you have problems, post short example code that shows the problem, and explain your question clearly. We can't read minds.
    Make sure you post code correctly so that it's not mangled by the forum software, and so that formatting is maintained. Select your typed or pasted code block and press the CODE button above the typing area.

  • Help with an array program

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

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

Maybe you are looking for

  • T.code for GL Open Items clearing

    Hi all,, Can anyone give the the tcode for clearing the Open items of a GL which is maintained in OIM...!? BR..AJ

  • Ipad mini (retina) goes wild ! can't type, lot of screen movement

    My screen seems to be to responsive, even when set on table the screen moves like crazy seems as if even moving a hand over the screen sets it off. if i try to type a message it'll give a lot of wrong characters. Turning wifi, bluetooth and so off do

  • Rounding off to 2 decimal places

    Hi, I use "Double" for my calculations and since I am working with $$ ;-) I need to round it off at 2 decimal places. Any quick way to do this? or do I have to write some major code for that? Thanks

  • JDeveloper documentation concern

    Hi, I'm trying to become a java certified programmer, and I had discovered sun java documentation is a mess, you can't compare against oracle documentation for eaxmple, once I finally found it, because it wasn't so easy, the problem I have is you can

  • Help Needed !! Urgent. Read .txt using j2me.

    Hi, I need to read this field; Server IP Address = 192.122.139.16* BT Addr & Port No. = 000B0D182EDA:1* Help IP Address = 192.168.0.100:3334* is there any easy coding which can help me to read all the fields above using j2me? I am using BufferedReade