简体   繁体   中英

Grabbing int from string in Java

What I want to do:

When the user types in a 3 digit int, it will list the integers and then add them. So the output should look like this

Please enter 3 digit number: 123
The first digit is: 1
The second digit is: 2
The third digit is: 3
The sum is: 6

Here is my code

//Author: Sean Cantwell
//Date: October 13, 2016
//Purpose: Grab ints and add them

import java.util.*;
import java.io.*;
public class MathChallenge
{
    public static void main(String args[])
    {
        Scanner kbReader1 = new Scanner(System.in);
        System.out.print("Enter a three digit number: ");
        number = kbReader1.next();
        String firstNum = number.substring(0,1);
        String secondNum = number.substring(1,2);
        String thirdNum = number.substring(2,3);
        System.out.println("The first digit is " + firstNum);
        System.out.println("The second digit is " + secondNum);
        System.out.println("The third digit is " + thirdNum);
        //ADD DIGITS TOGETHER HERE

    }
}

Use Integer.parseInt():

int firstInt = Integer.parseInt(firstNum);

etc, and then add them.

For added benefit, handle the NumberFormatException properly in case the user enters something that is not all digits.

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