How to record the numbers from the line to the variable



  • There's 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 the date of birth, for example, 18 декабря, but I need to record the number to the variable. intAnd the name of the month is in line to compare. How to break the line by number and line, as it is now in the variable. n A line? It's a simple question, but I can't figure out what to use for it, because I'm just learning. Thank you.



  • Partial entry:

    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 you're going to take it all and cut it out.

    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 + "'");
    }
    

    }

    And 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("Неправильный ввод.");
        }
    }
    

    }


    P. S. It's a good one, and the exceptions would be a good one.




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2