Extract characters with substring method in java

0

I ask for help please; I need to extract two different positions of the same string with the substring () method of java, but it generates an error.

package Entradas;

import java.util.Scanner;

public class Ejer20_parqueadero 
{
    public static void main(String[] args) 
  {
        double horaEntrada, horaSalida;
        String entrada="",salida="";
        
        System.out.println("Ingrese hora militar: ");
        Scanner hora=new Scanner(System.in);
               
        entrada=hora.nextLine().substring(0,2);
        salida=hora.nextLine().substring(3,5);
        
        
        System.out.println("entrada: "+entrada+" salida: "+salida);  
    }    
}

This error generates, when I compile

    
asked by roca33scorpio 14.09.2018 в 04:54
source

3 answers

0

in the image that shows that you have not entered the value for your output variable, that's why you get the error. Now, I do not understand very well what you are trying to achieve, but your program does run. You have to take into account that when you enter 22:12 when giving enter you have to enter another value for example 23:11

The output I would throw would be:

entrada: 22
salida: 11
    
answered by 14.09.2018 в 06:11
0

Hello the problem is here:

entrada=hora.nextLine().substring(0,2);
salida=hora.nextLine().substring(3,5);

When you run hora.nextLine() for the first time, you get "22:11", but when you run it again, you will not get any String because there is nothing in the next line. To solve the problem you should save the value in a variable String and then apply the substring to this variable.

String input = hora.nextLine();
entrada = input.substring(0,2);
salida = input.substring(3,5);
    
answered by 14.09.2018 в 06:33
0

Your program compiles correctly but the code is incorrect since you perform the line reading twice (nextline), for this you must save the time entered in a variable and then use the substring 2 times to obtain the values you want.

So that everything goes well you have to make the following modifications:

    public static void main(String[] args)
    {
        double horaEntrada, horaSalida;
        String entrada="",salida="";

        System.out.println("Ingrese hora militar: ");
        Scanner hora=new Scanner(System.in);

        String horaMilitar=hora.nextLine();
        entrada=horaMilitar.substring(0,2);
        salida=horaMilitar.substring(3,5);


        System.out.println("entrada: "+entrada+" salida: "+salida);
    }
    
answered by 14.09.2018 в 14:19