[Hi, guys. I'm learning Java with Cay Horstmann's 'Java SE8 for the Really Impatient'. Studying chapter 4]
I want to call the toString() method of the parent class and add something to it. Unfortunately, the call to the toString() method of the parent class seems not to be working.
So far I've got these classes:
public class Point {
private double _x = 0;
private double _y = 0;
public Point(double x, double y) {
_x=x;
_y=y;
}
#Override
public String toString() {
String theString = getClass().getSuperclass().toString() + " => " + getClass().getCanonicalName();
theString += "[";
int i=0;
for (Field theField : getClass().getDeclaredFields()) {
theField.setAccessible(true);
try {
if (i>0) theString += ", ";
theString += theField.getName() + ": " + theField.get(this).toString();
i++;
} catch (IllegalArgumentException ex) {
Logger.getLogger(Point.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("err1");
} catch (IllegalAccessException ex) {
Logger.getLogger(Point.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("err2");
}
}
theString += "]";
return theString;
}
...
}
public class LabeledPoint extends Point {
private String _label = "";
public LabeledPoint(String label, double x, double y) {
super(x, y);
this._label = label;
}
...
}
And I call them with this main method:
public static void main (String[] args) {
LabeledPoint lp1 = new LabeledPoint("FirstPoint", 10.5, 30);
System.out.println("The new point is:");
System.out.println(lp1);
}
So, I was expecting to get something like this:
Point[_x: 10.5, _y:30.0]=>LabeledPoint[_label: FirstPoint]
But instead, I'm getting :
Point=>LabeledPoint[_label: FirstPoint]
That is, the getClass().getSuperclass().toString() is not executing Point.toString(), but it's just printing out the canonical name.
Why is that?
You seem to need super.toString() instead of getClass().getSuperClass().toString()
OK, guys. (I don't know how good this is, but it works)
The Point class looks like this:
public class Point {
private double _x = 0;
private double _y = 0;
public Point(double x, double y) {
_x=x;
_y=y;
}
#Override
public String toString() {
String theString = super.toString() + "=>" + getClass().getCanonicalName();
//The following creates an array of fields that includes the parent 'Point's fields if the object is an instance of a direct child class of Point
Field[] theFields;
if (this.getClass() == Point.class) {
theFields = getClass().getDeclaredFields();
} else {
theFields = new Field[Point.class.getDeclaredFields().length+getClass().getDeclaredFields().length];
System.arraycopy(
Point.class.getDeclaredFields(),
0,
theFields,
0,
Point.class.getDeclaredFields().length
);
System.arraycopy(
getClass().getDeclaredFields(),
0,
theFields,
Point.class.getDeclaredFields().length,
getClass().getDeclaredFields().length
);
}
theString += "[";
int i=0;
for (Field theField : theFields) {
theField.setAccessible(true);
try {
if (i>0) theString += ", ";
theString += theField.getName() + ": " + theField.get(this).toString();
i++;
} catch (IllegalArgumentException ex) {
Logger.getLogger(Point.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("err1");
} catch (IllegalAccessException ex) {
Logger.getLogger(Point.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("err2");
}
}
theString += "]";
return theString;
}
...
}
Related
I have a file named "EE.txt" that contains the string: "E R R O R". As you can see in the compiler notes I have posted, I'm trying to call Huffman Tree and pass EE.txt along with it, for the filename. Anyone have any suggestions?
HuffmanNode.java
public class HuffmanNode implements Comparable
{
public String letter;
public Double frequency;
public HuffmanNode left, right;
// - add constructors to initialize letter and frequency, etc.
public HuffmanNode(String letter, Double frequency)
{
this.letter = letter;
this.frequency = frequency;
}
public HuffmanNode(String letter, Double frequency)
{
Double freq = Double.parseDouble( frequency );
this.letter = letter;
this.frequency = freq;
}
public HuffmanNode(HuffmanNode left, HuffmanNode right)
{
this.left = left;
this.right = right;
this.letter = left.letter + right.letter;
this.frequency = left.frequency + right.frequency;
}
public String toString()
{
return "<" + this.letter + ", " + this.frequency + ">";
}
public int compareTo(Object o)
{
HuffmanNode huff = (HuffmanNode) o;
return this.frequency.compareTo( huff.frequency );
}
}
HuffmanTree
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class HuffmanTree {
HuffmanNode root;
// - add a constructor to init the Tree from a HuffmanNode
public HuffmanTree(HuffmanNode huff)
{
this.root = huff;
}
// print legend
public void printLegend()
{
this.printLegend(this.root, "");
}
private void printLegend(HuffmanNode t, String s)
{
if( t.letter.length() > 1 )
{
this.printLegend( t.left, s + "0");
this.printLegend( t.right, s + "1" );
}
else
{
System.out.print( t.letter + "=" + s );
}
}
// takes a String for the file name containing our input (letter & frequency data).
// The letters and frequencies are all in the first line of the file, with spaces as separators.
// (You may assume each separator is a single space).
public static BinaryHeap fileToHeap(String filename)
{
try {
BufferedReader br = new BufferedReader(new FileReader( filename ));
String line = br.readLine();
br.close();
String[] key = line.split(" ");
HuffmanNode[] huffs = new HuffmanNode[ key.length / 2];
int i = 0;
int j = 0;
while( i < key.length )
{
huffs[ j ] = new HuffmanNode( key[i], key[i + 1]);
// System.out.println( key[i] + " " + key[i + 1 ] );
i = i + 2;
j++;
}
BinaryHeap heap = new BinaryHeap( huffs );
return heap;
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static HuffmanTree createFromHeap(BinaryHeap b)
{
try {
while( b.getSize() > 1 )
{
HuffmanNode huff1 = (HuffmanNode) b.deleteMin();
HuffmanNode huff2 = (HuffmanNode) b.deleteMin();
HuffmanNode huff = new HuffmanNode( huff1, huff2 );
b.insert( huff );
}
HuffmanTree tree = new HuffmanTree( (HuffmanNode) b.deleteMin() );
return tree;
} catch (Underflow e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
// - the main method will go here, as well as code to take
// a command-line argument for the input file name
/**
* #param args
*/
public static void main(String[] args) {
**// TODO Auto-generated method stub
BinaryHeap bheap = HuffmanTree.fileToHeap( "EE.txt");
bheap.printHeap();
HuffmanTree htree = HuffmanTree.createFromHeap( bheap );
htree.printLegend();
}**
}
I believe it is the main method that is causing all of the problems. I just am not quite sure how to edit it.
Compiler:
HuffmanEncoder % java HuffmanTree EE.txt
Exception in thread "main" java.lang.NumberFormatException: For input string: "R"
at java.base/jdk.internal.math.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2054)
at java.base/jdk.internal.math.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
at java.base/java.lang.Double.parseDouble(Double.java:735)
at HuffmanNode.<init>(HuffmanNode.java:16)
at HuffmanTree.fileToHeap(HuffmanTree.java:53)
at HuffmanTree.main(HuffmanTree.java:99)
Below is the commented line, where I'm getting an unreachable error:
public class HotelRoom{
private int rNo;
private int dRented;
private String rType;
private String occName;
**type of accomodation is checked below**
if(rType=="king"){ this.rType=rType; }
else if(rType=="queen"){ this.rType=rType;}
else if(rType=="suite"){ this.rType=rType;}
else{this.rType = "queen"; } }
**accessor**
public int getRoomNumber(){ return rNo; }
public int getDaysRented(){ return dRented; }
**mutator**
public String getRoomType(){ return rType; }
public String getOccupantName(){return occName; }
**setting the value of occupant based on the conditions**
public boolean setOccupant(String guestName, int days){
if(this.occName!=null){ return false; }
this.occName=guestName; this.dRented = days; return true; }
advance method
public void advanceDay(){
this.dRented = this.dRented - 1;
if(this.dRented <= 0){ this.occName = null; this.dRented = 0;}}
toString method:
public String toString(){String out = "";
if(occName!=null){out = "Rented"; return out;}
else{ out ="Free"; return out;}
Error line -"unreachable error":
return "HotelRoom" + rNo +":" + rType + "-" + out;
}
public static void main (String[] args){
HotelRoom r1 = new HotelRoom(007,"king");
System.out.println(r1);
}
}
The method toString (that I report here reformatted for readable reasons):
public String toString() {
String out = "";
if (occName != null) {
out = "Rented";
return out; // Exit here
} else {
out ="Free";
return out; // or exit here
}
// Never reachable
return "HotelRoom" + rNo +":" + rType + "-" + out;
}
the last row is never reachable because you return from the previous if block and also in the else block, so there is no chance to reach the last line.
I suppose that you like the following behaviour:
public String toString() {
String out = "";
if (occName != null) {
// Just set out variable
out = "Rented";
} else {
// Just set out variable
out ="Free";
}
// Return a complete string using the previous out variable
return "HotelRoom" + rNo +":" + rType + "-" + out;
}
A tip: format always your code so that it is more human readable. A code that is easy to read is also a code that is easy to study to find errors.
I have to be able to convert some variables in my class. I have a boolean variable, WaGa (Stands for Workstation/Gaming computer), and if it's true, I want to convert String WorGam
I have to do this through service and support methods, and I keep trying, but I constenly fail. It just prints out what's in the driver. HELP.
public class Graphics
//instance data
{
private int Ram;
private String Brand;
private int Res;
private int BiWi;
private int BaCl;
private boolean K4;
private boolean WaGa;
private String WorGam;
//boolean WaGa, boolean K4, int BaCl, int BiWi, int Res, String Brand, int Ram
public Graphics (int R, String B, int Re, int Bi, int Ba, boolean K4, boolean Wa, String Wor ) // constructor
{
Ram = R;
Brand = B;
Res = Re;
BiWi = Bi;
BaCl = Ba;
K4 = K4;
WaGa = Wa;
Wor = WorGam;
}
public int get_Ram() //Accessor Method - there are 3 of them
{
return Ram;
}
public String get_Brand() //Accessor Method - there are 3 of them
{
return Brand;
}
public int get_Res() //Accessor Method - there are 3 of them
{
return Res;
}
public int get_BiWi() //Accessor Method - there are 3 of them
{
return BiWi;
}
public int get_BaCl()
{
return BaCl;
}
public boolean get_K4()
{
return K4;
}
public String WorGam(boolean WaGa)
{
String WorGam;
if ( WaGa == true) {
return WorGam = "Workstation";
} else {
return WorGam = "True";
}
}
public String toString()
{
return ("Ram" + " " + Ram + ". " + "Brand:" + " " + Brand + ". " + "Resolution" + " " + Res + ". " + "Processer" + " " + BiWi + "." + " " + "Base Clock" + " " + BaCl+ " " + "K4?" + " " + K4+ " " +WorGam);
}
}
public class Graphicse_Driver
{
public static void main(String [] args)
{
Graphics unique=new Graphics(4, "Nvinda", 6, 7, 9, false, false, "sdf" );
System.out.println(unique);
You may need to reread you code to make sure there aren't any other mistakes in your code, but this is the root of your problem.
In order to access the WarGam getter, you need to call:
System.out.println(unique.WarGam());
When you do System.out.println(unique), you are trying to print out the entire Graphics object instead of just the WarGam string.
You then should change your WarGam() method to look like the following:
public String WorGam()
{
if (WaGa) {
return "Workstation";
}
return "Gaming";
}
Here is a more in depth explanation of the changes:
WaGa is a private variable of your Graphics class. Since the WarGam() method is in the same Graphics class, it already had access to the WaGa variable, so you do not need to pass it in.
if(WaGa == true) is just a wordier way of writing if(WaGa).
Instead of creating a String WorGam variable, you can just return the string you want directly.
The else surrounding the second return is unnessary since that code will only be hit if the first return is skipped.
After these changes, the private String WarGam variable is really not necessary either.
public String worGam(boolean waGa) {
if (waGa)
return "Workstation";
else
return "Gaming";
}
You need to correct your worGam() function:
public String worGam(boolean waGa) {
if (waGa == true)
return "Workstation";
else
return "True";
}
And the main() function:
public static void main(String [] args) {
Graphics unique = new Graphics(4, "Nnn", 6, 7, 9, false, false, "xxx");
System.out.println(unique.WorGam(false));
}
Hi I am new to java and looking for advice.
I want to take the result of the method Country_name and covert this result to an int and pass it in to the method calc_pop_pre_sq_ft.
From the example below, I enter France which is associated with a String result of "66 Million".
How would I take the String "66 Million" and change this to the int 66 and pass this in to my method?
At the moment I am passing 66 manually
calc1.calc_pop_pre_sq_ft(66,2);
I get the output
Country Population is 66million
Population is 33 Million people per square mile
Do I need to setup an array with String and int values associated with each String and then pass location of a country in that Array in to the method?
public class StringTest {
String Country_Name;
String Country_Name(String eName){
if (eName.equals ("UK")) {
Country_Name = "60";
} else if (eName.equals ("USA")) {
Country_Name = "318";
} else if (eName.equals ("Japan")) {
Country_Name = "127";
} else if (eName.equals ("France")) {
Country_Name = "66";
}
else {
Country_Name = "no country selected";
}
return Country_Name;
}
public int calc_pop_pre_sq_ft( int enter_Popu_in_Million, int enterSqumiles) {
int a_popu_per_sq_m = enter_Popu_in_Million / enterSqumiles;
return a_popu_per_sq_m;
}
public static void main(String[] args) {
StringTest calc1 = new StringTest();
int aSquaremiles = calc1.calc_pop_pre_sq_ft(66,2);
String aCountry = calc1.Country_Name("France");
System.out.println("Country Population is " + aCountry + " million");
System.out.println("Population is " + aSquaremiles + " Million people per square mile");
}
}
In Java, each basic data type has its own parser method implemented in his corresponding class. If you want to obtain an int out of your String returning method, you could do something like:
String aCountry = calc1.Country_Name("France");
int country_number = Integer.parseInt(aCountry);
Note that aCountry will keep having a String stored, but now you will have this String as an int stored in country_number.
Moreover, you can actually return an int from your Country_name method. It'd be like:
int Country_Name(String eName){
int Country_Name;
if (eName.equals ("UK")) {
Country_Name = 60;
} else if (eName.equals ("USA")) {
Country_Name = 318;
} else if (eName.equals ("Japan")) {
Country_Name = 127;
} else if (eName.equals ("France")) {
Country_Name = 66;
}
else {
Country_Name = -1;
}
return Country_Name;
}
Then, when you call the method, you should control that it's not returning -1, since this would mean that no countries were selected. Hope it helps.
To convert a String to an int you can do the following:
try {
return Integer.parseInt(myStringNumber);
} catch (NumberFormatException e) {
log.error("This is not a number.");
}
Try this code. I think this program will help you a lot.
public class StringTest {
String Country_Name;
String Country_Name(String eName){
if (eName.equals ("UK")) {
Country_Name = "60";
} else if (eName.equals ("USA")) {
Country_Name = "318";
} else if (eName.equals ("Japan")) {
Country_Name = "127";
} else if (eName.equals ("France")) {
Country_Name = "66";
}
else {
Country_Name = "-1";
}
return Country_Name;
}
public int calc_pop_pre_sq_ft( int enter_Popu_in_Million, int enterSqumiles) {
int a_popu_per_sq_m = enter_Popu_in_Million / enterSqumiles;
return a_popu_per_sq_m;
}
public static void main(String[] args) {
StringTest calc1 = new StringTest();
int aCountry = Integer.parseInt(calc1.Country_Name("France"));
if (aCountry != -1){
int aSquaremiles = calc1.calc_pop_pre_sq_ft(aCountry,2);
System.out.println("Country Population is " + aCountry + " million");
System.out.println("Population is " + aSquaremiles + " Million people per square mile");
}
else{
System.out.println("No country selected.");
}
}
I have been trying and trying for a while with this and I just seem to cannot solve it.
I am supposed to extract classes from a Java-file and print in a shape UML-diagram, in the IDE or writing on a file
e.g the program
public class Complex {
private int re;
private int im;
public Complex(int re, int im) {
this.re = re;
this.im = im;
}
public Complex add(Complex h) {
return new Complex(this.re + h.re, this.im + h.im);
}
public Complex sub(Complex h) {
return new Complex(this.re - h.re, this.im - h.im);
}
public Complex mul(Complex h) {
int a = re;
int b = im;
int c = h.re;
int d = h.im;
return new Complex(a * c - b * d, b * c + a * d);
}
public Complex div(Complex h) {
int a = re;
int b = im;
int c = h.re;
int d = h.im;
return new Complex((a * c + b * d) / (c * c + d * d), (b * c - a * d)
/ (c * c + d * d));
}
public String toString() {
if (im >= 0) {
return re + " + " + im + "i";
} else
return re + " " + im + "i";
}
}
Should generate something like:
a Complex
b int re
b int re
a Complex(re:int, im:int)
a add():Complex
a sub():Complex
a mul():Complex
a div():Complex
a toString():String
a main()
I have started with stripping the first parenthesis from the file;
import java.io.*;
public class ClassExtract {
public static void main(String[] args) {
ClassExtract obj = new ClassExtract();
obj.removeBracket("Complexx.txt");
}
public void removeBracket(String filnamn) {
try {
File f = new File(filnamn);
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter("noparanthesis_" + filnamn);
BufferedWriter bw = new BufferedWriter(fw);
String rad = br.readLine();
while (rad != null) {
rad = rad.replaceAll("\\(", " ");
bw.write(rad);
bw.newLine();
rad = br.readLine();
}
bw.close();
br.close();
} catch (FileNotFoundException e) {
System.out.printf("The file " + filnamn + " was not found.");
} catch (IOException e) {
System.out.printf("Writing error.");
}
}
}
I have thought of different ways of approaching this problem. The way that I think would be easiest would be to strip everything after collected the head public class Complex, which would mean the rest of the file would look something like:
public Complex int re, int im
public Complex add Complex h
public Complex sub Complex h
etc and do the same and read the index of the lines.
I actually feel very lost and I have hard to tackle this problem, any help would really be appreciated.
As Qwe says in the comment, you would be much better off looking at the Java Reflection APIs.
These let you inspect a class and list its methods, superclasses, interfaces and so on.
By tackling this problem with regexes/text analysis, you are basically trying to write a partial Java parser, which is an entirely unnecessary amount of pain!