添加用户输入的两个值
问题描述:
我应该如何使用户输入的两个值被添加?添加用户输入的两个值
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.print("Input height value = ");
height = input.readLine();
} catch(IOException e) {
System.out.print("Error");
}
System.out.println("The base is "+base+height);
}
}
答
首先,将两个输入字符串转换为数字,例如使用Integer.parseInt
。
当您“添加”两个字符串(或一个字符串和一个数字)时,结果是这些字符串的串联。将这些数字的结果是它们的总和,你所期望的,所以你的最后一行应该是这样的:
System.out.println("The base is " + (baseNumber+heightNumber));
答
此刻你是治疗base
和height
为字符串。
所以,你必须:
base + height = "2" + "3" = "23"
也就是说+
是字符串连接。
您需要使用Integer.parseInt
将它们转换为int
秒,然后将它们添加:
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);
答
为什么大家要分析它?只要改变的base
和height
类型int
及用途:
input.nextInt()
出了什么问题'的System.out.println(“该基地是” +基地+高); '? – Oswald
@Oswald OP希望'“基数是”+ base + height“(当'base = 2'和'height = 3'时)为'基数为5'。在这里它变成了'基地是23' – Nivas
下面的答案之一是可以接受的吗? – MGwynne