JAVA questissn regarding methods/classes - java

I am somewhat new to JAVA. I've been working with it in college, but I have to admit, my instructor is of absolutely no help. She hardly knows JAVA herself, but that is another issue all in itself. I've been confused as to how methods and classes work. I'm creating this program that uses two files, one "main" file, and a "test" file. I can't seem to get the "main" file correct, as the compiler keeps telling me that it cannot find the symbols, even though they are. In the "test" file, I can't seem to get the compiler to recognize the methods from the "main" file. I have made sure that the files are in the same folder. I want to combine them into one file for simplicity, but I will lose points. I've included my code so far. I'm not looking for a "fix-it" solution, I just want to figure out why it's not working. ANY help is appreciated, since my instructor isn't of much assistance Thank you kindly!
MAIN FILE:
import java.util.Scanner;
class Fruit1 {
static Scanner console = new Scanner(System.in);
public static void main(String args[]) {
String color;
String taste;
}
public Fruit1() {
// generic constructor
color = "red";
taste = "yum";
}
public Fruit1(String aColor, String aTaste) {
// constructor with parameters
color = aColor;
taste = aTaste;
}
public Fruit1(String bColor, String bTaste) {
color = bColor;
taste = bTaste;
}
String getTaste() {
return taste;
}
String getColor() {
// Accessor method
return color;
}
}
TEST FILE:
import java.util.*;
public class Fruit1Test {
static Scanner console = new Scanner(System.in);
public static void main(String args[]){
Fruit1 a = new Fruit1("pinkish-red", "sweet-tart");
Fruit1 l = new Fruit1("yellow", "tart/sour");
a.taste();
a.color();
l.taste();
l.color();
System.out.println("Your apple is " + a.color + "in color and has a " + a.taste + " taste. ");
System.out.println("Your lemon is " + l.color + "in color and has a " + l.taste + " taste. ");
System.out.println();
}
}

a.taste(); will try to find method taste(); in your main file i.e. in Fruit1.java file. However as same is not found, it will throw error at compile time only that Method taste() is not found...
All below 4 statements will FAIL as those are not present...
a.taste();
a.color();
l.taste();
l.color();
As you are creating object of class by using below statement, already values to taste and color by use of constructor public Fruit1(String aColor, String aTaste){.
Fruit1 a = new Fruit1("pinkish-red", "sweet-tart");
I believe you now want to print the values of color and taste. To print those use getter methods that you have (getColor() & getTaste())
System.out.println("Your apple is " + a.getColor() + " in color and has a " + a.getTaste() + " taste. ");
System.out.println("Your Lemon is " + l.getColor() + " in color and has a " + l.getTaste() + " taste. ");
Note
You don't need to write public Fruit1(String bColor, String bTaste){ again as you have already defined above that....
Also your below statement should be before constructor and out of psvm
String color;
String taste;
Let me know if you are unclear...
Good Luck

You never declare the fields color or taste for the object Fruit1. Instead, you created the variables in the main method.
I suggest you read some basic tutorials on Java to get the hang of things. (Oracle also provides more advanced tutorials.)

I noticed in Fruit1, you are declaring the member variables in function main(). From the looks of it, Fruit1Test should have a main() fxn but Fruit1 should not. Take out those member variables out of main() and get rid of main() in Fruit1 (put it under the 'console' variable).
I also noticed that you have 2 constructors that both take in Strings. The compiler will probably complain about that too. I don't have a compiler in front of me but that's what I can tell just from looking.

For your first problem, it seems you're misunderstanding how to declare instance fields. You're creating them inside the main function, when you should create them directly inside the class.
For your second problem, see Fahim Parkar's comment, if it applies to your case. BTW it's a good practice to always have only one class/interface/enum per file, and have the file with the same name of the class (this second part may be mandatory in Java, I don't remember for sure - it applies to public classes, but I dunno if it also applies for "default, package protected" ones).
If they're named correctly, OTOH, maybe the error is because your "main" file didn't compile, so the "test" one didn't find it...
P.S. I just noticed you have two constructors with the same signature (number of parameters and same parameter types). You must remove one.

Related

Getting class name

I am writing an administrator class that all other classes I am writing are meant to inherit from. In this case I want the classes to inherit a main method, and I am planning on implementing a factory as well. There are a few sysouts that I have to write that include various class names such as charcount, linecount and the such. For this I need to be able to get the current class name, since this method will be inherited by multiple classes. Is there a way to do this in java? You can find an example of the sysout I am looking to do below:
System.out.println("Usage: className <src>\n");
Thank you all in advance, any help is appreciated!
edit:
Hey guys!
Very sorry I wasnt clear before, I'll show the entire code below and try to further explain my idea. So what I am doing is essentially making a main method that checks to see if a file exists, and if the file exists, it will try to execute a certain function (All this will be in the command line).I am practicing factory design patterns (something I've never done before). I will use the execute part of the main method to call on some factory (not yet made) to create objects of subclasses of administrator and return things like charcount in a file and linecount in a file. The above question refers to one part of this main method that will print the usage of the subclass. So for example, I will have charcount inherit from administrator because the process of checking the file and is in the main method of administrator, however when I print the usage message, I dont want it to print "Usage: Administrator ", but "Usage: charcount ". I hope that clears things up, and sorry again for how badly I explained it above, you can find what I have so far as code below:
public class Administrator
{
private static File srcFile = null;
private static String srcFilename = "<srcFilename>";
public static void main(String[] args) throws IOException
{
//check the command line
if(args.length != 1)
{
System.out.println("Usage: charcount <src>\n");
return;
}
// Check if arguments are valid, if the srcFile exists, and if can create the dstFile.
if (args[0] != null)
{
//check <src>
srcFilename = args[0];
System.out.println( ": srcFilename '" + srcFilename + "'");
srcFile = new File(srcFilename);
if(!srcFile.canRead())
{
System.out.println("charcount: cannot open srcFile '" + srcFilename + "'");
return;
}
}
else
{
System.out.println("charcount: [OK] srcFilename = '" + srcFilename + "'");
}
}
public static int execute() {return 0;}
}
You can do something like this:
System.out.println("Class name: " + getClass().getName());
Which will return foo.bar.Baz (assuming your class is named Baz and in package foo.bar)
Or you can
System.out.println("Class name: " + getClass().getSimpleName());
Which will simply return 'Foo'
You might find this related question helpful: What is the difference between canonical name, simple name and class name in Java Class?
Edit: The question asks about doing this from the "main" method, which could be understood as public static void main(String[] args) or as the primary method in a given class hierarchy. Since the question goes on to discuss the method being inherited by multiple classes, I understood "main" as "primary". This answer wouldn't work from public static void main(String[] args) because getClass() is an instance method and can't be invoked from a static context.
Java Class class has some useful methods. You can use getClass().getSimpleName(). at runtime this method called based on object's type.
Try using this methods:
this.getClass().getCanonicalName() or this.getClass().getSimpleName().
If it's an anonymous class, you should use this.getClass().getSuperclass().getName()

Java constructor creates many null instances before the required object

this is my first question on here and I did a search before forming it, so I hope everything is as required.
I am working on a school assignment in Java. I am able to produce the required output but there are a lot of null instances created first. I don't understand why. Information about the library the professor created for the course and the code are below
Library included with this course: i2c.jar. It can be found here.
included in this Library are the classes Country and CountryDB. The API for the Country class can be found at http://130.63.94.24/~roumani/book/doc/i2c/ca/roumani/i2c/Country.html
The API for the CountryDB class can be found at http://130.63.94.24/~roumani/book/doc/i2c/ca/roumani/i2c/CountryDB.html
I am asked to create a class called Game, using the Country and CountryDB APIs.
The only attribute is db, which is an instance of CountryDB.
The constructor only sets the attribute (db) for this instance to a new CountryDB object.
The class is also meant to include a method (called qa) that follows this pseudocode:
get a reference to the database's capital city list
determine the size of this list. Cal it n.
generate a random number in [0,n) called index.
invoke get(index) on the list to get a random capital city. Call it c
get a reference to the database's data map
invoke get(c) on the map to get a reference to a country. Call it ref.
The method is then supposed to return one of two Strings (which will be clear in the code). Everything works as it should, except I get a lot of "nulls" before the desired output. When made into a List, db has size 241 so I suspect I am creating 241 null instances and 1 proper instance. I have no idea why though. I have tested every line of code in my method and the constructor was dictated by the textbook.
CODE
package ca.yorku.eecs.caps;
import java.util.List;
import java.util.Map;
import ca.roumani.i2c.Country;
import ca.roumani.i2c.CountryDB;
public class Game
{
private CountryDB db;
public Game()
{
this.db = new CountryDB();
}
public String qa()
{
List<String> capitals = db.getCapitals();
System.out.println(capitals.toString());
int n = capitals.size();
System.out.println(n);
int index = ((int) (n * Math.random()));
System.out.println(index);
String c = capitals.get(index);
System.out.println(c);
Map<String, Country> data = db.getData();
Country ref = data.get(c);
if (Math.random() > 0.5)
{
return "What is the capital of " + ref.getName() + "? \n" + ref.getCapital();
}
else
{
return ref.getCapital() + " is the capital of? \n" + ref.getName();
}
}
public static void main(String[] args)
{
Game g = new Game();
System.out.println(g.qa());
}
}
the System.out.println() statements are only there to test when the nulls occur. It clearly happens immediately because my psvm output is 241 nulls (on separate lines) followed by my desired output. Can somebody please tell me what I am doing wrong?
And, more generally (to help more people) how do you implement classes, the constructor of which instantiates another class and sets it as an attribute value?
I appreciate any help. Also, please note, I am not trying to get others to do my work for me. I've spent hours on this and my lab TA also wasn't sure why it happens either. He would have helped me correct it had he known how.
Thank you.

how to transfer variables in java

I am still fairly new to coding in java and I am trying to build a text game to help me learn. I am having issues transferring a variable to help me test out specs.
String a = user.next();
if(a.equals("warrior")){
System.out.println("You start to feel stronger, feels like you could run through a brick wall and keep on going without a scrath on you.\n" +
"Of course you might want to wait on that for awhile.\n" +
"********************************************************\n*\t\tAchievement got: Dumb as a rock!\t\t\t\t\t\t *\n********************************************************");
String specW = ("warrior");
comW (warrior);
}
public static void comW (warrior){
System.out.println("Testing1");
}
is anyone able to help me figure out why I keep having errors?
comW (specW);
}
public static void comW (String warrior){
System.out.println(warrior);
}
Do above changes in your code.
Basically you are passing a variable in comW method but the variable is not declared.
Secondly, in your comW method you didn't give parameter type.
I would recommend you to follow some tutorials carefully before posting question here.
You are creating a string variable with name specW but passing a variable warrior to comW function. So change the function parameter to specW. Also in the definition of function comW the parameter warrior is not given any type so give it a String type.
String a = user.next();
if(a.equals("warrior")){
System.out.println("You start to feel stronger, feels like you could run through a brick wall and keep on going without a scrath on you.\n" +
"Of course you might want to wait on that for awhile.\n" +
"********************************************************\n*\t\tAchievement got: Dumb as a rock!\t\t\t\t\t\t *\n********************************************************");
String specW = ("warrior");
comW (specW); // 1st Change
}
public static void comW (String warrior){ // 2nd Change
System.out.println("Testing1");
}

How to create an object by referring to a property

I want to create an object of a class by referring to its object, I think. I've been able to make it in C# but in Java it wont work. This is what I want to do:
controller.getDal().getStudentData().getPerson() = new Person(student.getIdNumber(), student.getName(), student.getAddress(), student.getTel());
But I get a error message saying:The left-hand side of an assignment must be a variable
How can I fix the problem? I've tried like doing like this:
register.AddStudent(controller.getDal().getStudentData().getPerson());
and then
System.out.println("Show info: " + controller.getDal().getStudentData().getPerson());
and the output I get is : Person#7cd0a5d9
Java doesn't have the Property syntax that c# does. you have to use a setter.
controller.getDal().getStudentData().setPerson(
new Person(/*blah blah blah*/)
);
if you control whatever type getStudentData returns, than you might have to make one.
public void setPerson(Person newPerson)
{
this.person = newPerson;
}
Right now you are trying to set a new person using a get method. You cannot set an object to a function. You are on the right track with your code:
register.AddStudent(controller.getDal().getStudentData().getPerson());
I do wonder however if in your code that a student and a person are the same thing. You did not provide enough code for me to test and to give you an guaranteed answer, but I would assumg that your code should be more like this:
register.AddStudent(controller.getDal().getStudent());
This way you are getting the student and then adding the student. I'm not sure what you are trying to accomplish but you should really be looking into set methods such as something like:
Person p = controller.getDal().getStudentData().getPerson();
p.setIdNumber = 0011559966
p.setAddress('123 C St');
Or even something along the lines of:
register.AddStudent(new Student("Billy", "Crystal", "123 C st"));
Anyway, if you had more code, I would be able to help you more, but that is the best I can think of without any real context
About:
System.out.println("Show info: " + controller.getDal().getStudentData().getPerson());
You must override the toString() method inside the Person class to the fields or string representation you want to see upon printing.
An example could be:
#Override
public String toString() {
return "Name: " + this.getName() + " Id Num: " + this.getIdNumber();
}

how to get the command line arguments from another class with java

so suppose I have a java package....
it's got the main class with the main method
and then it's got a whole bunch of other classes.....
my question is, is it possible to get the args that was passed into the main method from these other classes that are not part of the main class but in the same package...
No, not portably, there may be some trickery based on the JVM implementation but I've never seen it, and it would be a very bad idea to rely on it even if it existed.
If you want those values elsewhere, the main function needs to make them available somehow.
An easy way to do this (not necessarily the best way) is to simply store away the strings as the first thing in main and provide a means for getting at them:
Scratch2.java:
public class Scratch2 {
// Arguments and accessor for them.
private static String[] savedArgs;
public static String[] getArgs() {
return savedArgs;
}
public static void main(String[] args) {
// Save them away for later.
savedArgs = args;
// Test that other classes can get them.
CmdLineArgs cla = new CmdLineArgs();
cla.printArgs();
}
}
CmdLineArgs.java:
public class CmdLineArgs {
public void printArgs() {
String[] args = Scratch2.getArgs();
System.out.println ("Arg count is [" + args.length + "]");
for (int i = 0; i < args.length; i++) {
System.out.println ("Arg[" + i + "] is [" + args[i] + "]");
}
}
}
And, when run with the arguments a b c, this outputs:
Arg count is [3]
Arg[0] is [a]
Arg[1] is [b]
Arg[2] is [c]
The system-properties on some (?) JRE-implementations provide the system-property "sun.java.command" to get the programm-name and parameters that were used to start the program. Like "myjar.jar param1 param2 ...".
While this value doesn't even belong to the set of properties that are mentioned in the documentation, it is present in both Oracle-JRE v1.8 and OpenJRE v1.8 (tested).
I couldn't find any documentation whether this value is supported by default though (best I could find was the list in the System#getProperties() docs). Any clarification on this would be welcome. Handle with care!!!
If you don't care about OS portability, read /proc/self/cmdline or the equivalent for your OS.
See http://en.wikipedia.org/wiki/Procfs
As paxdiablo said, your main class would have to store these parameters and then either distribute or make available to needed ones. Often a good idea would be to let another class do the parsing of these parameters, and provide an object of this class instead of the raw command line to whoever needs it.
I'm kind of a newb at this, but you should be able to store the string[] args to a private instance variable, then make an accessor method for it.
E.g.,
public class test {
private String[] myArgs = new String[10];
public static void main(String[] args) {
myArgs = args;
}
public String[] getArgs() {
return myArgs;
}
}
Not sure if it will work, but that's the idea.

Categories