How to enter data in the same line

2

How can I enter data on the same line?

public static void main(String[] args)
{
    Scanner sc = new Scanner(System.in);

    System.out.println("Introduce la hora");

    int hora = sc.nextInt();
    System.out.print(":");
    int minutos = sc.nextInt();

    sc.close();
}

Exit example

Introduce la hora
22
:50

I would like that when I entered the data I would come out on the same line, 22:50

I've tried with string and nextLine () but neither.

    
asked by AlejandroB 20.09.2018 в 13:41
source

3 answers

4

If what you want is to enter data in the same line what you have to do is use print no println that will give a jump line when you present the message would be your code so,

public static void main(String[] args)
{
    Scanner sc = new Scanner(System.in);

    System.out.print("Introduce la hora");

    int hora = sc.nextInt();
    System.out.print(":");
    int minutos = sc.nextInt();

    sc.close();
}
    
answered by 20.09.2018 в 13:55
2

If you do not need to handle them later, just go on the screen and try Strings in this way.

public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);

        System.out.println("Introduce la hora (HH:MM)");

        String horacompleta=sc.nextLine();
        String minutos=horacompleta.substring(3);
        String hora=horacompleta.substring(0, 2);
        System.out.print(hora+":"+minutos);

        sc.close();
    }

Result:

Introduce la hora (HH:MM)
12:40
12:40
    
answered by 20.09.2018 в 14:01
0

In my opinion, the easiest thing is to indicate to the user the format with which you should enter the time

public static void main(String[] args)
{
    Scanner sc = new Scanner(System.in);

    System.out.println("Introduce la hora (HH:MM) ");

    string horaCompleta = sc.nextLine();
    System.out.println(horaCompleta);

    sc.close();
}

If you then need to have the hour and minute data you have 2 options:

1- As you told the user to enter the time in HH: MM format and save it in a string, you can obtain the data as follows:

int hora = Integer.parseInt(horaCompleta.substring(0, 2));
int minutos = Integer.parseInt(horaCompleta.substring(3));

With that you would already have both data in int format and you can use it in the way you need.

2- The other option is to ask you to enter 2 data instead of one:

public static void main(String[] args)
{
    Scanner sc = new Scanner(System.in);

    System.out.println("Introduce la hora ");
    int hora = sc.nextInt();

    System.out.println("Introduce los minutos ");
    int minutos = sc.nextInt();

    System.out.println(hora + ":" + minutos);

    sc.close();
}

In this way you have the 2 data separately and shows them in the conventional 22:50 format.

I hope it helps you!

    
answered by 20.09.2018 в 16:10