NPH

Did the professor tell you what the Gift class is supposed to represent?

If this program is about converting currency, what does a gift have to do with converting currency?

You mentioned that the Gift class must hold the total. You could use the Gift class below and create a Gift object in the main method (as you did earlier) and call the updateTotal after converting the currency.

[CODE]class Gift
{
private int total;

public void updateTotal(int amount)
{
    total += amount;
}

 public int getTotal()
 {
    return total;
 }

}[/CODE]This class isn't necessary. You could just maintain an variable in the ConvertCurrency class.

[B][I]Please give more information about the project so a more helpful response can be given[/I][/B]

:?: For more help, [url]www.NeedProgrammingHelp.com[/url]

NPH

The scanner interface can be used to read lines, tokens, etc.

Suppose you want to open a file named "c:\test.txt" using the Scanner:
[CODE]Scanner sc = new Scanner(new File("c:\test.txt"));[/CODE]To read all the lines from the file using the created scanner:
[CODE]while(sc.hasNextLine())
{
String scLine = sc.nextLine();

//process line

}[/CODE]What is the input file supposed to look like? What should the output of the program be?

:?: For more help, [url]www.NeedProgrammingHelp.com[/url]

NPH

You could create a batch file (.bat). This answer is for Windows computers. It is not an executable but it is very simple to make.

Suppose you main method is in the class MyTest. Then create a file called MyJavaRun.bat. (The name is arbitrary)

Inside the file write:

[CODE]java MyTest
pause[/CODE]The first line runs the JVM giving it the main class and the second command prevents the window from closing all of a sudden when the program exits.

Then just double click the .bat file and it will run the Java program.

:?: For more help, [url]www.NeedProgrammingHelp.com[/url]

NPH

Take $123.30.

[COLOR=Blue][B]1.[/B][/COLOR] First you need to separate the dollars and the cents using the substring method of the String class (see code below).

[COLOR=Blue][B]2.[/B][/COLOR] How do you convert a hundreds digit? Just put "Hundred" afterwards:

    1xx = > One Hundred xx

[COLOR=Blue][B]3.[/B][/COLOR] How do you convert a tens digit? This one is harder.

If the tens digit is 1, then it is easiest to just handle every possible case (11-19) in a big if statement.

    11=>"Eleven"
    ..
    19=>"Nineteen"

If the tens digit is a 2 then its always "Twenty" followed by the rest. 

    21 => "Twenty One"

...

If the tens digit is a 9 then its always "Ninety" followed by the rest. 

    97 => "Ninety Seven"

[COLOR=Blue][B]4.[/B][/COLOR] How do you obtain the digits? After separating the dollars from the cents, use the charAt method of the String class.

[COLOR=Blue]Run the code below for a simple example of obtaining the digits:[/COLOR]

[CODE]class NumToWord
{
public static void main(String[] a)
{

    //define string
    String text = "123.30";

    //find position of decimal in text
    int decimalPos = text.indexOf(".");

    //get text before decimal
    String dollars = text.substring(0, decimalPos);

    //get text after decimal
    String cents = text.substring(decimalPos+1);

    //get last pos in dollars text
    int lastPosInDollars = dollars.length()-1;

    //get hundreds digit
    char hundredsDigit = dollars.charAt(lastPosInDollars-2);

    //get tens digit
    char tensDigit = dollars.charAt(lastPosInDollars-1);

    //get ones digit
    char onesDigit = dollars.charAt(lastPosInDollars-0);

    //print
    System.out.println ("The ones digit is " + onesDigit);
    System.out.println ("The tens digit is " + tensDigit);
    System.out.println ("The hundreds digit is " + hundredsDigit); ...

NPH

Run this code below. See the comments for an explanation. This should help understand what you need to use.

[CODE]import javax.swing.;
import java.awt.
;

class TestPanel extends JPanel
{
//paint function
public void paint(Graphics g)
{
//cast to Graphics2D
Graphics2D g2D = (Graphics2D)(g);

    //set stroke
    int lineWidth = 5;
    g2D.setStroke( new BasicStroke(lineWidth));

    //draw line
    g2D.drawLine(0,0, 100, 100);

    //draw an arc from 45 degrees to (45+90) degrees. 90 determines how wide the arc is
    g2D.drawArc(0,0, 100, 100, 45, 90);
}

}

class Test
{
public static void main(String[] a)
{
//create JFrame
JFrame j = new JFrame();

    //add TestPanel
    j.getContentPane().add( new TestPanel());

    //show JFrame
    j.setBounds(0,0, 100,100);
    j.setVisible(true);
}   

}[/CODE]
:?: For more help, [url]www.NeedProgrammingHelp.com[/url]

NPH

Here is an example that uses max_length.
[CODE]
import javax.swing.JOptionPane;

public class Test
{
public static void main(String[] a)
{
//get first string from user
String indata1 = JOptionPane.showInputDialog("Enter text");

    //get second string from user
    String indata2 = JOptionPane.showInputDialog("Enter text");

    int max_length=0;

    //check length
    if( indata1.length() >= indata2.length())
    {
        max_length = indata1.length();
    }
    else
    {
        max_length = indata2.length();
    }

    System.out.println("The longest string has length " + max_length);

}

}[/CODE]
To make the code better, you could replace the if statements above with one line:

[CODE]max_length = Math.max(indata1.length(), indata2.length());[/CODE]
:?: For more help, [url]www.NeedProgrammingHelp.com[/url]

NPH

glamo,

See Chapter 7 in this page: [url]http://www.jeffheaton.com/ai/[/url]

You need to understand Neural Networks. I would suggest to read the other chapters.

:?: For more help, [url]www.NeedProgrammingHelp.com[/url]

NPH

OllieFalle,

Here are a few things that seem incorrect to me (correct me if I am wrong):

[B]1.[/B] Your method called userInput shown below has problems
[CODE]public void userInput ()
{
System.out.println("Enter a sequence of notes: ");
String sent = Keyboard.readString();
StringTokenizer st = new StringTokenizer(sent);
String word;
while (st.hasMoreTokens())
{
word = st.nextToken();
}
}[/CODE]
Notice that it reads through the tokens and stores each in the variable [B]word[/B]. Therefore, at the end, word holds the last token. All the other tokens were discarded.

[B][I]What you should do is tokenize and store the results in an ArrayList.[/I][/B]

[B]2. [/B] Your drawNote method always draws the same character at the same x position. Is this what you want?

[CODE]public void drawNote(Graphics g)
{
g.setColor(Color.black);
g.setFont( new Font("MS PMincho", Font.PLAIN, 48) );
g.drawString("" + '\u2669', 75, 275-10*notePosition);
}[/CODE]
[B]3. [/B] Your notePosition method seems to have a compile error. I don't see a StringTokenizer declared in that method or a instance variable. The only place it is created is in the userInput method but you can't access it from the notePosition method.

What do you want this method to do?

:?: For more help, [i]removed link to homework pay site[/i]

NPH

Melotron,

Here is an example of the code you need:

[CODE]import javax.swing.JOptionPane;

public class Test
{
public static void main(String[] a)
{
//get first string from user
String indata1 = JOptionPane.showInputDialog("Enter text");

    //get second string from user
    String indata2 = JOptionPane.showInputDialog("Enter text");

    //check length
    if( indata1.length() > indata2.length())
    {
        System.out.println("The longest is " + indata1);
    }
    else if( indata1.length() < indata2.length())
    {
        System.out.println("The longest is " + indata2);
    }
    else
    {
        System.out.println("They are the same length");
    }
}

}[/CODE]
:?: For more help, [url]www.NeedProgrammingHelp.com[/url]

jwenting commented: don't do people's homework, let them think for themselves. +0

NPH

Suppose you want to generate 50 unique random numbers from 0 to 100.
[CODE]
//Create an array of size 100 that remembers which integers are taken
boolean[] taken = new boolean[100];

//start count at 0
int count =0;

//create random gen
Random r = new Random();

//create array to hold 50 unique random numbers
int[] uniqueRNums = new int[50];

//begin the loop, stop when got 50 unique random numbers
while(count < 50)
{
//get random integer 0-100
int rNum = r.nextInt(100);

 //check if it is taken
 if(!taken[rNum] )
 {
    //mark as taken
    taken[rNum] = true;

    //add to unique random numbers list
    uniqueRNums[count]=rNum;

    //update count
    count++;
 }

}[/CODE]Hope this helps.

:?: For more help, [url]www.NeedProgrammingHelp.com[/url]

NPH

I would suggest to use a 3x3 two dimensional array. Maybe something like

[CODE]char player[][] = new char[3][3];[/CODE]Then when player 1 wants to use cell (1,2) write:

[CODE]player[1][2] = '1';[/CODE] :?: For more help, [url]www.NeedProgrammingHelp.com[/url]

NPH

To check if someone is already in the room use the following code:

[CODE]boolean isRoomOccupied(int floor, int room)
{
if( array[floor][room] == null )
return true;
else
return false;
}[/CODE]
When someone checks out call this function

[CODE]void checkOut(int floor, int room)
{
array[floor][room] = null;
}[/CODE]It is very important that you reset it back to null when it is check out time otherwise the first function won't work (because it checks for null)

For more help, [url]www.NeedProgrammingHelp.com[/url]

NPH

To add a new node to the end of the linked list you should try:

[CODE]Node newNode = new Node(characterObject);
if(length == 0)
{
firstNode = tailNode = newNode;
}
else
{
tailNode.next = newNode;
tailNode = newNode;
}
length++;[/CODE]The problem with your code is that you update tailnode in your add method and then you try to set it's next to be the newNode. But by this time, the tailNode is already newNode. So you just created a circular reference (newNode == newNode.next)

This problem doesn't occur in the above code because tailNode is modified after we modify tailNode.next.

tailNode.next "links in " the newNode. and then we make newNode the tailNode.

:?: For more help, [url]www.NeedProgrammingHelp.com[/url]

NPH

Here is a working example of what you need. Basically it takes commands like 'add node' with name "Child1" to node with name "Parent1". The root must always be referred to as "root".

Run the code and read the comments. Should be easy to use/modify.

[CODE]import javax.swing.;
import javax.swing.tree.
;
import java.util.*;

class JTreeReader extends JTree
{
//create map of names to node objects
private HashMap namesToNodes = new HashMap();

public JTreeReader()
{
    //create root of tree
    DefaultMutableTreeNode root = new DefaultMutableTreeNode("root");
    this.setModel(new DefaultTreeModel(root));

    //add to map
    namesToNodes.put("root", root);
}

//get node object with name
private DefaultMutableTreeNode getNode(String name)
{
    //make lowercase
    name = name.toLowerCase();

    //get node from map
    DefaultMutableTreeNode node = (DefaultMutableTreeNode)(namesToNodes.get(name));

    //if not defined
    if(node == null)
    {
        //create new node
        DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(name);  

        //add to map
        namesToNodes.put(name, newNode);

        //return new node
        return newNode;
    }
    else
    {
        //return old node
        return node;
    }
}

public void expandRoot()
{
    //expand path to root
    expandPath(new TreePath(getNode("root")));
}

//add first node to second node
public void addNodeTo(String childNodeName, String parentNodeName)
{
    //get two nodes
    DefaultMutableTreeNode parentNode = getNode(parentNodeName);
    DefaultMutableTreeNode childNode = getNode(childNodeName);

    //add child to parent at the end of child list
    ((DefaultTreeModel)getModel()).insertNodeInto(childNode, parentNode, parentNode.getChildCount());   

}

public static void main(String[] args)
{
    //create jframe
    JFrame jf = new JFrame();

    //create jtree
    JTreeReader tree = new JTreeReader();
    tree.addNodeTo("Item1","root");
    tree.addNodeTo("Sub Item 1","Item1");
    tree.addNodeTo("Sub Item 2","Item1");
    tree.addNodeTo("Item2","root");

    tree.expandRoot();

    //show
    jf.getContentPane().add(tree);
    jf.setBounds(0,0,500,500);

    jf.setVisible(true);
}

}[/CODE]
;) For more help, [url]www.NeedProgrammingHelp.com[/url]

NPH

The while loop only runs one time because of the statement

[CODE]return itemNo ;[/CODE]Once that statement executes the loop (and the entire method) are ended.

Take out the return and it should work. Why are you putting a return there anyways?

:cool: For more help, [url]www.NeedProgrammingHelp.com[/url]

NPH

Have you tried this code:

[CODE]Dim strBinary As String = "11111111"
Dim intValue As Integer
Dim iPos As Integer
Dim iVal As Integer

For iPos = 0 To strBinary.Length - 1
iVal = strBinary.Substring(strBinary.Length - iPos - 1, 1)
intValue = intValue + iVal * 2 ^ iPos
Next[/CODE] You can get more info at [url]http://www.experts-exchange.com/Programming/Programming_Languages/Dot_Net/VB_DOT_NET/Q_21259781.html[/url]

:mrgreen: For more help, [url]www.NeedProgrammingHelp.com[/url]

NPH

There are many problems:

  1. Fix mispelling/case errors.
  2. There is no unsigned keyword
  3. main must be public static
  4. f has no return type
  5. readLine() returns String not int
  6. I have no idea what you mean by the following line:

System.out.println("you have entered names of "+name[i=String[i].length()>=0]+"these are-:");

I recommend that you compile it and go error by error. Post the errors that you get here.

:mrgreen: For more help, [url]www.NeedProgrammingHelp.com[/url]

NPH

Try this code

[CODE]
double num = 1001.27124;

double newNum = Math.round(num100.0)/100.0;
System.out.println (newNum); //prints 1001.27
[/CODE]
It works because
100 shifts the numbers to the left twice. Then the round is applied. Then we divide by 100 to shift twice right.

For more help, [url]www.NeedProgrammingHelp.com[/url]

NPH

Override the paint method and use the translate method of the Graphics object. Remember that translate(100,100) doesn't mean goto point 100,100. It means move to the right 100 and move down 100.

[CODE]
public void paint(Graphics g)
{
//draw circle
drawCircle(g);

//move left and down by 100
g.translate(100,100);

//draw another circle
drawCircle(g);

//move left and down by 100
g.translate(100,100);

//draw another circle
drawCircle(g);

}

private void drawCircle(Graphics g)
{
g.setColor(fill);
g.fillOval(0, 0, 30, 30);
g.setColor(outline);
g.drawOval(0, 0, 30, 30);

}[/CODE]
For more help, [url]www.NeedProgrammingHelp.com[/url]

NPH

Check out these two links. Hope it helps.

[url]http://www.falkhausen.de/en/diagram/html/javax.swing.JComponents.html[/url]

[url]http://www.falkhausen.de/en/diagram/html/java.awt.Components.html[/url]

For more help, [url]www.NeedProgrammingHelp.com[/url]

NPH

You can use the String classes replaceAll method. Here is an example:

[CODE]String str = "Hello blank";
String newStr = str.replaceAll("blank", "Jim") ;

System.out.println(newStr); //prints "Hello Jim"[/CODE]
For more help, [url]www.NeedProgrammingHelp.com[/url]

NPH

Firstly,

The line with the code
[CODE]if((tokens.hasMoreTokens()) );[/CODE]is basically useless. This checks if there are tokens and does nothing. What you want is
[CODE]if((tokens.hasMoreTokens()) )
{
//put code here
}[/CODE]Also, you might want to use the trim() function when getting tokens. This cleans out the string of weird spaces at the beginning and end:
[CODE]String someTokenHere = tokens.nextToken().trim();[/CODE]
For more help, [url]www.NeedProgrammingHelp.com[/url]

NPH

You received a NullPointerException because the array [B]possibleseq [/B] is always null and you end up using it in your code.

The best solution is to create an ArrayList by writing
[CODE][B]ArrayList [/B]possibleseq= new [B]ArrayList[/B]();[/CODE]
then add your strings into it by writing:
[CODE]possibleseq.add("someText");[/CODE]
Then to get the 11th item from the ArrayList write:
[CODE]
//this line gets the 11th object and casts it into a String
[B]String [/B]obj = ([B]String[/B])(possibleseq.get(10));[/CODE]
For more help, [url]www.NeedProgrammingHelp.com[/url]

NPH

Your image is not being found. Probably the directory "C:/MyDocuments/MemoryGame/woodTable.gif"; doesn't exist.

If its in your documents folder then the correct directory would be:

C:/Documents and Settings/YOUR WINDOWS USER NAME HERE/My Documents/woodTable.gif.

For more help, [url]www.NeedProgrammingHelp.com[/url]

NPH

Each row contains a persons info. The best thing to do is create a class that holds each row. Here is an example:

[CODE]class PersonInfo
{
private String name;
private int age;
private String address;

public PersonInfo(String name, int age, String address)
{
    this.name=name;
    this.age=age;
    this.address=address;
}

}
[/CODE]

Then in your loop above you should write:
[CODE]
//create array outside
PersonInfo[] listOfInfo = new PersonInfo[100]; //change 100 to the desired size!

//maintain # of items in array
int listOfInfoSize=0;

//read lines
while (line != null)
{
StringTokenizer tokens = new StringTokenizer(line, ", \t");

//get three tokens
String nameToken = tokens.nextToken();
String ageToken = tokens.nextToken();
String addressToken = tokens.nextToken();

//create personinfo object
PersonInfo obj = new PersonInfo(nameToken, ageToken, addressToken);

//add to array
listOfInfo[listOfInfoSize++]=obj;

}[/CODE]
As you see above, the array will hold all the PersonInfo objects. Each PersonInfo object represents a row in the text file. You should add getter methods to the PersonInfo class. Then you can use this array to get any info you need.

For more help, [url]www.NeedProgrammingHelp.com[/url]

NPH

The hardest part is knowing how to store & structure the information once it is read.

Firstly, the program must be able to quickly answer the following question: Give me all info on a subject "Intro to Software". You should then be able to get the scale/non-scaled max scores for any assignment in the subject. You will need to do this when you read the students file and need to calculate the scores.

I recommend creating a class called Subject. Hashmaps can then be used to associate the name "Intro to Software" to an object of type Subject that holds all the info on Intro to Software. This lets you obtain all the info by just knowing the name.

This is [B]not[/B] the entire solution but here is the idea. Instead of hard coding the data, you must read it from the file but it should help. [B]Run it and read the comments.[/B]

[CODE]import java.util.*;
//subject class
class Subject
{
//name of subject
private String name;

//all the assignments in the subject
private ArrayList assignments = new ArrayList();

//constructor
public Subject(String name)
{
    this.name = name;
}

//add an assignment to subject
public void addAssignment(Assignment assign)
{
    assignments.add(assign);
}

//get an assignment from subject
public Assignment getAssignment(String name)
{
    for(int i =0; i < assignments.size(); i++)
    {
        Assignment assign = (Assignment)( assignments.get(i) );

        if(assign.getName().equals(name))
        {
            return assign;  
        }
    }

    throw new RuntimeException("Assignment " + name + " not found");
}

}

//assignment
class Assignment
{
//data
private String name;
private ...

NPH

Polymorphism means many forms. The idea of polymorphism is very important in OOP. Lets look at Java's IO classes (they use a lot of this concept).

The code below is legal:

[CODE]//The inputstream r will get its input from a file.
InputStream r = new FileInputStream("someFile.txt");[/CODE]The code below is also legal:

[CODE]//The inputstream r will get its input from a byte array
byte[] someBytes = new byte[500];
InputStream r = new ByteArrayInputStream( someBytes );[/CODE]
Therefore, if someone gives you an "InputStream" object and asks you "where do it gets it's input?". You CANNOT answer this question b/c it could be from a file or a byte array or from the network.

When you call the method r.read() is it calling the read method in FileInputStream, or the read method in ByteArrayInputStream? You CANNOT answer this question either because r is an InputStream and you can't tell if its really a FileInputStream or a ByteArrayInputStream.

Therefore, the read() method has many forms. If you call it, it might be getting data from a file, or from the network, or from a byte array. You just don't really know. Therefore the method has many forms and there is your polymorphism.

Why is this useful? Because it makes your program more useful and general. Since your program doesn't care for the source of its input, it works with anything (input from a file, network, or a byte array). This is much better than writing code for all possible combinations of streams.

For more ...

NPH

Why do you need to store all the lines? Couldn't you just maintain the average of the numbers in a variable.

For example,

[CODE]create a total & amount variable (for the average... average = total/amount)
double total =0;
double amount=0;

//for each line in the file
while ((line = input.readLine()) != null)
{

//tokenize the line
StringTokenizer tokenizer = new StringTokenizer(line, ",");

//if there are 3 tokens in the line
if( tokenizer.countTokens() == 3)
{
    //get 1st token in line
    String str = tokenizer.nextToken();

    //get 2nd token in line
    int num1 = Integer.parseInt(tokenizer.nextToken().trim());

    //get 3rd token in line
    int num2 = Integer.parseInt(tokenizer.nextToken().trim());

    //add numbers to total
    total += num1 + num2;

    //increment amount
    amount++;

}

}

//show average
System.out.println("Average is: " + total/amount);[/CODE]You should give more information about your project so a better answer can be given. Hope the above helps.

For more help, [url]www.NeedProgrammingHelp.com[/url]

NPH

== has many meanings

[B]1.[/B] When comparing simple data types (int, char, double, bool, etc), == compares the value of the two.

[CODE]int x = 1;
int y = 2-1;
System.out.println( x == y ); // [B]prints true[/B] [/CODE]

[B]2. [/B] When comparing two object references, it compares the value of the two references (not the value of the objects!). For example,

[CODE]
Integer x = new Integer(15);
Integer y = new Integer(15);
System.out.println( x == y ); // [B]prints false[/B] [/CODE]

x refers to an Integer object and y refers to an Integer object. Are the two references the same (do they refer to the same memory location)? No. So it prints [B]false[/B].

[B]3. [/B] To compare two [B]objects [/B] for their values you must use equals method
[CODE]
Integer x = new Integer(15);
Integer y = new Integer(15);
System.out.println( x.equals(y) ); // [B]prints true[/B][/CODE]

[B]4.[/B] There is one exception to this and its the String class.
[CODE]
String x = "15";
String y = "15";
System.out.println( x == y ); // [B]prints true[/B][/CODE]

Why is it true? Aren't x and y different references? NO! Java returns the same reference each time the "15" was created because Strings are immutable (can't be changed) and it is inefficient to maintain many copies of an immutable object.

To prevent Java from giving you the same reference use the new operator.
[CODE]
String x = new String("15");
String y = new String("15");
System.out.println( x == y ); // ...

NPH

Here is a quick & simple example of showing an image in java. The most import code is in the paint method. In this case, we are redefining the way a usual panel draws itself. The class ImagePanel does just this.

The other class just uses this panel in a frame and asks the user for an image to show. Hope this helps.

[CODE]import javax.swing.;
import java.awt.
;
import javax.imageio.;
import java.io.
;

//panel used to draw image on
public class ImagePanel extends JPanel
{
//path of image
private String path;

//image object
private Image img;

public ImagePanel(String path)   throws IOException
{
    //save path
    this.path = path;   

    //load image
    img = ImageIO.read(new File(path));

}

//override paint method of panel
public void paint(Graphics g)
{
    //draw the image
    if( img != null)
        g.drawImage(img,0,0, this);
}

}

//example of using image panel
class ImageFrame
{
public static void main(String[] args) throws IOException
{

    try
    {

        //create frame
        JFrame f = new JFrame();

        //ask for image file
        JFileChooser chooser = new JFileChooser();
        chooser.showOpenDialog(f);

        //create panel with selected file
        ImagePanel panel = new ImagePanel( chooser.getSelectedFile().getPath() );

        //add panel to pane
        f.getContentPane().add(panel);

        //show frame
        f.setBounds(0,0,800,800);
        f.setVisible(true);
    }
    catch(Exception e)
    {
        System.out.println ( "Please verify that you selected a valid image file"); 
    }       
}

}[/CODE]
For more help, [url]www.NeedProgrammingHelp.com[/url]