Print a server's hostname and IP from variables
Problem statement
Last problem, the text you printed was fixed, typed straight into the print line. Most of the time you want to print something that can change, like a server's hostname or IP address you looked up moments ago. For that, you store the value in a variable first, then print the variable.
- Python:
hostname = "web-01" - Java:
String hostname = "web-01"; - C++:
std::string hostname = "web-01";
A variable is just a name pointing at a value. Once it's set, you can use that name anywhere instead of retyping the value.
Common mistake: in Java and C++, forgetting the type keyword before the variable name.
- Wrong (Java):
hostname = "web-01"; - Right (Java):
String hostname = "web-01";
Python doesn't need a type keyword at all, which is why this mistake only bites you in Java and C++ - the compiler won't know what kind of value hostname is supposed to hold, and refuses to build.
Your task: create two variables, hostname = "web-01" and ip = "10.0.0.5", then print them on one line with - between them.
Expected output:
web-01 - 10.0.0.5Approach
Each language needs the value's type stated differently:
- Python doesn't ask for a type at all.
hostname = "web-01"just works. - Java and C++ need the type written before the name:
String hostname = ...in Java,std::string hostname = ...in C++ (this needs#include <string>at the top).
To combine two variables into one line of text, each language has its own way to join, or concatenate, strings:
- Python: an f-string,
print(f"{hostname} - {ip}")- see the f-string docs. - Java: the
+operator,System.out.println(hostname + " - " + ip); - C++: the
<<operator again, chained:std::cout << hostname << " - " << ip << std::endl;
hostname = "web-01"
ip = "10.0.0.5"
print(f"{hostname} - {ip}")