There is the following code:

public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Π£ΠΊΠ°ΠΆΠΈΡ‚Π΅ Π΄Π°Ρ‚Ρƒ роТдСния: "); String n = scanner.nextLine(); System.out.println(n); } 

In the console, I indicate the date of birth, for example, 18 дСкабря , but I need to write the number in the variable int , and the name of the month - in the string, then to compare. How to break a string into a number and string, because Now in the variable n string? The question is simple but I can not understand what to use for this, because I am just learning. Thank.

    1 answer 1

    You can read the input in parts:

     import java.util.Scanner; public class Main { public static void main(final String[] args) { System.out.println("Π£ΠΊΠ°ΠΆΠΈΡ‚Π΅ Π΄Π°Ρ‚Ρƒ роТдСния: "); final Scanner scanner = new Scanner(System.in); final int date = scanner.nextInt(); final String month = scanner.next(); System.out.println("Π’Ρ‹ ΡƒΠΊΠ°Π·Π°Π»ΠΈ '" + date + "' '" + month + "'"); } } 

    Or take it entirely and cut it:

     import java.util.Scanner; public class Main { public static void main(final String[] args) { System.out.println("Π£ΠΊΠ°ΠΆΠΈΡ‚Π΅ Π΄Π°Ρ‚Ρƒ роТдСния: "); final Scanner scanner = new Scanner(System.in); final String[] tokens = scanner.nextLine().split(" "); final int date = Integer.decode(tokens[0]); final String month = tokens[1]; System.out.println("Π’Ρ‹ ΡƒΠΊΠ°Π·Π°Π»ΠΈ '" + date + "' '" + month + "'"); } } 

    Or you can play with regular expressions:

     import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { public static void main(final String[] args) { System.out.println("Π£ΠΊΠ°ΠΆΠΈΡ‚Π΅ Π΄Π°Ρ‚Ρƒ роТдСния: "); final Scanner scanner = new Scanner(System.in); final String line = scanner.nextLine(); final Matcher matcher = Pattern.compile("(\\d+)\\s(.+)").matcher(line); if (matcher.find()) { final int date = Integer.decode(matcher.group(1)); final String month = matcher.group(2); System.out.println("Π’Ρ‹ ΡƒΠΊΠ°Π·Π°Π»ΠΈ '" + date + "' '" + month + "'"); } else { System.out.println("ΠΠ΅ΠΏΡ€Π°Π²ΠΈΠ»ΡŒΠ½Ρ‹ΠΉ Π²Π²ΠΎΠ΄."); } } } 

    PS For good, also exceptions would be nice to catch.

    • Thank! Does the next () method return the next character? - Nevada
    • @Nevada No. A piece of the entered string before the delimiter. The separator can be recognized using the Scanner.delimiter method and installed using the Scanner.useDelimiter method. - user194374