Question

public class NestedCountLoop
{
  public static void main(String[] args)
   {
    int sum = 0;
    for (int i = 1; sum < 5050; i++) {
    sum = sum + i;
    System.out.println(sum);
    }
   } 
}

So I have a little homework assignment for my intro programming class to use a nested loop to accept positive integer input and add all of the integers within the interval from 1 to that input. My mind is playing games with me and I'm having trouble getting going. I know I need a scanner and whatnot, and it has to print every result from 1 to n such as "The sum of 1 to 100 is 5050." Any advice is helpful

Était-ce utile?

La solution

Information on scanner at from http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

Scanner sc = new Scanner(System.in);

for (int i = o; i < 100; i++){
    int upperLimit = sc.nextInt();
    for (int w = 0; w < upperLimit; w++){
        sum = sum + i;
    }
    System.out.println("Sum is " + sum);
}

Autres conseils

public class NestedCountLoop
{
  public static void main(String[] args)
   {
    int to = Integer.parseInt(args[0]);
    int sum = 0;
    for (int i = 1; sum < to; i++) {
       sum = sum + i;
       System.out.println(sum);
    }
   } 
}

How about this one? It takes an input from the command line (arg0), and adds every number to your number (not inclusive).

So you have to compile your java file with javac, then you can run:

javac NestedCountLoop.java
java NestedCountLoop.class 100

On the other hand, the a previous solution mentioned the javadoc for your scanner, if you really need to use it. :)

System.out.println("Enter your maximum number: ");

// get the input
Scanner input = new Scanner(System.in);
int max = input.nextInt();

int sum = 0;

// iterate through an array to sum up the numbers
for (int i = 1; i < max; i++) {
    sum = sum + i; // sum += i;
}

// print out the sum after you counted everything
System.out.println(sum);
import java.util.Scanner;

public class sumoftenIntegerInput {

    public static void main(String[] args) {
        Scanner input = new  Scanner(System.in);
        int sum = 0;
        for(int i=1; i<=10; i++){
            System.out.println("Enter integer input " + i + ":");
            int a = input.nextInt();
            sum = sum + a ;

        }
        System.out.println("Total is:" + sum );
    }
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top