Overclockers Forums
 


Go Back   Overclockers Forums > Software > Programming Tips and Tricks > Java Help - How to do this
Reply


Welcome to the Overclockers Forums.

You are currently viewing our boards as a guest which gives you limited access to view most discussions and access our other features. By joining our free community you will have access to post topics, communicate privately with other members (PM), respond to polls, upload content and access many other special features. Registration is fast, simple and absolutely free so please, join our community today!

If you have any problems with the registration process or your account login, please contact us.

If you would prefer not to see any double-underlined words and corresponding advertisements without registering or logging in, place your cursor
here for ContentLink
 
Thread Tools
Old 11-02-09, 10:29 AM   #1
Stratus_ss
Overclockers AltOS Content Editor

 
Stratus_ss's Avatar 

Join Date: Jan 2006
Location: Ontario Canada
 
Java Help - How to do this

So I am working through a "Teach yourself java" style book and I am stumped.
One of the practice exercises asks you to create a program that creates a file and writes to it.

Quote:
Create a separate class that will handle all of the file operations. You will need to provide the file name when the object is instantiated, and then it will have a method that will call to write the data (a strand and 3 integers). It will also need to have a close method.
So if I understand the question correctly you are to write a method for each thing, one to create the file, one to write the file, one to close it.

This is what I have so far but I suspect I am not understanding how to call methods properly

Code:
public class file_ops {

	/**
	 * @param args
	 */
	public static void create_file(String[] args) throws Exception {

		//this is a class specifically to deal with file i/o
		java.io.PrintWriter output = new java.io.PrintWriter("part2.txt");
	}
public static void write_file(String[] args) throws Exception {
	//this will write to the file
	//it is here that I am kind of lost, how do I call the create_file() method for this section? 
	output.print("hello there");
	output.print(" 1");
	output.print(" 2");
	output.print(" 3");
}
public static void close_file(String[] args) throws Exception {
	//this will close the file
	output.close();
	
}

}
Anyone kick me towards the right direction?

__________________
HEAT

Those wishing to contribute to the AltOS section front page please PM me.

Leviathan41: "Playing with a controller because the mouse and keyboard is too easy is like racing with a bicycle because a car is too fast."
Stratus_ss is offline   Reply With Quote
Old 11-02-09, 11:14 AM   #2
SeanBest
Member

 
SeanBest's Avatar 

Join Date: Jul 2008
Location: James Madison University - Harrisonburg, VA
 
So I think this is what your looking for, assuming I understood what your trying to do.

You have a class that creates a file. Then that class uses another class to actually read,write, and close the file.

Code:
import java.io.*;

public class CreateFile
{
	public static void main(String[] args) throws IOException
	{
                /*Declarations*/
		FileOps file;
		String fileName;
		String words;
		int num1;
		int num2;
		int num3;
		
		fileName = "New File.txt";  //File name
		words = "Hello There!";  //Text
		num1 = 1;  //Num 1
		num2 = 2;  //Num 2
		num3 = 3;  //Num 3
		
		file = new FileOps(fileName);  //Create file with specified name
		file.write(words, num1, num2, num3);  //Writes text/numbers
		file.close();  //Close file
	}
}
Code:
import java.io.*;

public class FileOps 
{
	PrintWriter output;

	public FileOps(String name) throws IOException
	{
		output = new PrintWriter(name);  //Creates a file with specified name
	}

	public void write(String text, int first, int second, int third) 
	{
	        output.print(text);  //Write text
	        output.print(first);  //Write num1
	        output.print(second);  //Write num2
	        output.print(third);  //Write num3
	}

	public void close() 
	{
		output.close();  //Close file
	}
}
And you will end up with a text file name "New File.txt" that looks like this:

Code:
Hello There!123
Let me know if anything confuses you.

I should also mention that Java naming conventions don't allow for "_" in pretty much anything, as well as methods with two words should be side by side with the first lower and the second upper. And class names should be side by side with all parts upper. Just a little pointer if you ever get kinda serious. Style guides are important to each language.

__________________
HEAT
Motherboard -------- BIOSTAR TPower I45
CPU ------------------- Intel E8600
Memory -------------- 4GB Corsair Dominator DDR2 1066
Cooling --------------- Thermalright Ultra 120 Extreme
HDDs ----------------- Western Digital Velociraptor 300GB 10k RPM
Graphics Card ------- 2x MSI HD4870 OC Edition
Soundcard ----------- Creative X-Fi Xtremegamer
Case ------------------ Antec Nine Hundered
Power Supply ------- Corsair HX1000
OS --------------------- Win 7 x64, Mint 7
SeanBest is offline   Reply With Quote
Old 11-02-09, 12:48 PM   #3
Stratus_ss
Overclockers AltOS Content Editor

 
Stratus_ss's Avatar 

Join Date: Jan 2006
Location: Ontario Canada
 
Yes, thanks for that!
I will study this to digest exactly whats going on here. And thanks for the pointer about naming conventions, that probably would have caused problems later on

So if I understand correctly and I wanted the numbers to be entered by the user and not limited to 3 I could do something like

Code:
public void write(String text, int numbersArray[]);
in the fileOps file.

Then in the create file class I would do something like
Code:
//prompt the user
	    option = JOptionPane.showOptionDialog(frame, "Enter another number", "Select an Option",
	        JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, stringArray,
	        stringArray[0]);

if (option == JOptionPane.YES_OPTION){
	    	//ask the user for a number
	    	String user_input=JOptionPane.showInputDialog("Please enter your input to save to file);
	    	//initialize local variables
	    	int x = 0;
                numberArray[x]=Integer.parseInt(user_input);
x++
}
else
System.exit(0)


for(i=0;i<numberArray.length;i++)

{

file.append(numberArray[i]);
}

__________________
HEAT

Those wishing to contribute to the AltOS section front page please PM me.

Leviathan41: "Playing with a controller because the mouse and keyboard is too easy is like racing with a bicycle because a car is too fast."

Last edited by Stratus_ss; 11-02-09 at 12:54 PM.
Stratus_ss is offline   Reply With Quote
Old 11-02-09, 01:04 PM   #4
SeanBest
Member

 
SeanBest's Avatar 

Join Date: Jul 2008
Location: James Madison University - Harrisonburg, VA
 
You could use an array. Or just simply prompt the user for input and send each input in to be written one at a time, and honestly that's easier because an array needs to be specified to a certain size, unless you went with an ArrayList instead.

Sending them in one at a time also allows you to prompt the user for how many numbers they're inputting then run the loop that many times asking and sending in each, or use a do lopp and have it keep asking and sending in one at a time until they enter quit or just the return key. This way the method your sending into only takes one incoming variable.

the only benefit of using an array here would be if you needed the numbers for something again later and you needed them all in one group.

Store the number you get from the user in a int variable called "num" for example.

The after each input call:

Code:
file.write(num);

__________________
HEAT
Motherboard -------- BIOSTAR TPower I45
CPU ------------------- Intel E8600
Memory -------------- 4GB Corsair Dominator DDR2 1066
Cooling --------------- Thermalright Ultra 120 Extreme
HDDs ----------------- Western Digital Velociraptor 300GB 10k RPM
Graphics Card ------- 2x MSI HD4870 OC Edition
Soundcard ----------- Creative X-Fi Xtremegamer
Case ------------------ Antec Nine Hundered
Power Supply ------- Corsair HX1000
OS --------------------- Win 7 x64, Mint 7
SeanBest is offline   Reply With Quote
Old 11-02-09, 01:35 PM   #5
Stratus_ss
Overclockers AltOS Content Editor

 
Stratus_ss's Avatar 

Join Date: Jan 2006
Location: Ontario Canada
 
Here is my new problem, I have been to several basic Java sites and they all say that to evaluate strings you would do
Code:
if (string1 == string2) {
do some stuff
}
else{
do something else
}
Applying this knowledge, I have constructed the following to test the concept.

Code:
mport java.io.*;
import javax.swing.JOptionPane;

public class part3 {

	public static void main(String[] args) throws IOException
	{
                /*Declarations*/
		fileOperations file;
		String fileName;
		String words;
		String num1;
		String num2;
		String num3;
		
		fileName = "New_File.txt";  //File name
		file = new fileOperations(fileName);  //Create file with specified name
		;
		String test = new String ("done");
		if ((words = JOptionPane.showInputDialog("please enter a name")) == test) {
System.out.println("they are equal");
			file.close();  //Close file
			System.exit(0);
		}
		 else {
		num1 = 	JOptionPane.showInputDialog("please enter a number");
		num2 = 	JOptionPane.showInputDialog("please enter a number");
		num3 = 	JOptionPane.showInputDialog("please enter a number");	
		file.write(words, num1, num2, num3);  //Writes text/numbers
	}

}
}
the problem is I never get the result I expect. I tried testing the code more simply

Code:
import javax.swing.*;
public class test {

	    public static void main(String[] args){
	    String string1 = "Hi";
	    String string2 = JOptionPane.showInputDialog("please enter a string");
	    if (string1 == string2) {
	      System.out.println("The strings are equal.");
	      } else {
	        System.out.println(string1 + " " + string2);
	        }
	        }
	}
But I always get the same result string1+string2 (i.e. it always spits out "Hi Hi" regardless of what the user inputs)

Is there something wrong with my compiler?

__________________
HEAT

Those wishing to contribute to the AltOS section front page please PM me.

Leviathan41: "Playing with a controller because the mouse and keyboard is too easy is like racing with a bicycle because a car is too fast."
Stratus_ss is offline   Reply With Quote
Old 11-02-09, 02:03 PM   #6
SeanBest
Member

 
SeanBest's Avatar 

Join Date: Jul 2008
Location: James Madison University - Harrisonburg, VA
 
To compare strings you should use the compareTo() or equals() methods.

Code:
public class CompareString
{
	public static void main(String[] args)
	{
		String a = "a";
		String b = "b";
		
		if (a.equals(b))
			System.out.println("a = b");
		else
			System.out.println("a != b");
			
		if(a.compareTo(b) < 0)
			System.out.println("a < b");
		else
			System.out.println("a > b");
	}
}
the equals() method compares them character to character, where the compareTo() method compares them and will return integer values based on the comparison. equals() returns true or false like a boolean and compareTo returns an integer.

Using "==" is for primitive data types only, Strings are not primitive data types, they are Reference types.

__________________
HEAT
Motherboard -------- BIOSTAR TPower I45
CPU ------------------- Intel E8600
Memory -------------- 4GB Corsair Dominator DDR2 1066
Cooling --------------- Thermalright Ultra 120 Extreme
HDDs ----------------- Western Digital Velociraptor 300GB 10k RPM
Graphics Card ------- 2x MSI HD4870 OC Edition
Soundcard ----------- Creative X-Fi Xtremegamer
Case ------------------ Antec Nine Hundered
Power Supply ------- Corsair HX1000
OS --------------------- Win 7 x64, Mint 7
SeanBest is offline   Reply With Quote
Old 11-02-09, 02:07 PM   #7
SeanBest
Member

 
SeanBest's Avatar 

Join Date: Jul 2008
Location: James Madison University - Harrisonburg, VA
 
To further understand the compareTo() method. Use the above code then just

Code:
System.out.println(a.compareTo(b));
or anything variation a to b, b to a, and others you can create to see what int value is returned.


compareTo() will return "0" if they are the same, forgot to mention that earlier.

__________________
HEAT
Motherboard -------- BIOSTAR TPower I45
CPU ------------------- Intel E8600
Memory -------------- 4GB Corsair Dominator DDR2 1066
Cooling --------------- Thermalright Ultra 120 Extreme
HDDs ----------------- Western Digital Velociraptor 300GB 10k RPM
Graphics Card ------- 2x MSI HD4870 OC Edition
Soundcard ----------- Creative X-Fi Xtremegamer
Case ------------------ Antec Nine Hundered
Power Supply ------- Corsair HX1000
OS --------------------- Win 7 x64, Mint 7
SeanBest is offline   Reply With Quote
Old 11-02-09, 02:12 PM   #8
SeanBest
Member

 
SeanBest's Avatar 

Join Date: Jul 2008
Location: James Madison University - Harrisonburg, VA
 
Not sure if you ever looked, but the java APIs are AMAZING.

http://java.sun.com/j2se/1.5.0/docs/api/

Everything you could ever want to know about Java. I've learned a lot from just reading the APIs (even though it is boring).

__________________
HEAT
Motherboard -------- BIOSTAR TPower I45
CPU ------------------- Intel E8600
Memory -------------- 4GB Corsair Dominator DDR2 1066
Cooling --------------- Thermalright Ultra 120 Extreme
HDDs ----------------- Western Digital Velociraptor 300GB 10k RPM
Graphics Card ------- 2x MSI HD4870 OC Edition
Soundcard ----------- Creative X-Fi Xtremegamer
Case ------------------ Antec Nine Hundered
Power Supply ------- Corsair HX1000
OS --------------------- Win 7 x64, Mint 7
SeanBest is offline   Reply With Quote
Old 11-02-09, 02:18 PM   #9
Stratus_ss
Overclockers AltOS Content Editor

 
Stratus_ss's Avatar 

Join Date: Jan 2006
Location: Ontario Canada
 
Ya, I have peaked there from time to time, the problem is finding the correct information. Starting out in java means I don't know what is available I might take a look as soon as I can squeeze it in.

I do appreciate your guidance Sean, you've been (are being) a big help

__________________
HEAT

Those wishing to contribute to the AltOS section front page please PM me.

Leviathan41: "Playing with a controller because the mouse and keyboard is too easy is like racing with a bicycle because a car is too fast."
Stratus_ss is offline   Reply With Quote
Old 11-02-09, 02:21 PM   #10
SeanBest
Member

 
SeanBest's Avatar 

Join Date: Jul 2008
Location: James Madison University - Harrisonburg, VA
 
Just reading them will throw you for a loop. try just looking at specifics.

For example, you asked about comparing Strings, open the APIs and on the left side bottom box scroll down to String. Click String and in the right panel you will now see all methods the String class has available to it by default. there you will find equals() and compareTo() explained and how they work.

These are usually hard to read and understand, but once you read them you can see that they do what you want, how to use them might not be so easily explained there. So I usually then Google it looking for examples. but it's a very good place to get ideas.

__________________
HEAT
Motherboard -------- BIOSTAR TPower I45
CPU ------------------- Intel E8600
Memory -------------- 4GB Corsair Dominator DDR2 1066
Cooling --------------- Thermalright Ultra 120 Extreme
HDDs ----------------- Western Digital Velociraptor 300GB 10k RPM
Graphics Card ------- 2x MSI HD4870 OC Edition
Soundcard ----------- Creative X-Fi Xtremegamer
Case ------------------ Antec Nine Hundered
Power Supply ------- Corsair HX1000
OS --------------------- Win 7 x64, Mint 7
SeanBest is offline   Reply With Quote
Old 11-02-09, 02:22 PM   #11
SeanBest
Member

 
SeanBest's Avatar 

Join Date: Jul 2008
Location: James Madison University - Harrisonburg, VA
 
What compiler are you using btw?

__________________
HEAT
Motherboard -------- BIOSTAR TPower I45
CPU ------------------- Intel E8600
Memory -------------- 4GB Corsair Dominator DDR2 1066
Cooling --------------- Thermalright Ultra 120 Extreme
HDDs ----------------- Western Digital Velociraptor 300GB 10k RPM
Graphics Card ------- 2x MSI HD4870 OC Edition
Soundcard ----------- Creative X-Fi Xtremegamer
Case ------------------ Antec Nine Hundered
Power Supply ------- Corsair HX1000
OS --------------------- Win 7 x64, Mint 7
SeanBest is offline   Reply With Quote
Old 11-02-09, 02:34 PM   #12
Stratus_ss
Overclockers AltOS Content Editor

 
Stratus_ss's Avatar 

Join Date: Jan 2006
Location: Ontario Canada
 
java version "1.6.0_0"
OpenJDK Runtime Environment (IcedTea6 1.4.1) (6b14-1.4.1-0ubuntu11)
OpenJDK Server VM (build 14.0-b08, mixed mode)

Using Eclipse as my IDE

__________________
HEAT

Those wishing to contribute to the AltOS section front page please PM me.

Leviathan41: "Playing with a controller because the mouse and keyboard is too easy is like racing with a bicycle because a car is too fast."
Stratus_ss is offline   Reply With Quote
Old 11-02-09, 02:41 PM   #13
SeanBest
Member

 
SeanBest's Avatar 

Join Date: Jul 2008
Location: James Madison University - Harrisonburg, VA
 
Ah ok. I use jGrasp, but was going to suggest Eclipse as it has the thing where it tries to autofill the line. It gives you a lot of options when it comes to methods built in to classes. Sometimes I've seen ones I never knew were there.

__________________
HEAT
Motherboard -------- BIOSTAR TPower I45
CPU ------------------- Intel E8600
Memory -------------- 4GB Corsair Dominator DDR2 1066
Cooling --------------- Thermalright Ultra 120 Extreme
HDDs ----------------- Western Digital Velociraptor 300GB 10k RPM
Graphics Card ------- 2x MSI HD4870 OC Edition
Soundcard ----------- Creative X-Fi Xtremegamer
Case ------------------ Antec Nine Hundered
Power Supply ------- Corsair HX1000
OS --------------------- Win 7 x64, Mint 7
SeanBest is offline   Reply With Quote
Old 11-02-09, 03:06 PM   #14
SeanBest
Member

 
SeanBest's Avatar 

Join Date: Jul 2008
Location: James Madison University - Harrisonburg, VA
 
Comparison using equals() and compareTo() methods.

Code:
import java.util.*;

public class StringCompare
{
	public static void main(String[] args)
	{
		String string1 = "";
		String string2 = "";
		
		Scanner kb = new Scanner(System.in);
		
		System.out.print("Please enter string1: ");
		string1 = kb.nextLine();
		
		System.out.print("Please enter string2: ");
		string2 = kb.nextLine();
		
		if (string1.equals(string2)) 
			System.out.println("The strings are equal using the equals() method.");
		else
			System.out.println("\"" + string1 + "\"" +  " is not the same as " + "\"" + string2 + "\"");
			
		if (string1.compareTo(string2) == 0)
			System.out.println("The strings are equal using the compareTo() method.");
		else
			System.out.println("\"" + string1 + "\"" +  " is not the same as " + "\"" + string2 + "\"");
	}
}

__________________
HEAT
Motherboard -------- BIOSTAR TPower I45
CPU ------------------- Intel E8600
Memory -------------- 4GB Corsair Dominator DDR2 1066
Cooling --------------- Thermalright Ultra 120 Extreme
HDDs ----------------- Western Digital Velociraptor 300GB 10k RPM
Graphics Card ------- 2x MSI HD4870 OC Edition
Soundcard ----------- Creative X-Fi Xtremegamer
Case ------------------ Antec Nine Hundered
Power Supply ------- Corsair HX1000
OS --------------------- Win 7 x64, Mint 7
SeanBest is offline   Reply With Quote
Old 11-07-09, 07:47 PM   #15
Stratus_ss
Overclockers AltOS Content Editor

 
Stratus_ss's Avatar 

Join Date: Jan 2006
Location: Ontario Canada
 
ok I have another one for you. This time I am including the actual text and then what I typed.

Here is my code

Code:
public class PolymorphismDemo {

	public static void main(String[] args) {
		
		m(new GraduateStudent());
		m(new Student());
		m(new Person());
		m(new Object());
	}

	public static void m(Object x) {
		System.out.println(x.toString());
	}
	
	class GraduateStudent extends Student {
        }
	
	class Student extends Person{
		public String toString(){
			return "Studnet";
		}
	}
	
	class Person extends Object {
		public String toString(){
			return "Person";
			
		}
	}
}
What I cant figure out, is that I get the following error

Quote:
No enclosing instance of type PolymorphismDemo is accessible. Must qualify the allocation with an enclosing instance of type PolymorphismDemo (e.g. x.new A() where x is an instance of PolymorphismDemo).
No enclosing instance of type PolymorphismDemo is accessible. Must qualify the allocation with an enclosing instance of type PolymorphismDemo (e.g. x.new A() where x is an instance of PolymorphismDemo).
No enclosing instance of type PolymorphismDemo is accessible. Must qualify the allocation with an enclosing instance of type PolymorphismDemo (e.g. x.new A() where x is an instance of PolymorphismDemo).
By as far as I can see I typed it exactly out of the book. Is this a mistake in the book? If it is, its sure hard to follow
Attached Images
  

__________________
HEAT

Those wishing to contribute to the AltOS section front page please PM me.

Leviathan41: "Playing with a controller because the mouse and keyboard is too easy is like racing with a bicycle because a car is too fast."
Stratus_ss is offline   Reply With Quote
Old 11-07-09, 08:32 PM   #16
SeanBest
Member

 
SeanBest's Avatar 

Join Date: Jul 2008
Location: James Madison University - Harrisonburg, VA
 
Edited out ... read below!

__________________
HEAT
Motherboard -------- BIOSTAR TPower I45
CPU ------------------- Intel E8600
Memory -------------- 4GB Corsair Dominator DDR2 1066
Cooling --------------- Thermalright Ultra 120 Extreme
HDDs ----------------- Western Digital Velociraptor 300GB 10k RPM
Graphics Card ------- 2x MSI HD4870 OC Edition
Soundcard ----------- Creative X-Fi Xtremegamer
Case ------------------ Antec Nine Hundered
Power Supply ------- Corsair HX1000
OS --------------------- Win 7 x64, Mint 7

Last edited by SeanBest; 11-07-09 at 08:41 PM.
SeanBest is offline   Reply With Quote
Old 11-07-09, 08:39 PM   #17
SeanBest
Member

 
SeanBest's Avatar 

Join Date: Jul 2008
Location: James Madison University - Harrisonburg, VA
 
Try this ...

Code:
public class PolymorphismDemo 
{
	public static void main(String[] args) 
	{
		
		m(new GraduateStudent());
		m(new Student());
		m(new Person());
		m(new Object());
	}

	public static void m(Object x) 
	{
		System.out.println(x.toString());
	}
}
Code:
class GraduateStudent extends Student 
{
}
Code:
class Student extends Person
{
	public String toString()
	{
		return "Student";
	}
}
Code:
class Person extends Object 
{
	public String toString()
	{
		return "Person";
	}
}
The Person - Student - GraduateStudent are all classes. They all need to be separate classes. I'm guessing the guide your following is older, my professor still writes like that for demonstrations. It's really for example only, they're assuming your going to put each class in it's own separate .java file. This in the end will be 4 different .java files as listed above.

__________________
HEAT
Motherboard -------- BIOSTAR TPower I45
CPU ------------------- Intel E8600
Memory -------------- 4GB Corsair Dominator DDR2 1066
Cooling --------------- Thermalright Ultra 120 Extreme
HDDs ----------------- Western Digital Velociraptor 300GB 10k RPM
Graphics Card ------- 2x MSI HD4870 OC Edition
Soundcard ----------- Creative X-Fi Xtremegamer
Case ------------------ Antec Nine Hundered
Power Supply ------- Corsair HX1000
OS --------------------- Win 7 x64, Mint 7
SeanBest is offline   Reply With Quote
Old 11-07-09, 08:42 PM   #18
Stratus_ss
Overclockers AltOS Content Editor

 
Stratus_ss's Avatar 

Join Date: Jan 2006
Location: Ontario Canada
 
I would have been inclined to put classes on their own to, the line numbering indicated the same file though
This is the book that I am following, published May 2008

__________________
HEAT

Those wishing to contribute to the AltOS section front page please PM me.

Leviathan41: "Playing with a controller because the mouse and keyboard is too easy is like racing with a bicycle because a car is too fast."
Stratus_ss is offline   Reply With Quote
Old 11-07-09, 08:44 PM   #19
SeanBest
Member

 
SeanBest's Avatar 

Join Date: Jul 2008
Location: James Madison University - Harrisonburg, VA
 
http://www.amazon.com/Starting-Out-J...7644611&sr=8-2

This is the book my school uses (there is a 4th Edition out now, but I'm still using the 3rd). Great book. This book is nice in that almost every program in the book comes on a CD with the book as well. And programs written in multiple steps, each is a separate program.

Not sure why they would list them all like that with the line count continuing, but they do need to be separate classes.

Just took a look at the book through Google Books. Really strange how they list them like that in the same program it seems. I've never seen it done that way nor will my compiler take it like that.

__________________
HEAT
Motherboard -------- BIOSTAR TPower I45
CPU ------------------- Intel E8600
Memory -------------- 4GB Corsair Dominator DDR2 1066
Cooling --------------- Thermalright Ultra 120 Extreme
HDDs ----------------- Western Digital Velociraptor 300GB 10k RPM
Graphics Card ------- 2x MSI HD4870 OC Edition
Soundcard ----------- Creative X-Fi Xtremegamer
Case ------------------ Antec Nine Hundered
Power Supply ------- Corsair HX1000
OS --------------------- Win 7 x64, Mint 7
SeanBest is offline   Reply With Quote
Old 11-09-09, 11:11 AM   #20
Stratus_ss
Overclockers AltOS Content Editor

 
Stratus_ss's Avatar 

Join Date: Jan 2006
Location: Ontario Canada
 
This time I am just checking to see if I understand "Upcasting"

So say I make the following class

Code:
import java.util.*;

public class car {

	
	public static void drive(String i){
		System.out.println("I drive a " + i);
	}
and then a subclass

Code:
public class gm extends car{
	public static void main(String[] args){
	String GM = "GM"; 
	car.drive(GM);
		
	}
}
This is what upcasting is correct? Creating a method in the parent class, then invoking said method in the child class. Or did I do that backwards?

(p.s. I should change the topic of this thread to Sean, teach me java. )

__________________
HEAT

Those wishing to contribute to the AltOS section front page please PM me.

Leviathan41: "Playing with a controller because the mouse and keyboard is too easy is like racing with a bicycle because a car is too fast."
Stratus_ss is offline   Reply With Quote
Old 11-09-09, 11:20 AM   #21
SeanBest
Member

 
SeanBest's Avatar 

Join Date: Jul 2008
Location: James Madison University - Harrisonburg, VA
 
Sorta. But Upcasting is normally done using Objects. In your example your simply sending a String into another method in another class. By using "car.drive(GM)" without creating a local instance of the Object your technically Upcasting.

Here's another example:


Code:
import java.util.*;

class Instrument 
{
  public void play() 
  {
  }

  static void tune(Instrument i) 
  {
    i.play();
  }
}
Code:
class Wind extends Instrument 
{
  public static void main(String[] args) 
  {
    Wind flute = new Wind();
    Instrument.tune(flute); // Upcasting
  }
}
Upcasting is casting an Object as it's parent Object. Here the flute object is a Win Object, but it's being called by the Instrument.tune() method which is specifically an Instrument method, but because the Wind Objects are also Instruments Objects the flute Object can use the methods of the Instrument class.

Hope this makes sense. (Sorry for the lame music example, it was one I just found.)

__________________
HEAT
Motherboard -------- BIOSTAR TPower I45
CPU ------------------- Intel E8600
Memory -------------- 4GB Corsair Dominator DDR2 1066
Cooling --------------- Thermalright Ultra 120 Extreme
HDDs ----------------- Western Digital Velociraptor 300GB 10k RPM
Graphics Card ------- 2x MSI HD4870 OC Edition
Soundcard ----------- Creative X-Fi Xtremegamer
Case ------------------ Antec Nine Hundered
Power Supply ------- Corsair HX1000
OS --------------------- Win 7 x64, Mint 7
SeanBest is offline   Reply With Quote
Old 11-09-09, 12:00 PM   #22
Stratus_ss
Overclockers AltOS Content Editor

 
Stratus_ss's Avatar 

Join Date: Jan 2006
Location: Ontario Canada
 
so how about this then
Code:
public class car {

	
	public static void drive(Object x){
		
		System.out.println(x.toString());
	}
	
}
Code:
public class gm extends car{

	public static void main(String[] args){
		String GM= new String();
		GM = "I drive a gm";
		car.drive(GM);
	}

}

__________________
HEAT

Those wishing to contribute to the AltOS section front page please PM me.

Leviathan41: "Playing with a controller because the mouse and keyboard is too easy is like racing with a bicycle because a car is too fast."
Stratus_ss is offline   Reply With Quote
Old 11-09-09, 12:40 PM   #23
SeanBest
Member

 
SeanBest's Avatar 

Join Date: Jul 2008
Location: James Madison University - Harrisonburg, VA
 
More like this:

Code:
public class Car 
{
	public static void drive(Car car)
	{
		System.out.println(car.toString());
	}
}
Code:
public class GM extends Car
{
	public static void main(String[] args)
	{
		GM compact = new GM();
		Car.drive(compact);
	}
}
Your creating a GM object called compact. You then call the Car method drive() using the GM object compact. The GM object compact inherits the methods of Car because any GM object is a Car object as well.

When you run this you won't get anything but the storage place for the toString() as it isn't defined.

__________________
HEAT
Motherboard -------- BIOSTAR TPower I45
CPU ------------------- Intel E8600
Memory -------------- 4GB Corsair Dominator DDR2 1066
Cooling --------------- Thermalright Ultra 120 Extreme
HDDs ----------------- Western Digital Velociraptor 300GB 10k RPM
Graphics Card ------- 2x MSI HD4870 OC Edition
Soundcard ----------- Creative X-Fi Xtremegamer
Case ------------------ Antec Nine Hundered
Power Supply ------- Corsair HX1000
OS --------------------- Win 7 x64, Mint 7
SeanBest is offline   Reply With Quote
Old 11-09-09, 01:29 PM   #24
Stratus_ss
Overclockers AltOS Content Editor

 
Stratus_ss's Avatar 

Join Date: Jan 2006
Location: Ontario Canada
 
so if i wanted to return the string
Code:
public class gm extends car{

	public static void main(String[] args){
		gm compactGm = new gm();
		car.drive(compactGm);
	}
	public String toString(){
		return "I drive a GM";	
		}
}
with a seperate class

Code:
public class toString {
public String toString(){
	return " ";
	
}
}

__________________
HEAT

Those wishing to contribute to the AltOS section front page please PM me.

Leviathan41: "Playing with a controller because the mouse and keyboard is too easy is like racing with a bicycle because a car is too fast."
Stratus_ss is offline   Reply With Quote
Old 11-09-09, 01:32 PM   #25
SeanBest
Member

 
SeanBest's Avatar 

Join Date: Jul 2008
Location: James Madison University - Harrisonburg, VA
 
This works ... toString() doesn't need a separate class as it's only a method contained within the Car class.

Code:
public class Car 
{
	public static void drive(Car car)
	{
		System.out.println(car.toString());
	}
	
	public String toString()
	{
		return "I drive a GM compact";
	}
}
Code:
public class GM extends Car
{
	public static void main(String[] args)
	{
		GM compact = new GM();
		Car.drive(compact);
	}
}
Obiously you would want an if statement to change what String is returned with the toString statement so that you can ultimately get a different result depending on what you send in. The way listed above is a toString() for the Car class no the GM compact Object.

__________________
HEAT
Motherboard -------- BIOSTAR TPower I45
CPU ------------------- Intel E8600
Memory -------------- 4GB Corsair Dominator DDR2 1066
Cooling --------------- Thermalright Ultra 120 Extreme
HDDs ----------------- Western Digital Velociraptor 300GB 10k RPM
Graphics Card ------- 2x MSI HD4870 OC Edition
Soundcard ----------- Creative X-Fi Xtremegamer
Case ------------------ Antec Nine Hundered
Power Supply ------- Corsair HX1000
OS --------------------- Win 7 x64, Mint 7
SeanBest is offline   Reply With Quote
Old 11-09-09, 04:08 PM   #26
Stratus_ss
Overclockers AltOS Content Editor

 
Stratus_ss's Avatar 

Join Date: Jan 2006
Location: Ontario Canada
 
I just wanted to update the parent class incase anyone else is trying to do a similar thing. This is what I came up with

Code:
public class car {

	
	public static void drive(car model){
		
	displayObject(model);
	}

public static void displayObject(Object object) {
	if (object instanceof gm){
		System.out.println("I drive a GM"); 
	}
	else if (object instanceof ford){
		System.out.println("I drive a Ford");
	}
	else if (object instanceof chrysler){
		System.out.println("I drive a Chrysler");
	}
}
	

}

__________________
HEAT

Those wishing to contribute to the AltOS section front page please PM me.

Leviathan41: "Playing with a controller because the mouse and keyboard is too easy is like racing with a bicycle because a car is too fast."
Stratus_ss is offline   Reply With Quote

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT -5. The time now is 04:02 AM.


Top of PageLast Page

Home  |   Register  |   Calendar  |   FAQ  |   Search  |   Contact Us  |   Archive
Copyright © OCForums.com 2001 - 2008. All Rights Reserved.    Visit: Overclockers.com.    Advertise on OCForums


Other iNET Interactive Sites:
Web Hosting Talk | DB Forums | Mac-Forums | Hosting Catalog | Hot Scripts
Powered by vBulletin® Version 3.8.4
Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.