JAVA: Program that reads an integer and a position

3

I was given an exercise so that in Java I could do a program that read a multi-digit integer and a position; and then show on the screen the number of the number that is in the indicated position. For example, for number 1234 position 1 should return the value 4, 2: 3, 3: 2, 4: 1.  I can do it for a certain amount of numbers without problem, but I need the program to take any integer of any number of digits and show what is requested. It only occurred to me to divide the number by 10 ^ given position and then discard the rest, the problem with this is that I do not know how to make powers in java and I have only seen alternative structures until now.  This is the code I use for 3 figures, I do not see how to do it for more figures without using powers.

 public static int cifraInt(int numero,int posicion){
  //Modulo que lee un entero y su posicion y retorna el digito que se encuentra
  //en la posicion elegida
  int cent, dec, uni, digito;
  cent= numero/100;
  dec=numero/10-cent*10;
  uni=numero-cent*100-dec*10;
  switch (posicion){
      case 1: digito=cent;
      break;
      case 2: digito=dec;
      break;
      case 3: digito= uni;
      break;
      default: digito=-1;
  }
  return digito;
    
asked by TIKINNI 08.05.2018 в 18:56
source

2 answers

1

Hello nose if you help this data:

1.-There is something called a module that gives you the rest of a division and you work like this:

int resto = 634 % 10;
System.out.println("resto :"+resto);

the result is 4.

2.-to make the power of a number maybe you could do it like this:

int base=10;
int exponente=3;
for(int j=1;j<exponente;j++){
    base=base*10;//potencia de base 10
}
System.out.println("10 elevado a "+exponente+" es "+base);

3.- to know how many digits the number entered has been using the for cycle:

int cantDeDigitos = 1;
for(int i=1;i<=numero;i++){            
   cantDeDigitos = i;
   numero = numero / 10;                        
}
System.out.println("numero con "+cantDeDigitos+" digito/os");

I hope you succeed!

    
answered by 08.05.2018 / 23:52
source
2

And why not make it much simpler, tell the number to become a string , then break it into pieces, and return that bit?

Let's say, something like this:

public static int cifraInt(int numero,int posicion){
    String arr[] = String.valueOf(numero).split("");
    return arr[posicion];
}

The only thing that should be controlled is that the position is not outside the number of digits that the number has. With a if , before return , it could be easily solved.

Also, keep in mind that the array is indexed at zero, so in reality, you should look at the -1 position.

    
answered by 08.05.2018 в 19:32