Can someone explain to me the output of this code? - java

I am confused on the output of the code. I want to know for each call on variables i and s, which class is used to call the variables. The question involves variable shadowing. Also I want to know how s keeps on changing throughout the lines in the main method.
public class A {
public int i = 0;
public static String s = "";
public A(int i) {
System.out.println(i);
s += "x";
}
public A debug() {
if (this instanceof B) {
System.out.println("Spam");
s += "s";
}
return this;
}
}
public class B extends A {
public int i = 100;
public static String s = "s";
public B(int i, String s) {
super(i);
this.i += 5;
this.s = s;
}
public static void main(String[] argv) {
String s = "";
B b = new B(0, s);
System.out.println(b.i + " " + b.s);
s += "foo";
A a = new B(42, s);
System.out.println(a.i + " " + a.s);
System.out.println(b.debug().s + " " + b.i + " " + b.s);
System.out.println(a.debug().s + " " + a.i + " " + a.s);
}
}
Here is the output of that code:
0
105
42
0 xx
Spam
xxs 105 foo
Spam
xxss 0 xxss

public class A {
public int i = 0; //not changed, because it is not overrided
public static String s = "";
public A(int i) {
System.out.println(i); //1. 0, 3. 42
s += "x"; //After second run s="xx", because it is static
}
public A debug() {
if (this instanceof B) {
System.out.println("Spam"); //5, 7. Spam
s += "s"; //s = "xxs", than "xxss" because it is static
}
return this;
}
}
public class B extends A {
public int i = 100;
public static String s = "s";
public B(int i, String s) {
super(i);
this.i += 5; //First run: i=105, Second run: i=47
this.s = s; //First run: public static String s="", Second run: public static String a.s="foo"
}
public static void main(String[] argv) {
String s = "";
B b = new B(0, s);
System.out.println(b.i + " " + b.s); //2. 105
s += "foo"; //B.s is now foo
A a = new B(42, s);
System.out.println(a.i + " " + a.s); //3. 0 xx
System.out.println(b.debug().s + " " + b.i + " " + b.s); //1. because of (A)b.s = xxs, 2. b.i = 105, 3. b.s = foo
System.out.println(a.debug().s + " " + a.i + " " + a.s); //(A)a.s = "xxss", (A)a.i = 0, (A)a.s = "xxss"
}
}

Related

Java : Add method Generic Class

I'm new to Java. The Following Code is to create a generic class to generate complex numbers from real and Imaginary Parts. The add() method in the class is throwing the following Error.
Not sure how to proceed further. I have been at this for a day. Error Prompt
import java.util.*;
class ComplexNum<T>{
T i;
T r;
public ComplexNum (T r , T i){
this.r = r;
this.i = i;
}
public ComplexNum add(ComplexNum c2)
{
return new ComplexNum (r + c2.r, i +c2.i);
}
#Override
public String toString() {
return this.r + " + " + this.i + "i";
}
}
class Main{
public static void main(String[] args) {
int n1 = 1;
int n2 = 3;
double d1 =4.4;
double d2 = 5.4;
ComplexNum<Integer> c1 = new ComplexNum<Integer>(n1, n2);
ComplexNum<Double> c2 = new ComplexNum<Double>(d1, d2);
ComplexNum<Double> c3 = c1.add(c2);
System.out.println(c1 + " + " + c2 + " = "+ c3) ;
}
}
static class ComplexNum<T extends Number> {
T i;
T r;
public ComplexNum(T r, T i) {
this.r = r;
this.i = i;
}
public ComplexNum<Double> add(ComplexNum c2) {
Double newr = r.doubleValue() + c2.r.doubleValue();
Double newi = i.doubleValue() + c2.i.doubleValue();
return new ComplexNum<>(newr, newi);
}
#Override
public String toString() {
return this.r + " + " + this.i + "i";
}
}
class Main {
public static void main(String[] args) {
int n1 = 1;
int n2 = 3;
double d1 = 4.4;
double d2 = 5.4;
ComplexNum<Integer> c1 = new ComplexNum<>(n1, n2);
ComplexNum<Double> c2 = new ComplexNum<>(d1, d2);
ComplexNum<Double> c3 = c1.add(c2);
System.out.println(c1 + " + " + c2 + " = " + c3);
}
}

How to use array of objects in this context?

Assuming that the array is populated with 20 shipments, calculate the total cost of local shipments in the array.
I tried to create a for loop and then call out the method calcCost() and += it to the variable local so it would save the values I guess
I'm pretty sure the way I wrote the code is wrong so if someone could help me with it that would be great!
package question;
public class TestShipment {
public static void main(String[] args) {
Shipment r1 = new Shipment(
new Parcel("scientific calculator " , 250),
new Address("Dubai","05512345678"),
new Address("Dubai","0505432123"),
"Salim"
);
System.out.println(r1);
Shipment[] arr = new Shipment[100];
arr[5] = r1;
Shipment[] a = new Shipment[20];
double local = 0;
for (int i = 0; i < a.length; i++) {
if (a[i].isLocalShipment()) {
System.out.println(a[i].calcCost());
}
}
}
}
public class Shipment {
public Parcel item;
private Address fromAddress;
private Address toAddress;
public String senderName;
public Shipment(Parcel i, Address f, Address t, String name) {
item = i;
fromAddress = f;
toAddress = t;
senderName = name;
}
//setter
public void setFromAddress(String c, String p) {
c = fromAddress.getCity();
p = fromAddress.getPhone();
}
public boolean isLocalShipment() {
boolean v = false;
if (fromAddress.getCity() == toAddress.getCity()) {
v = true;
} else {
v = false;
}
return v;
}
public double calcCost() {
double cost = 0;
if (fromAddress.getCity() == toAddress.getCity()) {
cost = 5;
} else {
cost = 15;
}
if(item.weight > 0 && item.weight <= 200) {
cost += 5.5;
}
if(item.weight > 200) {
cost += 10.5;
}
return cost = cost * (1 + 0.5); //fix the tax
}
public String toString() {
return "From: " + senderName + "\nTo: " + toAddress
+ "\nParcel: " + item.desc+item.weight + "\ncost: " + calcCost();
}
}

Launch various method with an other method

I want launch various method(exercise) with an other method with Scanner.
When the machine asks which exercises, I want to answer with a tapping answer and when I say the exercise(method), the machine launch this method with my tapping answer.
Exemple:
Which exercises?
me - "W34"
(The machine launches the method W34)
You have to use reflection.
Note: For more please write your code in question I will change it accordingly
obj.getClass().getMethod(methodName).invoke.invoke(obj);
Sorry i m not a professional, and sorry for the code it was my first question on this site, i only put in some exercises because there are so many.
Code :
public class Main {
public static String CapitalizeEachWord(String st) {
String result = "";
st = st.replaceAll("() ([A-Z])", "$1 $2");
String[] words = st.split(" ");
for (String word : words)
if (word.length() > 0)
result += Character.toUpperCase(word.charAt(0)) + word.substring(1) + " ";
return result;
}
public static String Scann() {
Scanner in = new Scanner(System.in);
System.out.println("Wich exercises? (W + exNumb)");
int x = in.nextInt();
return null;
}
public static String W1() {
System.out.println("Hello");
System.out.println("Antoine Sidot!");
System.out.println();
return null;
}
public static String W2() {
int result = 74 + 36;
System.out.println(result);
return null;
}
public static String W3() {
System.out.println(50/3);
return null;
}
public static String W4() {
System.out.println(-5 + 8 * 6);
System.out.println((55 + 9) % 9);
System.out.println(20 + -3*5 / 8);
System.out.println(5 + 15 / 3 * 2 -8 % 3);
return null;
}
public static String W5() {
int nb1 = 25;
int nb2 = 5;
System.out.println(nb1 + " x " + nb2 + " = " + nb1*nb2);
return null;
}
}

toString an arraylist containing object

I have an array list of type car.
I have an overriding toString method which prints my car in the desired format.
I'm using the arraylist.get(index) method to print the cars.
I only have one for now it works, but I want it do print for all of the cars in the array list.
This is my code:
public class Garage {
private static int carsCapacity = 30;
ArrayList<Cars> myGarage;
public Garage() {
Scanner scanAmountOfCars = new Scanner(System.in);
System.out.println("Please limit the number of car the garage can contain.");
System.out.println("If greater than 50, limit will be 30.");
int validAmount = scanAmountOfCars.nextInt();
if (validAmount <= 50) {
carsCapacity = validAmount;
myGarage = new ArrayList<Cars>();
}
System.out.println(carsCapacity);
}
public void addCar() {
Cars car = new Cars(Cars.getID(), Cars.askCarID(), Cars.getPosition(), Attendant.askForAtt(), System.currentTimeMillis());
myGarage.add(car);
//System.out.println(car);
}
public static int getCarsCapacity() {
return carsCapacity;
}
#Override
public String toString() {
return "Garage [Car:" + myGarage.get(0).getPlateNum() + " ID:" + myGarage.get(0).getCarID() + " Position:" + Cars.getPosition() +
" Assigned to:" + Cars.getAssignedTo().getId() + "(" + Cars.getAssignedTo().getName()
+ ")" + " Parked at:" + Cars.convert(myGarage.get(0).getCurrTime()) + "]";
}
}
I also put the Cars class in case you need it:
public class Cars {
private String carID;
private String plateNum;
private static String position;
private static Attendant assignedTo;
private long currTime;
static String[] tempArray2 = new String[Garage.getCarsCapacity()];
public Cars(String carID, String plateNum, String position, Attendant assignedTo, long currTime) {
this.carID = carID;
this.plateNum = plateNum;
Cars.position = position;
Cars.assignedTo = assignedTo;
this.currTime = currTime;
}
private static void createCarsID() {
for (int x = 0; x < Garage.getCarsCapacity(); x++) {
tempArray2[x] = ("CR" + (x + 1));
}
}
public static String getID() {
createCarsID();
String tempID = null;
String tempPos = null;
for (int x = 0; x < tempArray2.length; x++) {
if (tempArray2[x] != null) {
tempID = tempArray2[x];
tempPos = tempArray2[x];
getPos(tempPos);
tempArray2[x] = null;
break;
}
}
return tempID;
}
public static void getPos(String IdToPos) {
String strPos = IdToPos.substring(2);
int pos = Integer.parseInt(strPos);
position = "GR" + pos;
}
public String getPlateNum() {
return plateNum;
}
public String getCarID() {
return carID;
}
public static String getPosition() {
return position;
}
public long getCurrTime() {
return currTime;
}
public static Attendant getAssignedTo() {
return assignedTo;
}
public static String askCarID() {
boolean valid = false;
System.out.println("Please enter your car's plate number.");
Scanner scanCarID = new Scanner(System.in);
String scannedCarID = scanCarID.nextLine();
while (!valid) {
if (scannedCarID.matches("^[A-Za-z][A-Za-z] [0-9][0-9][0-9]$")) {
valid = true;
System.out.println(scannedCarID);
} else {
System.out.println("Please enter a valid plate number. Ex: AF 378");
askCarID();
}
}
return scannedCarID.toUpperCase();
}
public static String convert(long miliSeconds) {
int hrs = (int) TimeUnit.MILLISECONDS.toHours(miliSeconds) % 24;
int min = (int) TimeUnit.MILLISECONDS.toMinutes(miliSeconds) % 60;
int sec = (int) TimeUnit.MILLISECONDS.toSeconds(miliSeconds) % 60;
return String.format("%02d:%02d:%02d", hrs, min, sec);
}
}
Your Garage should have the implementation of toString() which uses ArrayList#toString() implementation:
public String toString() {
return "Garage: " + myGarage.toString();
}
Also remember to implement toString() in Cars.java.
public String toString() {
return "[" + this.carID + " " +
this.plateNum + " " +
Cars.position + " " +
Cars.assignedTo.toString + " " +
String.valueOf(this.currTime) + "]"
}

java how to execute method

I have created a class Hotel defined as follows:
import java.util.Random;
public class Hotel {
private Osoba[] tab = new Osoba[100];
public void zamelduj(Osoba os, int num) {
if (tab[num - 1] == null) {
System.out.println("Pokoj o numerze " + num + "jest zajety");
return;
}
tab[num - 1] = os;
}
public void wymelduj(int num) {
tab[num - 1] = null;
}
public void zamienOsoby(int num1, int num2) {
Osoba o = tab[num1 - 1];
tab[num1 - 1] = tab[num2 - 1];
tab[num2 - 1] = o;
}
public void znajdzWolnePokoje() {
for (int i = 0; i < 100; i++) {
if (tab[i] == null) System.out.println(i + 1);
}
}
public void przydzielPokoje50() {
for (int i = 0; i < 50; i++) {
Random r = new Random();
Osoba o = new Osoba();
int num = r.nextInt(100);
tab[num] = o;
}
}
public void wypisz() {
for (int i = 0; i < 100; i++) {
if (tab[i] == null) System.out.println("Pokoj nr. " + (i + 1) + " jest wolny");
else System.out.println("Pokoj nr. " + i + " jest zajety przez " + tab[i].imie + " " + tab[i].nazwisko);
}
}
public static void main(String[] args) {
Hotel h = new Hotel();
//h.przydzielPokoje50();
//h.wypisz();
h.zamelduj(null, 30);
}
}
I also have a class Osoba:
public class Osoba {
public String imie;
public String nazwisko;
Osoba() {
imie = null;
nazwisko = null;
}
Osoba(String imie, String nazwisko) {
this.imie = imie;
this.nazwisko = nazwisko;
}
}
I want to execute the method Zamelduj, which will assign a person (Osoba) to a cell in a table. However, every time I insert something other than null in the following it says that the first argument is not a capable parameter of the method.
h.zamelduj(null, 30);
What am I doing wrong?
I think your problem is that on the line " h.zamelduj(null, 30);" you need to create a new Osoba:
h.zamelduj(new Osoba("o.o", "._.!"), 30);
what happens is that the function is expecting a Osoba, if you give it another thing, it refuses. i hope it helps
You need to create an object of the class hotel (in your class from where you want to call the method type):
Hotel myObjectHotel = new Hotel();
And then you can call the method trough:
myHotelObject. zamelduj(give parameters here);
:)
Update:
Missed the real question. Just focused on the topic. I'm sorry. ;)

Categories