Adding two values inputted by a user
What should i do to make the two values which were inputted by the user to be added?
import java.io.*;
public class InputOutput {
public static void main(String[] args) {
String base="";
String height="";
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
try {
System.out.print("Input base value = ");
base = input.readLine();
System.out.pri开发者_如何学JAVAnt("Input height value = ");
height = input.readLine();
} catch(IOException e) {
System.out.print("Error");
}
System.out.println("The base is "+base+height);
}
}
First, convert both input strings into numbers, for example with Integer.parseInt
.
When you "add" two strings (or a string and a number), the result is the concatenation of these strings. The result of adding numbers is their sum, as you would expect, so your final line should look like:
System.out.println("The base is " + (baseNumber+heightNumber));
At the moment you are treating base
and height
as strings.
So you have:
base + height = "2" + "3" = "23"
That is +
is string concatenation.
You need to use Integer.parseInt
to convert them to int
s and then add them:
int ibase = Integer.parseInt(base);
int iheight = Integer.parseInt(height);
int sum = ibase + iheight;
System.out.println("The base is " + sum);
int sum = Integer.parseInt(base)+ Integer.parseInt(height);
System.out.println("The base is "+ sum);
Why does everyone want to parse it? Just change the type of base
and height
to int
and use:
input.nextInt()
精彩评论