'Adding a space in concatenation in Java
So im working on this assignment that asks me to calculate the BMI using weight, height. im done the entire code, however, I have tried everything to add a space in the print statements, however, I'm not sure why adding the + is not working in between the variable and the string. I havent added the variable in the first two print statements, because I just want to see what the issue is first.
I have attached the output, and what i've worked on so far, I am still a beginner, so any detailed feedback would be appreciated.
enter code hereimport java.util.Scanner;
[import java.lang.Math;
import java.lang.System;
class Main {
public static void main(String\[\]args){
//make a scanner object
Scanner scan = new Scanner(System.in);
//prompt the user to enter name
System.out.println("Enter patients name: ");
//store user's input into string called name
String name = scan.nextLine();
//prompt user to enter height
System.out.print("Enter height in meters: ");
//store user's height into string
String height = scan.nextLine();
//prompt the user to enter weight
System.out.print("Enter weight: ");
//store user's weight into string
String weight = scan.nextLine();
//calculate the BMI using height and weight of the user
Double x = Double.parseDouble(weight)/Math.pow(Double.parseDouble(height),2);
System.out.println(x);
//if the BMI is less than 20, print that the patient is underweight
if(x < 20){
System.out.println("The patient is underweight");
}
//if the BMI is between 20 and 25, then print that the user is average
else if(x > 20 && x < 25){
System.out.println("The patient is average");
}
//if the BMI is greater than 25, print that the patient is overweight
else if(x > 25){
System.out.println (name + "is overweight");
}
}
}
`enter code here`'*.java')
java -classpath .:target/dependency/* Main
Enter patients name:
Liam
Enter height in meters: 2
Enter weight: 200
50.0
Liamis overweight
\[enter image description here\]\[1\]
\[1\]: https://i.stack.imgur.com/HEm6Y.png][1]
Solution 1:[1]
Inputs lack a SPACE, so output lacks a SPACE
If the value stored in variable named name does not contain a SPACE, and if the string literal "is overweight" does not contain a SPACE, then why would you expect the concatenated result to contain a SPACE?
You could redefine either part to contain a SPACE.
name + " is overweight" // SPACE added to front of string literal.
Or you could concatenate three parts, using a SPACE as the middle part.
name + " " + "is overweight". // Middle part is a string literal containing a single character, a SPACE.
Or you could join the parts while specifying a SPACE in between. Use the String.join static method.
String.join( " " , name , "is overweight" )
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Basil Bourque |
