- #1
Darkstar3000
- 29
- 0
Write a program to input a whole number n using the Scanner class. If the number is less than 0, your program should print an error message. If the number is 0 or 1, the actual number should be printed. If the number is greater than 1, compute the sum of all integers between 1 and the given number n (1+2+...+n) using a for loop and print this sum.
it needs to be a for loop
This was my attempt at writing it, I was going to try it out in steps but bluej keeps giving me red working bar so I think something is wrong:
I made a few modifications but I don't really know how to go forth from here
it needs to be a for loop
This was my attempt at writing it, I was going to try it out in steps but bluej keeps giving me red working bar so I think something is wrong:
Code:
import java.util.Scanner;
/*
* Test Run1
*/
public class ForLoopandSum {
public static void main(String[] args) {
int n;
Scanner number = new Scanner(System.in);
n = number.nextInt();
if(n<0){
System.out.println( "You entered " + n);
}
{
System.out.println( "Please enter a whole number greater than 0 ");
}
}
}
I made a few modifications but I don't really know how to go forth from here
Code:
import java.util.Scanner;
/*
* Test Run1
*/
public class ForLoopandSum {
public static void main(String[] args) {
Scanner number = new Scanner(System.in);
System.out.println( "Enter an integer: ");
int n = number.nextInt();
if(n>=0){
System.out.println( "You entered " +n);
}
else{
System.out.println( "Please enter a value greater than 0 ");
}
}
}
Last edited: