简体   繁体   English

Integer.parseInt()错误

[英]Integer.parseInt() Error

i'm getting an errors while trying to use Integer.parseInt() . 尝试使用Integer.parseInt()出现错误。 They are, no suitable method found for parseInt(int) and method Integer.pasreInt(String) in not applicable. 它们是不适用于parseInt(int)的合适方法,而Integer.pasreInt(String)方法不适用。

import java.io.InputStream; 
import java.util.Scanner; 
import java.util.regex.Pattern; 

class bday1
{ 
public static void main(String[] args) 
{ 
    Scanner sc = new Scanner(System.in);
    int day;
    int month=0;
    int year;
    int whatDay;
    int howManyDays=0;
    int leapYear;
    final int JANYEAR = 1901;
    int[] dayMonth = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    boolean numberEntered=true;
    String strMonth;
    String[] days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};

    System.out.print("What is your birthdate? "); 
    sc.useDelimiter(Pattern.compile("[-/.\\s]")); 
    day = sc.nextInt();
    strMonth = sc.next();
    year = sc.nextInt();

    if((strMonth.charAt(0) >='0') && (strMonth.charAt(0) <='9'))
    {
        numberEntered=true;
        System.out.println ("number entered");
    }

    if(numberEntered)
    {
        strMonth=Integer.parseInt(month);
    }

    else
    {
        System.out.println ("string entered");
    }

Thats my snippet of code i believe i having trouble with. 多数民众赞成在我的代码片段,我相信我有麻烦。 Any help would be great. 任何帮助都会很棒。

Since month is initialized to zero and isn't changed afterwards, setting strMonth to month would only succeed in setting it to 0. By the looks of your code, it appears that you are trying to set the value of month to strMonth . 由于month初始化为零,并且此后不会更改,因此将strMonth设置为month只会成功将其设置为0。从代码的外观来看,您似乎试图将month的值设置为strMonth To do this, replace: 为此,请替换:

strMonth = Integer.parseInt(month);

With the following: 具有以下内容:

month = Integer.parseInt(strMonth);

You are trying to assign the String value into the int dataType. 您正在尝试将String值分配给int数据类型。 so only it wont allow you. 所以只有它不会允许你。

strMonth= Integer.parseInt(month); // variable month and strMonth is int dataType

And then the Integer.parseInt() will return the String value. 然后Integer.parseInt()将返回String值。 Change the type to String or convert the String to int 将类型更改为String或将String转换为int

try 尝试

strMonth = String.valueOf(month);

In you code you are use parseInt which expects a String. 在代码中,您使用parseInt,它需要一个字符串。 The month that you are using is already an int. 您使用的月份已经是一个整数。

What you are trying to do is convert an int to a String. 您尝试做的是将int转换为String。 Normal ways would be Integer.toString(i) or String.valueOf(i) . 正常的方式是Integer.toString(i)String.valueOf(i)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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