System.out in parameter - java

I have a test file and according to it I need to build my program the test file
is below. However, I confused by s1.showDetails(System.out); I have never met
System.out in parameter can anyone help. What to do with it??? when I am trying to write showDetails() the compiler writes mistake. my student code is beneath this Thank you in advance!
import java.util.*;
public class Q2 {
public static void main(String [] args)
{
// Start on section A
System.out.println("Question 2");
System.out.println("Start on part A");
Student s1 = new Student("John", "Smith", 42);
s1.showDetails(System.out);
Course cs = new Course("Computer science");
}
}
public class Student {
private String name;
private String familyName;
private int moduleMark;
private int total;
protected Student(String name, String familyName, int moduleMark)
{
this.name = name;
this.familyName = familyName;
this.moduleMark = moduleMark;
}
public String getName()
{
return name;
}
public String getFamilyName()
{
return familyName;
}
public int getModuleMark()
{
return moduleMark;
}
public String showDetails()
{
return (this.name + " " + this.familyName + " " + moduleMark + total);
//print(name);
}
}

System.out is a variable like every other variable.
System is a class
out is a public static variable inside System of type PrintStream. So you can access it with System.out
So System.out.println(..) is just a call to the println(..) function of a PrintStream
So your function should look like:
public String showDetails(PrintStream stream) {
...
}

The error pretty much describes what the problem is.
The method showDetails() in the type Student is not applicable for the arguments (PrintStream) at Q2.main(Q2.java:9)
The program tries to call your method with System.out which happens to be a PrintStream. So, change your showDetails to
public String showDetails(PrintStream out) {
out.println(this.name + " " + this.familyName + " " + moduleMark + total);
}
This allows the tester (I assume there is a program which tests your assignment for correctness) to give you any PrintStream, either System.out or any other PrintStream.

The error essentially means that the compiler didn't find the method with the name showDetails that takes an argument of type PrintStream. You have no need to pass the System.out to the showDetails() method. The correct way writing the showDetails() is below. Read about System.out.
public void showDetails()
{
System.out.println(this.name + " " + this.familyName + " " + moduleMark + total);
}

Your program can't compile.
Your main is using a method named showDetails that takes a PrintStream as a parameter (System.out). And you are defining only a method named showDetails without parameter.
Look at the doc of System.out. It s a field like any other of the class System. Indeed it's somewhat special as it is static but that doesn't change the game that much...
So write a method with the correct parameter list and you will get closer.
public String showDetails(PrintStream stream) {
//your code here
}
showDetails should write to the stream passed in parameter.
While you are at learning programming. Try to separate query from command. It's a good principle : a method should do one thing : either do something to your current object using a parameter or answer a query about the state of your current object. Not both.
Here you return a string and require a stream... You should better split that into 2 methods : one to get the string and then as second one to call stream.write on that string.
public String toString() {
//your code here
}
public void showDetails(PrintStream stream) {
//your code here
}

Since the print is commented out from your showDetails message there are 2 obvious solutions
The showDetails message is not meant to print out anything (despite the name) and you should just print it out in the main method
System.out.println( s1.showDetails() );
The showDetails message should print the String to any PrintStream, and then you have to adjust both the signature of that method as well as the implementation
public String showDetails(PrintStream stream) {
stream.println( ... );
}

Related

Why the output is different, java inheritance?

I've got 2 classes, car extends vehicle, Why, when I'm trying to print a new created car object the output isn't equal as I thought.
I'm running it on Eclipse, java 11
public class vehicle_13 {
private int years;
public vehicle_13(int y) {
years=y;
}
public int years() {
return years;
}
public String driving() {
return "Can drive";
}
public int speed() {
return 50;
}
public String toString() {
return "years = "+years()+"\n"+this.driving()+"\n"+"speed = "+this.speed()
+"\n"+this.money_per(); // driving() = this.driving()
}
public int money_per() {
return years*10;
}
}
public class car_13 extends vehicle_13 {
public car_13(int y) {
super(0);
}
public int speed() {
System.out.println(super.driving());
return super.speed()*2;
}
}
I expect the output of this car object .toString() to be:
years = 0
Can drive
Can drive
speed = 100
0
but the actual output is:
Can drive
years = 0
Can drive
speed = 100
0
When you concatenate the string like this:
return "years = " + years() + "\n" + this.driving() + "\n"
+ "speed = " + this.speed() + "\n" + this.money_per();
It has to execute each of the methods before it creates the string. After all, it's the result of executing the method that gets added to the string. So the println in the speed method is called when this.speed() is evaluated, then the concatenated string is returned by toString, and then the result is passed to System.out.println. So the println in speed runs before the println in main, not in the middle of it.
P.S: Long concatenation like this, is better suited to the String.format method
return String.format("years = %d\n%d\nspeed = %d\n%d",
years(), driving(), speed(), money_per());
You have called super.driving in the sub-class and that is what is evaluated first. Therefore it prints out "Can drive" first, before the result of the toString as you expected.

Why doesn't the Fourth Line End With "Arnie"?

I am "learning Java" using a tutorial. One of the lessons involves constructors calling constructors.
After the lesson I did some playing around doing "strange stuff" and I can't figure out what is happening.
I attached an image file captured from the Eclipse screen. (don't be hating).
I thought that would be better because it shows the output screen.
I would expect "name" to be "Arnie" the first time it is printed in the second constructor.
Why is it "Bertie"?
class Machine {
private String name;
private int code;
public Machine() {
this("Arnie", 0);
System.out.println("First constructor running: " + name);
}
public Machine(String name) {
this("Arnie", 0);
System.out.println("Second constructor running before 'this.name': " + name);
this.name = name;
System.out.println("Second constructor running after 'this.name': " + name);
}
public Machine(String name, int code) {
this.name = name;
this.code = code;
System.out.println("Third constructor running: " + name + " " + code);
}
}
public class Application {
public static void main(String[] args) {
Machine machine1 = new Machine();
Machine machine2 = new Machine("Bertie");
Machine machine3 = new Machine("Chalkie", 7);
}
}
It is printing the name variable that is passed in to the constructor. Leaving everything the same, you would see "Artie" if you were to change name to this.name.
The reason is that the constructor that takes the name argument is shadowing the property String name. Either change constructor argument to something other than name, or change lines 12 and 14 to be this.name.

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);

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));

Java Retrieve or Remove a value from TreeMap

I have a problem retrieving a Student's info from a list, or deleting it... Heelp... Code below:
import java.util.*;
public class Directory
{
private TreeMap<String, Student> studentList;
private int numberOfEntries;
public Directory()
{
studentList = new TreeMap<String, Student>();
numberOfEntries = 0;
}
public void addStudent(Student newStudent)
{
studentList.put(newStudent.StudentInfo(), newStudent);
//numberOfEntries++;
}
public void StudentInfo(String StudentInfo)
{
Object obj = studentList.get(StudentInfo);
System.out.println(obj);
}
public void removeStudent(String StudentInfo)
{
Object obj = studentList.remove(StudentInfo);
System.out.println(obj + "Removed");
}
public void printStudentList()
{
System.out.println("List of Students: " + studentList.keySet());
}
}
======= Student class ======== (Persons contains first, last & email)
public class Student extends Persons
{
private String Sclass;
public Student(String Lname, String Fname, String Email, String Sclass)
{
super(Lname, Fname, Email);
this.Sclass = Sclass;
}
public String StudentInfo()
{
return " Full Name " + Lastname + " " + Firstname + "\n" +
"E-Mail: " + Email + "\n" +
"Class Attending: " + Sclass;
}
public String getName()
{
return Lastname;
}
}
I could try and debug this for you, but that would defeat the purpose. (This is your homework ... and the purpose is for you to learn how to do this yourself.)
My advice is as follows:
FIRST fix the style errors:
The names of variables should always start with a lower-case letter ... unless they are static final constants.
The names of methods should always start with a lower-case letter
Method and variable names should also be meaningful and consistent. For instance:
public void removeStudent(String StudentInfo)
Here StudentInfo actually needs to a student name, not a "student info" string as created by the StrudentInfo method ...
Another example: lname and fname are not meaningful. (I can guess what they mean, but that is not good enough.)
Create yourself a tester program that created instances of those classes and performs a sequence of tests on them. Start with simple things, then move on the more complicated ones.
(In the real world, we'd set up a more formal set of "unit tests" ... but you are probably not ready for that yet.
In fact, if you choose more meaningful names, and then look carefully at how those names are used, your error should "leap out and hit you on the nose".
But you will get maximum benefit if you go through the process yourself.

Categories

Resources