Why in the second example (unlike the first) the result is concatenated and not summed?

Asked

Viewed 75 times

0

example 1

final double BEGIN = 10.20, KM = 1.30, BAG = 2;
Scanner s = new Scanner (System.in);
double clientKm, clientBags;

System.out.println("How many km?:");
clientKm = s.nextDouble();

System.out.println("How many bags?:");
clientBags = s.nextDouble();

System.out.println("Your bill is: " + (BEGIN + (clientKm * KM) + (clientBags * BAG)) + " shekels.");

example 2:

int floorCome, floorCall, floorGo;
final int FLOORTIME = 3, STOPTIME = 5;
Scanner s = new Scanner(System.in);

System.out.println("Which floor is the elevator now? ");
floorCome = s.nextInt();

System.out.println("From which floor is the person calling? ");
floorCall = s.nextInt();

System.out.println("To which floor you like to go? ");
floorGo = s.nextInt();

System.out.print("Will take " + STOPTIME + FLOORTIME * (floorCome - floorCall) + FLOORTIME * (floorCall - floorGo) + " seconds.");

3 answers

6

Java, when it finds an expression like "String" + tipo primitivo, uses the method toString() of the primitive type to obtain the string which represents it and then concatenate it with the previous string, resulting in a new string.

In the first case the concatenation is only done after the sum because the existence of the parentheses causes the first calculation of what is inside them and only after the concatenation.

1

I think it was an inattention of yours, because in the first example you are concatenating the sentence with the variables correctly using the parentheses and making the program do the calculation correctly, In the second example you stopped putting a parenthesis to separate mathematical expression from the sentence, causing the variables to possibly concatenate instead of occurring the solution of mathematical expression. Notice the difference

System.out.println("Your bill is: " + (BEGIN + (clientKm * KM) + (clientBags * BAG)) + " shekels.");

System.out.print("Will take " + STOPTIME + FLOORTIME * (floorCome - floorCall) + FLOORTIME * (floorCall - floorGo) + " seconds.");  

So replace the second line above with this line below, and I noticed that the ln in his Sytem.out.print

System.out.println("Will take " + (STOPTIME + FLOORTIME * (floorCome - floorCall) + FLOORTIME * (floorCall - floorGo)) + " seconds.");  

0


In the first example you use the "(" and ")" to separate the types, if you do so in the second example, it will work.

System.out.print("Will take " + (STOPTIME + FLOORTIME * (floorCome - floorCall) + FLOORTIME * (floorCall - floorGo)) + " seconds.");

Browser other questions tagged

You are not signed in. Login or sign up in order to post.