Unexpected Output from Class Test - java

I have the following code:
import java.util.*;
public class Room {
ArrayList<Bed> beds = new ArrayList<Bed>();
private int BedNumber;
public void createBed(boolean isDouble) {
beds.add(new Bed(isDouble));
BedNumber++;
}
public int howManyBeds() {
return BedNumber;
}
public static void main(String[] args) {
Room p = new Room();
p.createBed(true);
p.createBed(false);
Bed test = p.beds.get(0);
System.out.println(test);
}
}
public class Bed {
private boolean isDouble;
public Bed(boolean isDouble) {
this.isDouble = isDouble;
}
public String bedSize() {
if (isDouble) {
return "Double Bed";
} else {
return "Single Bed";
}
}
}
When I compile it, Eclipse informs me that there are errors present in the code and asks me if I wish to proceed. When I do, I end up with a totally unexpected output - Bed#14ae5a5
I'm so confused as to what might be causing this. I imagine it's something stupidly simple but I'm just not seeing it.
Can anyone see what I'm missing?
UPDATE ----
Found the error which I've corrected below. I was printing the object reference instead of calling a method...
This is now printing the correct result, however, Eclipse is still informing me that something is wrong at compilation.
Is my code badly written? Can anyone determine why Eclipse isn't happy?

Your compilation errors are due to your attempt to declare two public classes in one Java file.
As for the output, you are attempting to print the Bed object--which results in Object.toString() being printed.
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
So, it prints the name of the class, "Bed," with an # sign followed by the hex value of its hash, 14ae5a5.

The println method of System.out actually calls the toString method of the parameter, in this case, a bed. However, toString is not present in your Bed class! So what did it do? It calls the toString method of Object, which returns Bed#XXXX where XXXX is the memory location of your bed.
To solve this, just add a toString method to your class. Remember to add #Override to overwrite the toString method of Object
#Override
public String toString () {
//return a string representation here
}

Related

Client Class Error in Java

Now, I also just have a simple question on the client class below, an error I'm getting, how to fix that error, and properly print (this.toString())
import java.io.*;
import java.util.Scanner;
public class IndexClient
{
File file = new File("file.txt");
System.out.println(this.toString());
}
Basically, I am getting an error on the second to last line that says identifier expected right before the after the println and before the first parentheses. Why am I getting that error, how would I fix that error, and then how would I successfully print (this.toString())?
Update Number 1:
I am not sure that this is entirely necessary; however, if you need it, my toString() method is below:
public String toString()
{
String sb = "";
for (int d = 0; d < words.size(); d++)
{
sb += "The word: " + words.get(d) + System.lineSeparator();
}
return sb;
}
Update Number 2:
I really appreciate all the help and constructive criticism of the code that I can get. I hope I didn't turn this simple question into one too complex. Thank you very much :)
Update Number 3:
I am sorry for leaving so many notes. However, I was only just wondering if this is a common question that any of you guys see a lot because it seems like this comes up a lot in class, and the teacher assisstant can't answer the question. Thanks again :)
You can't use :
System.out.println(toString());
Out side a method, you can use it inside a method or you can create your main method :
public void myMethod(){
System.out.println(toString());
}
Or
public static void main(String args[]){
System.out.println(toString());
}
You cannot have code outside a method in a java class.
You must create an object of your class to access this.
A correct minimal implementation would look like that (taken from the Online Java IDE):
import java.lang.Math; // headers MUST be above the first class
public class HelloWorld
{
// arguments are passed using the text field below this editor
public static void main(String[] args)
{
OtherClass myObject = new OtherClass("Hello World!");
System.out.print(myObject);
}
}
// you can add other public classes to this editor in any order
public class OtherClass
{
private String message;
private boolean answer = false;
public OtherClass(String input)
{
message = "Why, " + input + " Isn't this something?";
}
public String toString()
{
return message;
}
}

Java return multiple strings in one method

I am attempting to write a program which asks users what their pet name is, species, finds out thirst level and gives a response accordingly.
I would appreciate if someone could help me with a problem im having, in each of the 2 methods askpetname and thirstlevel there are 2 strings i want accessible throughout the entire class without using global variables.
Can someone tell me what it is i am doing incorrectly or point me in the right direction.
Also, i understand that my excess use of methods for tedious tasks is bad practice but it helps with memorising syntax.
Thanks.
class dinoo
{
public static void main(String[] p)
{
explain();
output();
System.exit(0);
}
public static void explain()
{
print("The following program demonstrates use of user input by asking for pet name.");
return;
}
public static String askpetname()
{
Scanner scanner = new Scanner(System.in);
print("Name your dinosaur pet!");
String petname = scanner.nextLine();
print("Awesome, cool dinosaur name, what species is " + petname+ " ?");
String petspecies = scanner.nextLine();
return petname, petspecies;
}
public static int thirstlevel()
{
Random ran = new Random();
int thirst = ran.nextInt(11);
int hunger = ran.nextInt(11);
return thirst,hunger;
}
public static String anger(int thirst, int hunger)
{
double angerscore = (thirst+hunger)/2;
String temper;
if(angerscore<=2)
{
temper = "Serene";
}
else if(3<=angerscore<=6)
{
temper= "Grouchy";
}
else if(6<angerscore)
{
temper = "DANGEROUS";
}
return temper;
}
public static String warning()
{
if (temper.equals("Serene"))
{
print("He's looking happy!");
}
else if(temper.equals("Grouchy"))
{
print("Ahhh hes a bit "+temper+", you better start feeding him before he gets mad!");
}
else if(temper.equals("DANGEROUS"))
{
print("GET OUT OF THERE, HES " + temper+"!!!. He will have to be put down for everyones safety.");
}
}
public static void output()
{
print(askpetname() + "'s, thirst level is "+thirstlevel()+"/10");
return;
}
public static String print(String message)
{
System.out.println(message);
return message;
}
}
That code won't compile since you can't have:
return string1, string2;
or
else if(3<=angerscore<=6)
Instead of trying to return multiple Strings, your best bet is to create a class, say called Pet, one that holds String fields for the pet's name, a Species field for its species, as well as any other fields for hunger, thirst ... that would best encapsulate all the data that makes up one logical "pet" as well as a methods such as getAnger() that returns a value for anger depending on the Pet's state. Then you can create and return a viable Pet object from your creational method.
Also, your code has lots of compilation errors, suggesting that you could improve the way that you create your code. Never try to add new code to "bad" code, to code that won't compile. If possible, use an IDE such as NetBeans, Eclipse, or IntelliJ to help you create your programs. The IDE's will flag you if any of your code contains compilation errors, and then the key is: don't add new code until you've first fixed the existing compilation error. If you can't use an IDE, then you must compile early and often, and do the same thing -- fix all errors before adding new.
First, I would recommend shooting through a tutorial first before attempting this, do all the hello worlds covering scope, objects, arrays and functions. Get familiar with Object Oriented Style, although thats not even procedural programming ... nothing returns 2 objects ... always 1 (it could be an array containing many objects, but an array is a single object)
Moving on,although this is terrible coding practice, but its ok for a beginner,since your functions are all static, create a private static variable inside each function and create getter functions
//convert
String petname = scanner.nextLine();
// To this
private static String petname = scanner.nextLine();
// Then add this below it
public static String getPetName()
{
return petname;
}
and same for every piece of data you need.
Now remove the return statement from all of your functions and declare return type as void
Then call all functions from Main,
askpetname();
thirstlevel();
then print final output (after you have called the functions) as such
System.out.println("Petname: " + getPetname + " ThirstLevel: " + getThirstLevel() + " HungerLevel: " + getHungerLevel);

Java code does not return anything even though it is supposed to

I'm just new to Java OOP, and I hardly understand about the class and stuff. I tried to write some code to understand but I didn't succeed. Here is my code, I expected it to return the number of eggs but I don't know why it returns nothing.
class EggCounter {
private int egg;
{
egg = 0;
}
public void eggAdd()
{
egg = egg + 1;
}
public void eggBreak()
{
egg = egg - 1;
}
public void eggAddDozen()
{
egg = egg + 12;
}
public int getEgg()
{
return egg;
}
}
public class EggTest
{
public static void main(String[]args)
{
EggCounter egg = new EggCounter();
egg.eggAdd();
egg.eggAddDozen();
egg.eggBreak();
egg.getEgg();
}
}
It does return 12. Replace the egg.getEgg(); line in your main method with System.out.println(egg.getEgg()); and you will notice it prints 12.
It is returning, it's just that you do nothing with the return value of getEgg. What you need to do is store it into the variable or do something with it. return <value> only returns the given value to the callee, you must store it to use it. Example:
int eggCount = egg.getEgg();
System.out.println(eggCount);
Here, the assignment of eggCount calls egg.getEgg(). The call resolves when the number of eggs is returned, which assigns the return value to eggCount. Finally, it will print out eggCount. If you need the result of egg.getEgg() later, you can simply just output the following:
System.out.println(egg.getEgg());
How this works is the method egg.getEgg() is called. The return value is then resolved, which is passed into the print statement. This gets rid of storing it into a variable you can use later.

Return statement not working when calling another method

I have recently started experimenting with the return statement, and I have a small doubt relating to it- When I have a method which calls another method, will the return statement of that method which I am calling be displayed?
Let be give an example to make it clearer-
/** Program to test return statment */
public class Test
{
public static void main(int a)
{
EvenOrOdd(a);
}
private static boolean EvenOrOdd(int a)
{//I can declare as public and run directly but then what is the point in calling the method?
if(a%2==0)
{
System.out.println("The output is true.");//Displays
return true;//Does not display(As in that window does not pop up with the result.)
}
else
{
System.out.println("The output is false.");//Displays
return false;//Does not display
}
}
}
If I were to simply remove the main method(or even make the second method public and run that directly), my return statement is displayed however if I attempt to call the method and run the program my return statement isn't displayed.
So is this just a problem I am facing or is it a general rule in Java that the return statement doesn't work when you call another method(which has a return statement)?
If it is the latter, then I apologise, I was not aware of this.
Thanks...
***UPDATE***
It seems that nobody has understood what I exactly mean. I will give another example-
Please run this program-:
/** Program to test Return statment;simple program to return sum of two digits */
public class Return_Test
{
public static int main(int a,int b)
{
return a+b;//What I am lloking for is that box in which this is displayed.
}
}
A return statement only returns the value ,does not Display it
If you don’t catch the return value , how can it be displayed? add something like this and try
,
public class Test
{
public static void main(int a)
{
boolean temp=EvenOrOdd(a);
if(temp)
System.out.println("Output is True");
else
System.out.println("Output False(not even )");
//Or you can directly call the method as' System.out.println(EvenOrOdd));'
}
private static boolean EvenOrOdd(int a)
{//I can declare as public and run directly but then what is the point in calling the method?
if(a%2==0)
{
System.out.println("The output is true.");//Displays
return true;//Does not display
}
else
{
System.out.println("The output is false.");//Displays
return false;//Does not display
}
}
}
And Please try learning some good Naming Conventions , Classes are Named like this ,
FirstSecond,TestException(Each Word Starts with a Capital Letter) etc , methods start with a small letter , isPrime() , isEven(),
What a lot of other responders don't know is that when you run a method in BlueJ, it executes the method, and if the the return value of the method is non-void, it is shown in a popup dialog by invoking toString. That's what the questioner means by the value being displayed.
The answer to the user's original question is that by surrounding the method with a void return, it "hides" the result. So this code:
public void callMe1(int a)
{
EvenOrOdd(a);
}
will not display the return. But if you adjust the return type and actually return the value of the inner call:
public int callMe2(int a)
{
return EvenOrOdd(a);
}
Then BlueJ will display the returned value. The display aspect is down to BlueJ, but the rules for whether or not the value gets returned are the same as in Java; void means no return.
Within the body of the method, you use the return statement to return the value. It will not print anything on its own.
Changes done - System.out.println(EvenOrOdd(5));
public class Test {
public static void main(String[] args) {
System.out.println(EvenOrOdd(5));
}
private static boolean EvenOrOdd(int a) {// I can declare as public and run directly but then what is the point in
// calling the method?
if (a % 2 == 0) {
System.out.println("The output is true.");// Displays
return true;// Does not display
} else {
System.out.println("The output is false.");// Displays
return false;// Does not display
}
}
}
Output
The output is false.
false
You never actually display the return result from the method...
The name of the method is consuming EvenOrOdd returning true or false is ambigious, may isEven would be better...
You could try something like...
System.out.println(a + " is even = " + EvenOrOdd(a));
You should also avoid using multiple return statements within a single method, it can quickly become confusing as to how the method actually works, in your case, you can reduce the over complexity at the same time, for example...
private static boolean isEven(int a)
{
boolean isEven = false;
if(a%2==0)
{
System.out.println("The output is true.");//Displays
isEven = true;//Does not display
}
return isEven;
}
first change your main signature from main(int a) to main(String [] args) otherwise you will get following runtime exception :
Error: Main method not found in class yourpackagename.Test, please define the main method as:
public static void main(String[] args)
well you didn't print the value return from function :
in your main do this:
System.out.println(EvenOrOdd(5));

How to parse Bank information into particular format, plus java questions

Doing a java assignment in CSE 205 at ASU, and I'm having a hard time understanding parsing. I've looked through our online textbook, and parsing rarely comes up and it's never given a full explanation. I've looked through the java api documentation a few times and I never understand what it's saying, so I hope someone isn't too frustrated as to explain how to do it.
The class is:
BankParser
The BankParser class is a utility class that will be used to create bank objects from a string. The BankParser class cannot be instantiated. It has the following method:
public static Bank bankParser(String lineToParse)
The bankParser method's argument will be a string in the following format:
bankName/bankID/city,state
A real example of this string would be:
Bank Arizona/10001/Phoenix,AZ
The bankParser method will parse this string, pull out the information, create a new bank object, set the attributes of the object, and return it.
So far this is my setup:
public class BankParser {
public static Bank bankParser(String lineToParse) {
}
}
Also, in my Bank class I have this toString method:
public String toString() {
String printInfo = ("\nBank name:\t" + bankName + "\nBank ID:\t" + bankID + "\nBank address:\t" + bankAddress + "\n");
return printInfo;
It gives me 2 markers in eclipse: that this overrides java.lang.Object.toString, and that the return type is missing. What does this all mean?? The return type is String, I don't see what the problem is with that, but the override I'm clueless
EDIT; This is what I've come up with for bankParser
public static Bank bankParser(String lineToParse) {
String[] returnValue = lineToParse.split("/");
Bank temp = new Bank();
temp.setbankName(returnValue[0]);
temp.setbankID(returnValue[1]);
temp.setbankAddress = (returnValue[2]); //this one won't work, see below
return temp;
}
}
And THESE are the methods in Bank and Address that apply to bankParser
public void setBankName(String bank1) {
bankName = bank1;
}
public void setBankID(String bankID1) {
bankID = bankID1;
}
public void setBankAddress(String city, String state) {
bankAddress.setCity(city);
bankAddress.setState(state);
}
In Address.java:
public void setCity(String city1) {
city = city1;
}
public void setState(String state1) {
state = state1;
}
I would use library like Apache Common CSV for reading and writing.
Reader in = new StringReader("bankName/bankID/city,state");
Iterable<CSVRecord> parser = CSVFormat.newBuilder()
.withDelimiter('/')
.parse(in);
for (CSVRecord csvRecord : parse) {
...
}
Your bankParser method is empty. It needs to return a Bank object, and Java will complain until you do this. You could always have it return null for now til, make it at least a compilable stub you figure this out:
public static Bank bankParser(String lineToParse) {
Bank returnValue = null;
// TODO: create a Bank object, assign to returnValue
return returnValue;
}
As for your override bit, are you getting an error message? Or a warning? The code you've posted seems kosher, so it should compile. Please show the actual full message.
As for your actual parsing, I'd use String#split("/") to split the lineToParse into an array of tokens and then work with each token, create arguments for a Bank constructor call and create a Bank object.
i.e., code to show the concept:
String text = "Bank Arizona/10001/Phoenix,AZ";
String[] tokens = text.split("/");
System.out.println(java.util.Arrays.toString(tokens));

Categories

Resources