简体   繁体   中英

In java, how do I make a loop statement to print the sum of positive nums from 1 to the value assigned to an int from an input from a scanner?

how do I make a loop statement to print the sum of positive numbers from 1 to the value assigned to int from input from a scanner?

public static void main(String[] args) {
    int num = 0;
    int sum = 0;
    
    Scanner sc = new Scanner(System.in);
    System.out.println("Input a number over value 1 ");
    num = Integer.parseInt(sc.nextLine());
    
    if (num <= 0) {
        System.out.println("the number has be an Integer");
        return;
    }
    
    for (int i = 1; i <= num; i++) {
        System.out.println(i + "+");
        sum += i;
        // I have no idea what I can do from here one?
    }
}
public static void getData() {
    System.out.println("Please enter user input  ");
    Scanner sc = new Scanner(System.in);
    int input = sc.nextInt();
    if (input == 0) {
        System.out.println("user input cann't accept.");
    } else {
        int sumValue = 0;
        for (int j = 1; j <= input; j++) {
            sumValue = sumValue + j;
        }
        System.out.println(sumValue);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM