在Java中从字符串中获取int

时间:2016-10-13 23:46:33

标签: java java.util.scanner

我想做什么:

当用户键入3位int时,它将列出整数然后添加它们。所以输出应该是这样的

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

这是我的代码

//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

    }
}

1 个答案:

答案 0 :(得分:1)

使用Integer.parseInt():

int firstInt = Integer.parseInt(firstNum);

等,然后添加它们。

为了增加收益,请在用户输入的内容不是全数字时正确处理NumberFormatException。