Why in the second example (unlike the first) does the result come out concatenated and not added?

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.");
    
asked by anonymous 06.11.2017 / 11:52

3 answers

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.");
    
06.11.2017 / 12:05
6

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

In the first case, the concatenation is only made after the summation because the existence of the parentheses causes the first one to be computed, and then the concatenation is performed.

    
06.11.2017 / 11:59
1

I think it was an inattentiveness of yours, because in the first example you are concatenating the sentence with the variables correctly using the parentheses and causing the program to do the calculation correctly, and in the second example you stopped putting a parenthesis to separate the mathematical expression of the phrase, making the variables possibly concatenate instead of the solution of the 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 change the second line above by this line below, and I noticed that ln was missing on your Sytem.out.print

System.out.println("Will take " + (STOPTIME + FLOORTIME * (floorCome - floorCall) + FLOORTIME * (floorCall - floorGo)) + " seconds.");  
    
06.11.2017 / 12:17