this is the oracle GUI

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;


public class OracleGUI extends JFrame implements ActionListener
{
	// Define constants
	public static final String GET_QUESTION = 
			"I will answer any question. Let me know yours.\n" + 
			"Type your question in the following and hit Submit.";
	public static final String GET_ADVICE = 
			"That's a difficult question. \n" + 
			"I need some advice from you first.\n";
	public static final String GIVE_ADVICE = 
			"Here is my advice to your problem.\n" + 
			"Hope it helps.\n" + 
			"Hit Reset button to ask another question.";
			
	public static final String BT_SUBMIT = "Submit";
	public static final String BT_RESET = "Reset";
	
	public static final int CHAR_PER_LINE = 40;
	public static final int LINES_USER_INPUT = 10;
	public static final int LINES_PROMPT = 5;
	
	
	public static final int STAGE_GET_QUESTION = 0;
	public static final int STAGE_GET_ADVICE = 1;
	public static final int STAGE_GIVE_ADVICE = 2;
	
	// GUI components
	private JTextArea	prompt;
	private JTextArea	userInput;
	private JButton		btSubmit;
	private JButton		btReset;
	
	//
	private int			stage;
	private Oracle		ora;
	
	public OracleGUI ()
	{
		// Create the oracle to be used
		ora = new Oracle ();
		
		// Set window size, location and title
		setSize (400, 250);
		setLocation (250, 250);
		setTitle ("I'm the Oracle");
		
		// Create all components here
		Container contentPane = getContentPane ();
		
		contentPane.setLayout (new BorderLayout ());
		
		// Add prompt label; set its background color, and font
		prompt = new JTextArea (LINES_PROMPT, CHAR_PER_LINE);
		prompt.setText (GET_QUESTION);
		prompt.setBackground (contentPane.getBackground ());
		prompt.setEditable (false);
		Font oldFont = prompt.getFont ();
		prompt.setFont (new Font (oldFont.getFontName (), Font.BOLD, oldFont.getSize ()));
		contentPane.add (prompt, BorderLayout.NORTH);
		
		// Add user input textarea
		userInput = new JTextArea (LINES_USER_INPUT, CHAR_PER_LINE);
		contentPane.add (userInput, BorderLayout.CENTER);
		
		// Add a panel to hold two buttons
		JPanel btPane = new JPanel ();
		contentPane.add (btPane, BorderLayout.SOUTH);
		
		btPane.setLayout (new FlowLayout ());
		
		btSubmit = new JButton (BT_SUBMIT);
		btSubmit.addActionListener (this);
		btPane.add (btSubmit);
		
		btReset = new JButton (BT_RESET);
		btReset.addActionListener (this);
		btPane.add (btReset);
		
		// Make everything visible
		setVisible (true);
		
	}
	
	
	public void actionPerformed (ActionEvent e)
	{
		String actionCommand = e.getActionCommand ();
		
		if (actionCommand.equals ("Submit"))
		{
			switch (stage)
			{
			case STAGE_GET_QUESTION:	//user submitted a question 
				updateForAdvice ();
				break;
			
			case STAGE_GET_ADVICE:		// user submitted an advice 
				giveAdvice ();
				break;
			default:
				break;
			}		
		}
		else if (actionCommand.equals ("Reset"))
			reset ();
	}
	
	/*
	 * Main method to start the window
	 */
	public static void main (String[] args)
	{
		OracleGUI	oraGUI = new OracleGUI ();
		
		oraGUI.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
	}
	
	
	/*
	 * Private helper methods
	 */
	
	private void updateForAdvice ()
	{
		String userQ = userInput.getText ().trim ();
		
		if (userQ.length () == 0)
		{
			JOptionPane.showMessageDialog (null,
				"You need to tell me more about your problem\n"+
				"for me to give you any help");
			return;	
		}
		
		// Change the prompt message
		prompt.setText (GET_ADVICE);
		
		// Clear the user-input textarea
		userInput.setText ("");
		
		stage ++;
	}
	
	private void giveAdvice ()
	{
		String userAdvice = userInput.getText ().trim ();
		
		if (userAdvice.length () == 0)
		{
			// Tell the user to enter something
			JOptionPane.showMessageDialog (null, 
				"Nothing is free.\n"+
				"You need to give me some help so that I can help you.");
				
			return;	
		}
		
		// Retrive an advice from the oracle
		String oraAdvice = ora.getAdvice ();
		
		// Add user's advice to oracle
		ora.addAdvice (userAdvice);
		
		// Update GUI
		prompt.setText (GIVE_ADVICE);
		
		userInput.setText (oraAdvice);
		
		btSubmit.setEnabled (false);
		
		stage ++;
	}
	
	private void reset ()
	{
		// Reset stage
		stage = STAGE_GET_QUESTION;
		
		// Reset prompt message
		prompt.setText (GET_QUESTION);
			
		// Clear user-input textarea
		userInput.setText ("");
		
		// Reset button status
		btSubmit.setEnabled (true);
	}
}

then heres the oracle (code) which i have to fix...

/** 
 * Oracle.java: An Oracle object keeps a list of advices. 
 * It can learn a new advice by adding it to its list, 
 * and it can give advice by retrieving one randomly from its list. 
 */

public class Oracle
{
	/**
	 * Adds a new piece of advice to its list
	 */
	public void addAdvice (String advice)
	{
		// This is a stub. Nothing is done here
		return;
	}
	
	/**
	 * Retrieves randomly a piece of advice from its list
	 */
	public String getAdvice ()
	{
		// This is a stub. It returns a fixed advice
		return "Keep on searching, and you'll find the answer.";
	}
	
	/**
	 * Returns a random number in the range of 0 - (range-1)
	 */
	private static int getRandomIndex (int range)
	{
		return ((int) (Math.random () * range));
	}
}

and this is the intruction...

"Implement the Oracle class. More specifically, you need to write the following three: a default constructor, method addAdvice () and method getAdvice ().

Use an array to keep a list of advices. Make the size of the array 5 (define a named constant for this number). In the default constructor of the Oracle class, initialize the oracle with 2 pieces of advices of your choice.

"

ok..thank you for reading this far...

im not asking anyone of you to do my homework, i want to do it my self..but i need advice where to start, and how to start..

im stuck fromt he begginning which is bad...

if i get a start i think i should be ok...i may ask questtions and all...but it would be great if i get help.

thank you very much.

any help (sites) or anything will be greatly appriciated...

Recommended Answers

All 24 Replies

The instructions are very clear. You have to add an array to that class to store each "advice". The add method should add that string to the array and the get method should return a random entry from that array. Short of telling you exactly how to do it, I don't see what more needs to be said.

If you have a specific question then ask it, but the instructions are simple enough that you should know how to start.

thank you.

i guess the instructions are clear..but first, i dont understand it.

well, im not American so its hard for me to understand.

is there any advice that you can please give me?

Start by adding a string array to that class. Re-read your class notes on arrays if you have difficulty declaring it. You were given the size to make it.

Then work on the addAdvice() method to add a string to that array.

thank you...appriciate it.

import java.util.*;

public class Oracle
{
    private static ArrayList <String> advice = new ArrayList<String> (); 
    
    /**
     * Adds a new piece of advice to its list
     */
    public void addAdvice (String advice)
    {
        
        this.advice.add (advice);
        String[] strArray;
        strArray = new String[5];
        
        strArray[0] = "search engines like google are great places to search.";
       // strArray[1] = "";
       // strArray[2] = "";
       // strArray[3] = "";
       // strArray[4] = "";

        return;
    }
    
    /**
     * Retrieves randomly a piece of advice from its list
     */
    public String getAdvice (int index)
    {
        // This is a stub. It returns a fixed advice
        return advice [index];
    }
    
    /**
     * Returns a random number in the range of 0 - (range-1)
     */
    private static int getRandomIndex (int range)
    {
        return ((int) (Math.random () * range));
    }
}

i got that...

but how do i "get advice"??

thanks for anyhelp...

ive been searchin on the net about arrays, but i still dont get it..

if there is a good site out there, it would be great if you post it.

thanks for any help.

First of all don't use the same name for the ArrayList and the argument of addAdvice(). It is bad programming.
Second, does this thing compile? I think that the getAdvice (int index) will have a problem:

public String getAdvice (int index)
    {
        // This is a stub. It returns a fixed advice
        return advice [index];
    }

the variable advice is declared to be an ArrayList, and the method's signature is a String. I would try something like this:
return advice.get(index); or make the advice to be an array.

Although the instructions tells you to use arrays, you use ArrayList. You can have you constructor initialize an array and have a private int variable to monitor at which place you need to add the new advice. Have that variable to be 0 and every time you call add do:

public void addAdvice (String adv)
    {
        //advice should be an array initialized at the constructor
        //index should be initialized at the Constructor with value 0;
       if (index<advice.length) {
           advice[index] = adv;
           index++;
       }
    }

And for getAdvice, use the random number generator but the range should be from 0 to index-1

thanks.

appriciate it.

i have a quick question.

how do i add two advices to the array within the constructor and update index accordingly?

public class Oracle
{
  private String [] advice=null;
  private int index=0;
  
    public Oracle() {
      advice=new String[5]; //as rerquested to have length 5
      index=0;
    }

//if you want two advice then pass them as arguments and manually increase or set the index
//remember indexis where the next advice will be stored
 
   public Oracle(String adv1, String adv2) {
      advice=new String[5]; //as rerquested to have length 5
      index=0;

      advice[index]=adv1;
      index++;

      advice[index]=adv2;
      index++;
     
     /*
     OR since this is the constructor and you know that these will be the first values: 
     advice[0]=adv1;
     advice[1]=adv1;
     index=2;
      */
    }
}

But why do you want two at the constructor?

i have a quick question.

how do i add two advices to the array within the constructor and update index accordingly?

Just like you add any "advices" to the array - you call the method that you wrote. That is what it's there for.

thanks for the help.

my instructor told me to put two at the constructor.

As an argument to the constructor or within the default constructor? Hopefully not as args to the constructor, because that is pretty arbitrary and useless. If you want to pass some initial entries in the constructor, you are much better off accepting a String array as the parameter and copying those to your internal array.

/** 
* Oracle.java: An Oracle object keeps a list of advices. 
* It can learn a new advice by adding it to its list, 
* and it can give advice by retrieving one randomly from its list. 
*/

import java.util.*;

public class Oracle
{
	
  private String [] advice=null;
  private int index;
  
  
 //constructor
public Oracle ()
{
advice = new String[5];
index = 0;

advice[0] = "It's as simple as this";
//advice[1] = "";
//advice[2] = "";
//advice[3] = "";
//advice[4] = "";
}

 	public void addAdvice (String advice)
    {
           
       if (index < advice.length) 
       {
           advice[index] = adv;
           index++;
       }
       return;
                   
    }
    

    public String getAdvice ()
    {
      
        
        
        return advice.get(index); 
    }
    
    /**
     * Returns a random number in the range of 0 - (range-1)
     */
    private static int getRandomIndex (int range)
    {
        return ((int) (Math.random () * range));
    }
}

i fixed the constructor and all that.

thanks for all the help.

but it doesnt recognize "length", also how do i make it recogize the "adv" in the "addAdvice"?

thanks

On which line? The stack trace provides the line number and specifics of the error.

"adv" is not defined in addAdvice(), which is most likely the source of your error.

Also, I would point out that the method

public void addAdvice (String advice)
    {
           
       if (index < advice.length) 
       {
           advice[index] = adv;
           index++;
       }
                   
    }

gives you plenty of room to create errors. You have named the string parameter the same as your array instance variable. I would recommend changing that parameter name to something like "entry" to avoid ambiguity and scope issues.

commented: thanks for all the help... +1

OOOO!!!

ok!! thanks!!! now thats fixed:)

SWEET!!! its working:D

/** 
* Oracle.java: An Oracle object keeps a list of advices. 
* It can learn a new advice by adding it to its list, 
* and it can give advice by retrieving one randomly from its list. 
*/

import java.util.*;

public class Oracle
{
	
  private String [] advice=null;
  private int index;
  
  
  
 //constructor
public Oracle ()
{
advice = new String[5];
index = 0;

advice[0] = "It's as simple as this";
advice[1] = "Search engines like google are great!";

}

 	public void addAdvice (String entry)
    {
           
       if (index < advice.length) 
       {
           advice[index] = entry;
           index++;
       }
       return;
                   
    }
    

    public String getAdvice ()
    {
      
        
        
       	return advice [index];
    }
    
    /**
     * Returns a random number in the range of 0 - (range-1)
     */
    private static int getRandomIndex (int range)
    {
        return ((int) (Math.random () * range));
    }
}

now i have to get it random...lol.

this site is great:D

Do you know WHY you increase the index in the addAdvice method? You increase it because when you add a new advice you don't want it to be placed at the same place as a previous inserted advice. Now look at the constructor and the addAdvice

public Oracle ()
{
advice = new String[5];
index = 0;

advice[0] = "It's as simple as this";
advice[1] = "Search engines like google are great!";
}

public void addAdvice (String entry)
    {
           
       if (index < advice.length) 
       {
           advice[index] = entry;
           index++;
       }
       return;
                   
    }

If you call the constructor and then the add method, the index in the add method will have value 0. So the advice passed as argument in the add method will be placed at the '0' place of the array which will overwtite the "It's as simple as this" of the constructor.

Since you "add" two "advices" in the constructor, you should also increase the index twice as well

commented: helpful point +9
commented: thanks for the explanation (arrays) +1

Which is why the constructor should just call add() twice with the strings you want to add. Why code a method to manage the array additions and then not use it?

Just because a method is public does not mean that it's not useful within the class is well. Having the code that manages that operation defined in a single place and using it for all additions to your array minimizes the changes needed to alter how that operation works and ensures that if you change that behavior you don't have to make related changes elsewhere in the class.

wow, thanks for the explanation.

appriciate it.

this stuff is due tomorrow...in 10 hours... (its 2AM in the morning right now).

thats about 70%, i need to get it random, and need to get it to have "new advice".

i think i should get it...

how do i start "get advice"??

i have the getRandomIndex on the bottom..

it doesnt do random...and im LOST. lol.

how do i start "get advice"??

i have the getRandomIndex on the bottom..

it doesnt do random...and im LOST. lol.

What do you mean how you start it? Create an instance of the object and call its methods.

And the getAdvice method should have an int argument, so you will be able to get the selected value:

public String getAdvice(int i) {
  return advice[i];
}

You have return advice [index]; and since the index variable holds where the next String should be placed, the method will not return anything useful, because you haven't put anything in that place yet.

i got it to work:)

public String getAdvice()
    {
        int random = (int) (Math.random() * advice.length);
        return advice [random];
    }

that should be good:)

also, i have to do a System.out.println thing so it shows the list of advices, where should i put that? at the end?

If you want to print all the advices that are in the array then I would suggest a new void method that uses a for-loop to print all the elements of the array.

As for the getAdvice(), it is correct, but you are using the advice.length:

int random = (int) (Math.random() * advice.length);

So if your array has values:
{"Advice 1","Advice 2","Advice 3","",""}
Then it is possible for random to take value 3 or 4 which will return nothing. I would suggest to use:

int random = (int) (Math.random() * index);

Use the same in the for-loop for printing all the values:

for (int i=0;i<index;i++) {
  System.out.println(advice[i]);
}

everyyone thanks for all the help:)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.