How to crop a String and convert to int in Java?

Asked

Viewed 231 times

2

How can I cut out the String monthAndYear, convert and assign variables respective? At the time of conversion shows an error.

System.out.print("Enter month and year to calculate income (MM/YYYY): ");
String monthAndYear = sc.nextLine();

int month = Integer.parseInt(monthAndYear.substring(0, 1));
int year = Integer.parseInt(monthAndYear.substring(3));
  • what error? show the value of the monthAndYear variable

  • To get the month you have to use monthAndYear.substring(0, 2), are two digits required by the mask that presents.

  • Before performing parseint you should also check whether the monthAndYear variable has the format you wanted it to be inserted and otherwise indicate to the user that you have made a mistake and ask again.

3 answers

3

An alternative (in addition to substring already suggested in the other answer) would use split:

String monthAndYear = ...
String[] partes = monthAndYear.split("/"); // separar pela barra
if (partes.length == 2) {
    int month = Integer.parseInt(partes[0]);
    int year = Integer.parseInt(partes[1]);
}

Remembering that the method parseInt can launch a NumberFormatException if one of the parties is not a number (and you can place a try/catch to check this if you want).
And you still need to validate the values (if the month is between 1 and 12, for example), which can be done before with regex (as suggested the other answer), or after the Parsing.


If you’re dealing with dates, use a date API

If his String should have a date (though incomplete as it only has month and year), so why not use a date API?

If using Java >= 8, use the package classes java.time:

String monthAndYear = ...
DateTimeFormatter parser = DateTimeFormatter.ofPattern("MM/uuuu");
YearMonth ym = YearMonth.parse(monthAndYear, parser);
int month = ym.getMonthValue();
int year = ym.getYear();

The class java.time.format.DateTimeFormatter takes as a parameter the format in which the String is (in this case, "month/year"). Next we use a java.time.YearMonth, which is a class that represents a year and a month (just what we need).

The method parse returns an instance containing the numerical values of the month and year that were in the String. It is then possible to recover these numerical values using the respective getters. The Parsing also already validates if the values are valid (if the month is between 1 and 12), so you already guarantee that it is a valid date. Case to String is not in the specified format, or some of its values are invalid, a DateTimeParseException.


For Java <= 7, you can use the class java.text.SimpleDateFormat, which works in a similar way to java.time:

String monthAndYear = ...
SimpleDateFormat sdf = new SimpleDateFormat("MM/yyyy");
sdf.setLenient(false);
Calendar c = Calendar.getInstance();
c.setTime(sdf.parse(monthAndYear));
int month = c.get(Calendar.MONTH) + 1;
int year = c.get(Calendar.YEAR);

An important difference is the use of setLenient(false), otherwise months with values such as "00" and "13".

Case to String is invalid, a ParseException.

Another detail is that to get the numeric value of the month you must add up to 1, because in this API the months are indexed to zero (January is zero, February is 1, etc).


If you want, for Java 6 and 7 you can also use Threeten Backport, one backport of java.time. Basically, it has classes and methods with the same names and functionalities, the difference is that instead of using the package java.time, you use the org.threeten.bp. Apart from this detail, the code would look just like the Java 8 example above.

3


Here is an example of what the user places.

In this example the field year allows to put years since the year 0.

import java.util.Scanner;

class Main {
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);  
    String monthAndYear = "";
    do{
      System.out.print("Enter month and year to calculate income (MM/YYYY): ");
      monthAndYear = in.nextLine();
    }while(!monthAndYear.matches("^(1[0-2]|0[1-9])/[0-9]{4}$"));


    int month = Integer.parseInt(monthAndYear.substring(0, 2));
    int year = Integer.parseInt(monthAndYear.substring(3)); 

    System.out.println(month);
    System.out.println(year);
    in.close();
  }
}
  • If you want to restrict the year put in comment for me to update the answer.

  • The error happens at the time of conversion, the monthAndYear variable receives a String with the date. This is the error - Enter Month and year to calculate income (MM/YYYY): Exception in thread "main" java.lang.Stringindexoutofboundsexception: Begin 0, end 1, length 0 at java.base/java.lang.String.checkBoundsBeginEnd(String.java:3319) at java.base/java.lang.String.substring(String.java:1874) at application.ProgramWorker.main(Programworker.java:59)

  • I cannot reproduce your mistake using this solution. By error you are still using your version and are trying to get the substring of a string smaller than your Begin and end arguments.

2

In your case, in addition to the strategies already discussed, can also be used regular expressions:

    String monthYear = "07/2019";
    Pattern pattern = Pattern.compile("([\\d]{2})\\/([\\d]{4})");
    Matcher matcher = pattern.matcher(monthYear);

    if (matcher.matches()) {
      int month = Integer.parseInt(matcher.group(1));
      int year = Integer.parseInt(matcher.group(2));
    }
  • thanks for the help

Browser other questions tagged

You are not signed in. Login or sign up in order to post.