Consecutive addition

0

Hi, I'm learning how to program and I had to make a code that adds several numbers but when I run it gets stuck after putting the number of numbers to add, someone knows where I'm wrong.

here the code:

import java.util.Scanner;
  public class Suma{
    public static void main (String [] args) {
   Scanner entrada = new Scanner( System.in);
     int s = 0;
     int suma = 0;
      int n=0;
     String salida= "";

  System.out.println(" Cuanto numeros deseas sumar");
         n =  entrada.nextInt();  
     while( s<=n);{
        suma = suma+s; 
           s= s+1;}


System.out.println( salida+ " El resultado es " +suma);
}
}
    
asked by Irvin Miguel Angulo 16.04.2018 в 20:08
source

3 answers

0

This should be the order of your code.

public class Suma {
    public static void main(String[] args) {
        Scanner entrada = new Scanner(System.in);
        int numero = 0, acu = 0, suma = 0, n;
        String salida = "";

        System.out.println("Cuanto numeros deseas sumar: ");
        n = entrada.nextInt();
        while (acu < n) {
            System.out.println("Dame un numero: ");
            numero = entrada.nextInt();
            suma = suma + numero;
            acu++;
        }

        System.out.println(" El resultado es " + suma);
    }
}
    
answered by 16.04.2018 в 20:23
0

Try this in the last line, maybe the error is because you add and concatenate at the same time, that is, you use the + sign for String and int

System.out.println ("The result is" + (sum));

    
answered by 16.04.2018 в 20:26
0

The fundamental problem is syntax error while( s<=n);{ , after parentheses goes the start of the key and not a (; ). PD: Here are some tips that will make your life easier:

  • Instead of writing s= s+1; you can write this s++; will increase by 1 s but when you finish reading the sentence or you can type ++s; which is the other way around
  • Like instead of suma = suma+s; you can write suma += s; will do the same
  • If you are not going to write anything in the variable output it is not necessary to put it System.out.println( salida+ " El resultado es " +suma); or declare it, you are only occupying space in memory unnecessarily System.out.println(" El resultado es " +suma); you can do it like this
answered by 21.04.2018 в 10:32