Sum of component numbers

2

I'm trying to solve the following problem using DESVIO CONDICIONAL COMPOSTO . But I do not know how to calculate the numbers that make up the digit.

  

Require an integer value between 100 and 999. If the value read is less than 500, display the sum between its component numbers. If not, subtract your components.

I just know that I should use IF and ELSE , where I will put this condition

if(nb > 500 ) {

for the sum of the component numbers to occur.

What I broke my mind but I really could not come to a conclusion is how I will do the sum!

For example, if the number is 328, how will I add the numbers 3, 2 and 8?

    
asked by anonymous 08.05.2018 / 02:55

3 answers

2
  • Read the user number:

    Scanner entrada = new Scanner(System.in);
    int numero = Integer.parseInt(entrada.nextLine());
    
  • Make sure the number is ok:

    if (numero < 100 || numero > 999) {
        System.out.println("Esse número não serve.");
        return;
    }
    
  • Separate components:

    int centenas = numero / 100;
    int dezenas = numero / 10 % 10;
    int unidades = numero % 10;
    
  • From now on, I'm sure you already know how to do it. :)

        
    08.05.2018 / 05:01
    0

    Use split to transform the value into an array of values and loop to read and add

      String[] array = numeroQueOUsuarioDigitar.split("");
    
      int total = 0;
    
      if(Integer.parseInt(numeroQueOUsuarioDigitar) < 500) {
          for(String e : array) {
              total += Integer.parseInt(e);
          }
      } else {
          for(String e : array) {
              total -= Integer.parseInt(e);
          }
     }
    
        
    08.05.2018 / 03:13
    0

    Break value into substrings and back to int.

        if(nb > 500 ) {
            String aux = Integer.toString(i);
            //TRANSFORMA O NUMERO EM STRING
            int un = Integer.parseInt(aux.substring(0, 1));
            //PEGA O PRIMEIRO CRACTER E TRANSFORMA EM INT
            int de = Integer.parseInt(aux.substring(1, 2));
            //PEGA O SEGUNDO CRACTER E TRANSFORMA EM INT
            int ce = Integer.parseInt(aux.substring(2, 3));
            //PEGA O TERCEIRO CRACTER E TRANSFORMA EM INT
            int total = ce + de + un;
            //SOMA OS COMPONENTES
        }else{
            String aux = Integer.toString(i);
            //TRANSFORMA O NUMERO EM STRING
            int un = Integer.parseInt(aux.substring(0, 1));
            //PEGA O PRIMEIRO CRACTER E TRANSFORMA EM INT
            int de = Integer.parseInt(aux.substring(1, 2));
            //PEGA O SEGUNDO CRACTER E TRANSFORMA EM INT
            int ce = Integer.parseInt(aux.substring(2, 3));
            //PEGA O TERCEIRO CRACTER E TRANSFORMA EM INT
            int total = ce - de - un;
            //SUBTRAI OS COMPONENTES
        }
    

    It's a very beginner code, however, so you do it using only if and else

        
    08.05.2018 / 05:25