Java 字符串到整数的转换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14657657/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 16:59:56  来源:igfitidea点击:

Java String to Integer Conversion

javastring

提问by zwork

Possible Duplicate:
How to convert string to int in Java?

可能的重复:
如何在 Java 中将字符串转换为 int?

I am trying to figure out how to convert a string that has integers in it to an integer variable.

我想弄清楚如何将包含整数的字符串转换为整数变量。

Code:

代码:

import java.util.Scanner;

public class main {
    public static void main(String args[]) {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter date of birth (MM/DD/YYYY):");
        String DOB = input.next();
        String month = DOB.substring(0, 1);
        String day = DOB.substring(3, 4);
        String year = DOB.substring(6, 9);
        int month1 = month;
        int age = 0;
        //age = 2013 - DOB - 1;
        int age2 = 0;
        age2  = age + 1;
        System.out.println("You are " + age + " or " + age2 + " years old");
    }
}

I want to turn String month, String day, and Sting yearinto integers.

我想把String month, String day, 和Sting year变成整数。

回答by Neil Locketz

use int month = Integer.parseInt(stringMonth);

利用 int month = Integer.parseInt(stringMonth);