添加用户输入的两个值

问题描述:

我应该如何使用户输入的两个值被添加?添加用户输入的两个值

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); 
    } 
} 
+0

出了什么问题'的System.out.println(“该基地是” +基地+高); '? – Oswald

+1

@Oswald OP希望'“基数是”+ base + height“(当'base = 2'和'height = 3'时)为'基数为5'。在这里它变成了'基地是23' – Nivas

+0

下面的答案之一是可以接受的吗? – MGwynne

首先,将两个输入字符串转换为数字,例如使用Integer.parseInt

当您“添加”两个字符串(或一个字符串和一个数字)时,结果是这些字符串的串联。将这些数字的结果是它们的总和,你所期望的,所以你的最后一行应该是这样的:

System.out.println("The base is " + (baseNumber+heightNumber)); 
+0

不应该将字符串转换为int更好? – Zhianc

+0

@js david是的,'parseInt'(它返回一个'int',与'valueOf'相比,它返回​​一个'Integer')确实是更好的选择,尽管由于自动拆箱,两者都有效。我想要强调的是,'int'(或者'Integer')并不总是最好的选择,特别是如果你期望大输入或者小数输入。 – phihag

此刻你是治疗baseheight为字符串。

所以,你必须:

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); 

为什么大家要分析它?只要改变的baseheight类型int及用途:

input.nextInt()