Help with simple programming

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

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

Similar Messages

  • URL: newbie needs help with simple programming question!

    Hi everyone,
    Please direct me to a FAQ or other resource, or help me with this problem:
    I want to create a text field (or similar container) that contains both ordinary text AND a URL/hyperlink in it. For example, the following text might appear in the text field:
    "I have many _pictures_ from my vacation"
    where the word "pictures" is actually a hyperlink to a web site, and the other portions of the string are simple text.
    All advice and help is appreciated!
    -Dennis Reda
    [email protected]

    Well here is one way you code do it but if you do alittle research on them links above it will explain how this code works.Well it will explain how jeditorpane and hyperlinklistener work
    import javax.swing.*;
    import java.awt.*;
    import javax.swing.event.*;
    import java.net.*;
    public class b extends javax.swing.JApplet implements HyperlinkListener  {
       JEditorPane field = new JEditorPane();
      public b() {
        Container pane = getContentPane();
        FlowLayout flo = new FlowLayout();
        pane.setLayout(flo);
        field.setPreferredSize(new Dimension(200, 25));
        field.setEditable(false);
        pane.add(field);
        setContentPane(pane);
         String gg1 = "<html><body>I have many_<a    href='http://www.home.com'>pictures</a>_from my vacation</body></html>";
         field.addHyperlinkListener(this);
         field.setContentType("text/html");
         field.setText(gg1);
      public void hyperlinkUpdate(HyperlinkEvent e) {
         if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
          try{
            URL url = new URL("http://www.msn.com");
            getAppletContext().showDocument(url,"_self"); 
            }catch(Exception r) {};
      public void init()  {
         b c = new b();
    ps hope this helped                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Help with simple program

    I am trying to get a program in my CS1 course and am having a hard time, help.. this is what the prof wants>>> Your employer is developing encryption software and wants you to write a Java program that will display all the prime numbers less than N, where N is a number to be entered by a user. In addition to displaying the primes themselves, provide a count of how many there are.

    here is one that i wrote. It does not add them though:
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    class FindPrimes extends JFrame implements Runnable, ActionListener {
         Thread go;
         JLabel howManyLabel = new JLabel("Quantity: ");
         JTextField howMany = new JTextField("400", 10);
         JButton display = new JButton("Display primes");
         JTextArea primes = new JTextArea(8, 40);
         FindPrimes() {
              super("Find Prime Numbers");
              setSize(400, 300);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              BorderLayout bord = new BorderLayout();
              setLayout(bord);
              display.addActionListener(this);
              JPanel topPanel = new JPanel();
              topPanel.add(howManyLabel);
              topPanel.add(howMany);
              topPanel.add(display);
              add(topPanel, BorderLayout.NORTH);
              primes.setLineWrap(true);
              JScrollPane textPane = new JScrollPane(primes);
              add(textPane, BorderLayout.CENTER);
              setVisible(true);
         public void actionPerformed(ActionEvent evt) {
              display.setEnabled(false);
              if (go == null) {
                   go = new Thread(this);
                   go.start();
         public void run() {
              int quantity = Integer.parseInt(howMany.getText());
              int numPrimes = 0;
              // candidate:  the number that might be prime
              int candidate = 2;
              primes.append("First " + quantity + " primes:");
              while (numPrimes < quantity) {
                   if (isPrime(candidate)) {
                        primes.append(candidate + " ");
                        numPrimes++;
                   candidate++;
         public static boolean isPrime(int checkNumber) {
              double root = Math.sqrt(checkNumber);
              for (int i = 2; i <= root; i++) {
                   if (checkNumber % i == 0) {
                        return false;
              return true;
         public static void main(String[] arguments) {
              FindPrimes fp = new FindPrimes();
    }

  • Help with simple program please!

    Hi. I am brand new to Java and pretty new to programming in general. I am writing a project for a class where we have to output the index at which a certain "target" string matches the "source" string. I'm stuck. I thought my code would make "compare" a string of length target.length()? Any help is greatly appreciated. Thanks!
    public static ArrayList<Integer> matches(String source, String target) {
    // check preconditions
    assert (source != null) && (source.length() > 0)
         && (target != null) && (target.length() > 0): "matches: violation of precondition";
    ArrayList<Integer> result = new ArrayList<Integer>();
    String compare = "";
    for (int i=0; i<source.length()-target.length()+1;i++){
         int count = 0;
         for (int k=i; k<i+target.length(); k++){
              compare = compare + source.charAt(k);
         for (int j=0; j<target.length(); j++){
              if (target.charAt(j) == compare.charAt(j)){
                   count ++;
         if (count == target.length()){
              result.add(i);
              return result;
    }

    I apologize, I am new to the forums and posted that code horribly. Here is the accurate code.
        public static ArrayList<Integer> matches(String source, String target) {
            // check preconditions
            assert (source != null) && (source.length() > 0)
                 && (target != null) && (target.length() > 0): "matches: violation of precondition";
            ArrayList<Integer> result = new ArrayList<Integer>();
            String compare = "";
            for (int i=0; i<source.length()-target.length()+1;i++){
                 int count = 0;
                 for (int k=i; k<i+target.length(); k++){
                      compare = compare + source.charAt(k);
                 for (int j=0; j<target.length(); j++){
                      if (target.charAt(j) == compare.charAt(j)){
                           count ++;
                 if (count == target.length()){
                      result.add(i);
              return result;
        }

  • Hi need help with simple program

    1 System.out.println("Input Number of Question: ");
    2
         3     inputQuestionNum = Integer.parseInt(input.nextLine());
              4     
              5     if(inputQuestionNum>=10) {
              6          System.out.println("Error: Please try again"); //how to return to line 1      
    7 else { 
    8      System.out.println("ok");     
    9 }
    Hi, i am new to java, how to make the program return back to first line when input is more then 10? I do not know how to describe my problem therefore i can't google for solution. thank you in advance.

    The usual approach is to use a do-while loop:Scanner input = new Scanner (System.in);
    int inputQuestionNum;
    do {
        System.out.println ("Input Number of Question: ");
        inputQuestionNum = Integer.parseInt (input.nextLine ());
        if (inputQuestionNum >= 10) {
            System.out.println ("Error: Please try again");
        } else {
                System.out.println ("ok");
        } while (inputQuestionNum >= 10);Ask if that's not clear.
    db

  • Need help with simple program

    I believe that I have everything right except when I get down to the else I want it to return to the while loop. Is there a better way of doing this because it doesn't work for me. Here is the program:
    public class ABCInput
         public static void main(String[] args) throws Exception
              char response;
              System.out.println("Please type a A,B,C to receive a message or a Q to quit");
              response = (char)System.in.read();System.in.read();System.in.read();
              while(response == 'A' || response == 'B' || response == 'C')
                   System.out.println("\"Good Job\"\n\n");
                   System.out.println("Please type a A,B,C to receive a message or a Q to quit");
                   response = (char)System.in.read();System.in.read();System.in.read();
              if(response == 'Q')
                   System.out.println("Thanks for playing");
                   System.exit(0);
              else
                   System.out.println("You have entered an invalid letter. Please try again");
                   response = (char)System.in.read();System.in.read();System.in.read();
    }

    mahugl,
    Try this out.
    public class ABCInput
         public static void main(String[] args) throws Exception
              char response;
              boolean notInvalid = true;
              boolean notFinished = true;
              System.out.println("Please type a A,B,C to receive a message or a Q to quit");
              response = (char)System.in.read();System.in.read();System.in.read();
              while(notFinished == true)
                   while(notInvalid == true)
                        if(response == 'A' || response == 'B' || response == 'C' || response == 'Q' || response == 'a' || response == 'b' || response == 'c' || response == 'q')
                             notInvalid = false;
                        else
                             System.out.println("You have entered an invalid letter. Please try again");
                             response = (char)System.in.read();System.in.read();System.in.read();
                   if(response == 'Q' || response == 'q')
                        notFinished = false;
                   else
                        System.out.println("\"Good Job\"\n\n");
                        System.out.println("Please type a A,B,C to receive a message or a Q to quit");
                        response = (char)System.in.read();System.in.read();System.in.read();
                        notInvalid = true;
              System.out.println("Thanks for playing");
              System.exit(0);
    }jerryrika

  • Help with Paint program.

    Hello. I am somewhat new to Java and I was recently assigned to do a simple paint program. I have had no trouble up until my class started getting into the graphical functions of Java. I need help with my program. I am supposed to start off with a program that draws lines and changes a minimum of 5 colors. I have the line function done but my color change boxes do not work and I am able to draw inside the box that is supposed to be reserved for color buttons. Here is my code so far:
    // Lab13110.java
    // The Lab13 program assignment is open ended.
    // There is no provided student version for starting, nor are there
    // any files with solutions for the different point versions.
    // Check the Lab assignment document for additional details.
    import java.applet.Applet;
    import java.awt.*;
    public class Lab13110 extends Applet
         int[] startX,startY,endX,endY;
         int currentStartX,currentStartY,currentEndX,currentEndY;
         int lineCount;
         Rectangle red, green, blue, yellow, black;
         int numColor;
         Image virtualMem;
         Graphics gBuffer;
         int rectheight,rectwidth;
         public void init()
              startX = new int[100];
              startY = new int[100];
              endX = new int[100];
              endY = new int[100];
              lineCount = 0;
              red = new Rectangle(50,100,25,25);
              green = new Rectangle(50,125,25,25);
              blue = new Rectangle(50,150,25,25);
              yellow = new Rectangle(25,112,25,25);
              black = new Rectangle(25,137,25,25);
              numColor = 0;
              virtualMem = createImage(100,600);
              gBuffer = virtualMem.getGraphics();
              gBuffer.drawRect(0,0,100,600);
         public void paint(Graphics g)
              for (int k = 0; k < lineCount; k++)
                   g.drawLine(startX[k],startY[k],endX[k],endY[k]);
              g.drawLine(currentStartX,currentStartY,currentEndX,currentEndY);
              g.setColor(Color.red);
              g.fillRect(50,100,25,25);
              g.setColor(Color.green);
              g.fillRect(50,125,25,25);
              g.setColor(Color.blue);
              g.fillRect(50,150,25,25);
              g.setColor(Color.yellow);
              g.fillRect(25,112,25,25);
              g.setColor(Color.black);
              g.fillRect(25,137,25,25);
              switch (numColor)
                   case 1:
                        g.setColor(Color.red);
                        break;
                   case 2:
                        g.setColor(Color.green);
                        break;
                   case 3:
                        g.setColor(Color.blue);
                        break;
                   case 4:
                        g.setColor(Color.yellow);
                        break;
                   case 5:
                        g.setColor(Color.black);
                        break;
                   case 6:
                        g.setColor(Color.black);
                        break;
              g.setColor(Color.black);
              g.drawRect(0,0,100,575);
         public boolean mouseDown(Event e, int x, int y)
              currentStartX = x;
              currentStartY = y;
              if(red.inside(x,y))
                   numColor = 1;
              else if(green.inside(x,y))
                   numColor = 2;
              else if(blue.inside(x,y))
                   numColor = 3;
              else if(yellow.inside(x,y))
                   numColor = 4;
              else if(black.inside(x,y))
                   numColor = 5;
              else
                   numColor = 6;
              repaint();
              return true;
         public boolean mouseDrag(Event e, int x, int y)
              int Rectheight = 500;
              int Rectwidth = 900;
              currentEndX = x;
              currentEndY = y;
              Rectangle window = new Rectangle(0,0,900,500);
              //if (window.inside(Rectheight,Rectwidth))
                   repaint();
              return true;
         public boolean mouseUp(Event e, int x, int y)
              int Rectheight = 500;
              int Rectwidth = 900;
              startX[lineCount] = currentStartX;
              startY[lineCount] = currentStartY;
              endX[lineCount] = x;
              endY[lineCount] = y;
              lineCount++;
              Rectangle window = new Rectangle(0,0,900,500);
              if (window.inside(Rectheight,Rectwidth))
                   repaint();
              return true;
         public void Rectangle(Graphics g, int x, int y)
              g.setColor(Color.white);
              Rectangle screen = new Rectangle(100,0,900,600);
    }If anyone could point me in the right direction of how to go about getting my buttons to work and fixing the button box, I would be greatly appreciative. I just need to get a little bit of advice and I think I should be good after I get this going.
    Thanks.

    This isn't in any way a complete solution, but I'm posting code for a mouse drag outliner. This may be preferable to how you are doing rectangles right now
    you are welcome to use and modify this code but please do not change the package and make sure that you tell your teacher where you got it from
    MouseDragOutliner.java
    package tjacobs.ui;
    import java.awt.BasicStroke;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Container;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Point;
    import java.awt.Stroke;
    import java.awt.event.*;
    import java.util.ArrayList;
    import java.util.Iterator;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.SwingUtilities;
    * See the public static method addAMouseDragOutliner
    public class MouseDragOutliner extends MouseAdapter implements MouseMotionListener {
         public static final BasicStroke DASH_STROKE = new BasicStroke(1.0f, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_BEVEL, 10.0f, new float[] {8, 8}, 0);
         private boolean mUseMove = false;
         private Point mStart;
         private Point mEnd;
         private Component mComponent;
         private MyRunnable mRunner= new MyRunnable();
         private ArrayList mListeners = new ArrayList(1);
         public MouseDragOutliner() {
              super();
         public MouseDragOutliner(boolean useMove) {
              this();
              mUseMove = useMove;
         public void mouseDragged(MouseEvent me) {
              doMouseDragged(me);
         public void mousePressed(MouseEvent me) {
              mStart = me.getPoint();
         public void mouseEntered(MouseEvent me) {
              mStart = me.getPoint();
         public void mouseReleased(MouseEvent me) {
              Iterator i = mListeners.iterator();
              Point end = me.getPoint();
              while (i.hasNext()) {
                   ((OutlineListener)i.next()).mouseDragEnded(mStart, end);
              //mStart = null;
         public void mouseMoved(MouseEvent me) {
              if (mUseMove) {
                   doMouseDragged(me);
         public     void addOutlineListener(OutlineListener ol) {
              mListeners.add(ol);
         public void removeOutlineListener(OutlineListener ol) {
              mListeners.remove(ol);
         private class MyRunnable implements Runnable {
              public void run() {
                   Graphics g = mComponent.getGraphics();
                   if (g == null) {
                        return;
                   Graphics2D g2 = (Graphics2D) g;
                   Stroke s = g2.getStroke();
                   g2.setStroke(DASH_STROKE);
                   int x = Math.min(mStart.x, mEnd.x);
                   int y = Math.min(mStart.y, mEnd.y);
                   int w = Math.abs(mEnd.x - mStart.x);
                   int h = Math.abs(mEnd.y - mStart.y);
                   g2.setXORMode(Color.WHITE);
                   g2.drawRect(x, y, w, h);
                   g2.setStroke(s);
         public void doMouseDragged(MouseEvent me) {
              mEnd = me.getPoint();
              if (mStart != null) {
                   mComponent = me.getComponent();
                   mComponent.repaint();
                   SwingUtilities.invokeLater(mRunner);
         public static MouseDragOutliner addAMouseDragOutliner(Component c) {
              MouseDragOutliner mdo = new MouseDragOutliner();
              c.addMouseListener(mdo);
              c.addMouseMotionListener(mdo);
              return mdo;
         public static interface OutlineListener {
              public void mouseDragEnded(Point start, Point finish);
         public static void main(String[] args) {
              JFrame f = new JFrame("MouseDragOutliner Test");
              Container c = f.getContentPane();
              JPanel p = new JPanel();
              //p.setBackground(Color.BLACK);
              c.add(p);
              addAMouseDragOutliner(p);
              f.setBounds(200, 200, 400, 400);
              f.addWindowListener(new WindowClosingActions.Exit());
              f.setVisible(true);
    }

  • Please help me with simple program

    Can someone please write a simple program for me that opens up a webpage in the center of the screen , with a set size, and then asks the user where they would like to click on the screen. Then once the person clicks it asks how many times they would like to click there, and then once they enter the # the program opens up the webpage (in the center at the same spot as before, with the same set size) and automatically clicks on the predesignated spot , and then closes all open internet windows, and keeps doing it for however many times the person chose. PLEASE HELP ME WITH THIS!!! If you could, please post the source code here. Thank you so much to whoever helps me!!!!!!!

    If it's not to learn, then what is the purpose of
    this project?well, if it's not HW and its not for learning java, then why the hell would anyone like to have a program that may open a webpage and then repeatedly click on predefined place...
    let me see...
    now if he had asked for program that fakes IP as well, then i would suggest that he tryes to generate unique clicks, but now... i'm not sure... maybe just voting in some polls or smthing... though, i would not create a program that clicks on the link or form element, but rather just reload url with given parameters for N times...

  • Need Help with Simple Chat Program

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

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

  • Need Help with simple array program!

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

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

  • Help with pathfinding program

    hi,
    i study java at school and i need help with my project.
    im doing a simple demonstration of a pathfinding program whose algoritm i read off Wikipedia (http://en.wikipedia.org/wiki/Pathfinding)where the co-ordinates of the start and end points
    are entered and the route is calculated as a list of co-ordinates. Here is the section of code i am having trouble with-
    void find_path(int x,int y,int p,int q)
    int t1;int t2;
    int temp_pool[][]=new int[4][3];//stores contagious cells of elements in grid pool
    int grid_pool[][]= new int[100000][3];
    int pass_pool[][]=new int[4][3];//stores the pool of squares which can be added to the list of direction
    int path[][]= new int[10000][3];//stores actual path
    int count=1;int note=10;int kk=0;
    int curx,cury;
    //the above arrays contain 3 columns - to store x and y co-ordinate and a counter variable(the purpose of which will become clear later)
    grid_pool[0][0]=p;
    grid_pool[0][1]=q;
    grid_pool[0][2]=0;
    int counter=grid_pool[0][2];
    for(int i=0;i<=100;i++)
    counter++;
    curx=grid_pool[0];
    cury=grid_pool[i][1];
    temp_pool[0][0]=curx-1;
    temp_pool[0][1]=cury;
    temp_pool[0][2]=counter;
    temp_pool[0][0]=curx;
    temp_pool[0][1]=cury-1;
    temp_pool[0][2]=counter;
    temp_pool[0][0]=curx+1;
    temp_pool[0][1]=cury;
    temp_pool[0][2]=counter;
    temp_pool[0][0]=curx;
    temp_pool[0][1]=cury+1;
    temp_pool[0][2]=counter;
    int pass=0;
    for(int j=0;j<=3;j++)
    int check=0;
    int in=temp_pool[j][0];
    int to=temp_pool[j][1];
    if(activemap[in][to]=='X')
    {check++;}
    if(linear_search(grid_pool,in,to)==false)
    {check++;}
    if(check==2)
    pass_pool[pass][0]=in;
    pass_pool[pass][1]=to;
    pass++;
    }//finding which co-ordinates are not walls and which are not already present
    for(int k=0;k<=pass_pool.length-1;k++)
    grid_pool[count][0]=pass_pool[k][0];
    grid_pool[count][1]=pass_pool[k][1];
    count++;
    if(linear_search(grid_pool,x,y)==true)
    break;
    //in this part we have isolated the squares which run in the approximate direction of the goal
    //in the next part we will isolate the exact co-ordinates in another array called path
    int yalt=linear_searchwindex(grid_pool,p,q);
    t1=grid_pool[yalt][2];
    int g1;int g2;int g3;
    for(int u=yalt;u>=0;u--)
    g3=find_next(grid_pool,p,q);
    g2=g3/10;
    g1=g3%10;
    path[0]=g2;
    path[u][1]=g3;
    path[u][2]=u;
    for(int v=0;v<=yalt;v++)
    System.out.println(path[v][0]+','+path[v][1]);
    ill be grateful if anyone can fix it. im done with the rest though

    death_star12 wrote:
    hi,
    i study java at school and i need help with my project.
    im doing a simple demonstration of a pathfinding program whose algoritm i read off Wikipedia (http://en.wikipedia.org/wiki/Pathfinding)where the co-ordinates of the start and end points
    are entered and the route is calculated as a list of co-ordinates. Here is the section of code i am having trouble with-
    ...The part "i am having trouble with" means absolutely nothing to the people who are answering questions here. It's like going to the doctor with a broken rib and just saying "doc, I don't feel so well". Get my point?
    Also, please take the trouble to properly spell words and use a bit of capitalization. Your question is hard to read as it is, which will most probably cause (some) people not to help you. And lastly, please use code tags when posting code: it makes it so much easier to read (see: [Formatting Messages|http://mediacast.sun.com/users/humanlever/media/forums_text_editor.mp4]).
    Thanks.

  • Help with a Program I am writing!  Please!

    Hello All,
    This is my first post...I hope to find some answers to my program I am writing! A couple things first - I am 17, and have designed a comp. science class for myself to take while a senior in high school, since there was not one offered. My end of the 2nd term project is to write a program that encompasses the information I have learned about for the past two terms. I know the very basics, if that. Please help!
    My program involves the simple dice throwing program, 'Dice Thrower' by Kevin Boone. The full text/program write out can be found at:
    http://www.kevinboone.com/PF_DiceThrower-java.html
    I am hoping to add a part to this program that basically tells the program if the dice show doubles, pop up a little GUI window that says "You are a Winner! You Got Doubles!"
    I was thinking as I finished chapter 7 in my text book, that either an 'if/else' or 'switch' statement might be the right place to start.
    Could someone please write me a start to the program text that I need to add to 'Dice Thrower', or explain what I need to do to get started! Thank you so much, I really appreciate it.
    Erick DeVore - Eroved Kcire

    import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.JLabel;
    import javax.swing.JFrame;
    import java.awt.FlowLayout;
    import java.awt.Color;
    public class DiceThrower extends Applet
    Die die1;
    Die die2;
    public void paint (Graphics g)
         die1.draw(g);
         die2.draw(g);
         g.drawString ("Click mouse anywhere", 55, 140);
         g.drawString ("to throw dice again", 65, 160);
    public void init()
         die1 = new Die();
         die2 = new Die();
         die1.setTopLeftPosition(20, 20);
         die2.setTopLeftPosition(150, 20);
         throwBothDice();
         // Erick's Program Insert below
         public class WinnerGui extends JFrame;
      public WinnerGui();
        super ("You Are The Winner with GUI");
        Container c = getContentPane();
        c.setBackground(Color.lightGray);
        c.setLayout(new FlowLayout());
        c.add(new JLabel("You're a Winner! You Got Doubles!"));
            //End Erick's Program insert
         DiceThrowerMouseListener diceThrowerMouseListener =
              new DiceThrowerMouseListener();
         diceThrowerMouseListener.setDiceThrower(this);
         addMouseListener(diceThrowerMouseListener);
    public void throwBothDice();
         die1.throwDie();
         die2.throwDie();
         repaint();
    class Die
    int topLeftX;
    int topLeftY;
    int numberShowing = 6;
    final int spotPositionsX[] = {0, 60,  0, 30, 60,  0,  60};
    final int spotPositionsY[] = {0,  0, 30, 30, 30,  60, 60};
    public void setTopLeftPosition(final int _topLeftX, final int _topLeftY)
         topLeftX = _topLeftX;
         topLeftY = _topLeftY;
    public void throwDie()
         numberShowing = (int)(Math.random() * 6 + 1);
    public void draw(Graphics g)
         switch(numberShowing)
              case 1:
                   drawSpot(g, 3);
                   break;
              case 2:
                   drawSpot(g, 0);
                   drawSpot(g, 6);
                   break;
              case 3:
                   drawSpot(g, 0);
                   drawSpot(g, 3);
                   drawSpot(g, 6);
                   break;
              case 4:
                   drawSpot(g, 0);
                   drawSpot(g, 1);
                   drawSpot(g, 5);
                   drawSpot(g, 6);
                   break;
              case 5:
                   drawSpot(g, 0);
                   drawSpot(g, 1);
                   drawSpot(g, 3);
                   drawSpot(g, 5);
                   drawSpot(g, 6);
                   break;
              case 6:
                   drawSpot(g, 0);
                   drawSpot(g, 1);
                   drawSpot(g, 2);
                   drawSpot(g, 4);
                   drawSpot(g, 5);
                   drawSpot(g, 6);
                   break;
    void drawSpot(Graphics g, final int spotNumber)
         g.fillOval(topLeftX + spotPositionsX[spotNumber],
              topLeftY + spotPositionsY[spotNumber], 20, 20);
    class DiceThrowerMouseListener extends MouseAdapter
    DiceThrower diceThrower;
    public void mouseClicked (MouseEvent e)
         diceThrower.throwBothDice();
    public void setDiceThrower(DiceThrower _diceThrower)
         diceThrower = _diceThrower;
    }That was what I have dwindled it down to, using my knowledge, as well as others' expertise...however I am listening to what you say, and get these messages when I try to compile in the CMD:
    line 63 - illegal start of expression (carrot at p in public)
    line 63 - ; expected (carrot at c in class)
    line 63 - { expected (carrot at ; at end of line)
    line 65 - illegal start of expression (carrot at p in public)
    line 83 - <identifier> expected (carrot as: (this) ) -- I don't even know what that means ^
    line 84 - invalid method declaration; return type required (carrot at a in add)
    line 84 - <identifier> expected (carrot like this: [see below])
    addMouseListener(diceThrowerMouseListener);
    ^
    line 84 - ) expected (carrot is one place over from previous spot [see above]
    line 93 - illegal start of expression (carrot at p in public)
    I know this seems like a lot of errors, but believe it or not, I actually had it up in the high teens and was able to fix some of them myself from going by previous examples, as well as looking things up in my text book. If anyone has any suggestions concerning the syntax errors of the code, please please let me know and I will work my hardest to fix them...thank you all so much for helping.
    Erick

  • Help with java program: Finding the remaining Gas in a Car

    I am a java newbie and I know this is a simple program but I am not getting the required result. Any help will be appreciated.
    Here is the code for Car.java :
    class Car{
         public  double gasTank;
         public  double drive;
         public  double fueleff;
         public Car()
              gasTank = 0;
         public Car(double rate)
              fueleff = rate;
              gasTank = 0;
         public void eff(double rate)
              fueleff = rate;
         public void drive(double amountDrove)
              drive = amountDrove;
              double amtRem = (gasTank-(drive/fueleff));
              gasTank = amtRem;
         public void addGas(double amountPumped)
              double amtRem = gasTank + amountPumped;
              gasTank = amtRem;
         public double getGas()
              return gasTank;
    }Here is the code for CarTester.java :
    public class CarTester {
      public static void main(String[] arg) {
        Car myHybrid = new Car();
        double amtRem = myHybrid.getGas();
        myHybrid.eff(50);
        myHybrid.addGas(20);
        myHybrid.drive(100);
        System.out.println("Amount Remaining: " + amtRem + " Gallons");
    }I should be getting 18 Gallons in the gasTank but I am getting 0.0. What am I doing wrong?

    And replace
    public void drive(double amountDrove)
    drive = amountDrove;
    double amtRem = (gasTank-(drive/fueleff));
    gasTank = amtRem;
    }with
    public void drive(double amountDrove)
      drive = amountDrove;
      gasTank -= drive/fueleff; // same logic as for +=
    }Cheers =)

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

  • Need some help with a program Please.

    Well, im new here, im new to java, so i need your help, i have to make a connect four program, my brother "Kind of" helped me and did a program for me, but the problem is i cant use some of those commands in the program and i have to replace them with what ive learned, so i will post the program and i will need your help to modify it for me.
    and for these programs, also i want help for:
    They have errors and i cant fix'em
    the commands that i've leaned:
    If statements, for loops, while loops,do while, strings, math classes, swithc statement, else if,logical operators,methods, one and two dimensional arrays.
    Thanx in advance,
    truegunner
    // Fhourstones 3.0 Board Logic
    // Copyright 2000-2004 John Tromp
    import java.io.*;
    class Connect4 {
    static long color[]; // black and white bitboard
    static final int WIDTH = 7;
    static final int HEIGHT = 6;
    // bitmask corresponds to board as follows in 7x6 case:
    // . . . . . . . TOP
    // 5 12 19 26 33 40 47
    // 4 11 18 25 32 39 46
    // 3 10 17 24 31 38 45
    // 2 9 16 23 30 37 44
    // 1 8 15 22 29 36 43
    // 0 7 14 21 28 35 42 BOTTOM
    static final int H1 = HEIGHT+1;
    static final int H2 = HEIGHT+2;
    static final int SIZE = HEIGHT*WIDTH;
    static final int SIZE1 = H1*WIDTH;
    static final long ALL1 = (1L<<SIZE1)-1L; // assumes SIZE1 < 63
    static final int COL1 = (1<<H1)-1;
    static final long BOTTOM = ALL1 / COL1; // has bits i*H1 set
    static final long TOP = BOTTOM << HEIGHT;
    int moves[],nplies;
    byte height[]; // holds bit index of lowest free square
    public Connect4()
    color = new long[2];
    height = new byte[WIDTH];
    moves = new int[SIZE];
    reset();
    void reset()
    nplies = 0;
    color[0] = color[1] = 0L;
    for (int i=0; i<WIDTH; i++)
    height[i] = (byte)(H1*i);
    public long positioncode()
    return 2*color[0] + color[1] + BOTTOM;
    // color[0] + color[1] + BOTTOM forms bitmap of heights
    // so that positioncode() is a complete board encoding
    public String toString()
    StringBuffer buf = new StringBuffer();
    for (int i=0; i<nplies; i++)
    buf.append(1+moves);
    buf.append("\n");
    for (int w=0; w<WIDTH; w++)
    buf.append(" "+(w+1));
    buf.append("\n");
    for (int h=HEIGHT-1; h>=0; h--) {
    for (int w=h; w<SIZE1; w+=H1) {
    long mask = 1L<<w;
    buf.append((color[0]&mask)!= 0 ? " @" :
    (color[1]&mask)!= 0 ? " 0" : " .");
    buf.append("\n");
    if (haswon(color[0]))
    buf.append("@ won\n");
    if (haswon(color[1]))
    buf.append("O won\n");
    return buf.toString();
    // return whether columns col has room
    final boolean isplayable(int col)
    return islegal(color[nplies&1] | (1L << height[col]));
    // return whether newboard lacks overflowing column
    final boolean islegal(long newboard)
    return (newboard & TOP) == 0;
    // return whether newboard is legal and includes a win
    final boolean islegalhaswon(long newboard)
    return islegal(newboard) && haswon(newboard);
    // return whether newboard includes a win
    final boolean haswon(long newboard)
    long y = newboard & (newboard>>HEIGHT);
    if ((y & (y >> 2*HEIGHT)) != 0) // check diagonal \
    return true;
    y = newboard & (newboard>>H1);
    if ((y & (y >> 2*H1)) != 0) // check horizontal -
    return true;
    y = newboard & (newboard>>H2); // check diagonal /
    if ((y & (y >> 2*H2)) != 0)
    return true;
    y = newboard & (newboard>>1); // check vertical |
    return (y & (y >> 2)) != 0;
    void backmove()
    int n;
    n = moves[--nplies];
    color[nplies&1] ^= 1L<<--height[n];
    void makemove(int n)
    color[nplies&1] ^= 1L<<height[n]++;
    moves[nplies++] = n;
    public static void main(String argv[])
    Connect4 c4;
    String line;
    int col=0, i, result;
    long nodes, msecs;
    c4 = new Connect4();
    c4.reset();
    BufferedReader dis = new BufferedReader(new InputStreamReader(System.in));
    for (;;) {
    System.out.println("position " + c4.positioncode() + " after moves " + c4 + "enter move(s):");
    try {
    line = dis.readLine();
    } catch (IOException e) {
    System.out.println(e);
    System.exit(0);
    return;
    if (line == null)
    break;
    for (i=0; i < line.length(); i++) {
    col = line.charAt(i) - '1';
    if (col >= 0 && col < WIDTH && c4.isplayable(col))
    c4.makemove(col);
    By the way im using Ready to program for the programming.

    You can't really believe that his brother did this
    for him...I did miss that copyright line at the beginning when
    I first looked it over, but you know, if it had been
    his brother, I'd be kinda impressed. This wasn't a
    25 line program. It actually would have required
    SOME thought. I doubt my brother woulda done that
    for me (notwithstanding the fact that I wouldn't need
    help for that program, and my brother isn't a
    programmer).I originally missed the comments at the top but when I saw the complexity of what was written then I knew that it was too advanced for a beginner and I relooked through the code and saw the comments.

Maybe you are looking for

  • How can I get a refund from the app store?

    Hi, I bought an game from the app store for 4.99. The description was written to be completely misleading and misrepresentative of the product (BADASS DUCATI: Street Monster). I notice the same developer has a number of apps. on the store following t

  • How can i rebuy an app with my new ID and password

    I need to rebuy an updated app, because I no longer remember the password or email address I used for the original purchase.  It is actually a free app, but it shows downloaded when I view it.

  • There is a problem with launching iPhoto.

    Every time I try to launch it crashes and says "You can't open the application iPhoto because it may be damaged or incomplete". I don't know how to resolve this issue If you can help. Thanks

  • Is it possible to get this o/p in a query

    Hello All, is it possible to write a query for the output SQL> select * from emp1; EMPNO EMPNAME 100 AAA 222 BBB 333 CCC 444 DDD SQL> select * from bank; BANKID BANKNAME 1 ICICI 2 HDFC 3 SBI 4 SBH SQL> select * from emp1_bank; EMPNO BANKID 100 1 100

  • J2ee Execution Exception

    Hello people, I am new here .please be kind to me .. I followed the J2ee Tutorial and executed successfully the example in it.the Converter example.after doing that,i wanted to write my own application . so did a Simple User Authentification Example.