简体   繁体   中英

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.print("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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM