Question: I am a complete beginner to java. I have to create a simple program using methods. The program will prompt the user for an int.
I am a complete beginner to java. I have to create a simple program using methods. The program will prompt the user for an int. Then I have to use a method to add all the integers, starting from 1 to up to and including the number entered. Once added, I have to print the sum of numbers up to that point.
I must create a scanner. The only outside methods I can use are Scanner methods and print methods. I cannot have more than one loop in the program. Lastly, I need to create a method separate from the main method. I must repeat this process three times so that the output looks something like this:
?
This is what I have right now:
package main;
import java.util.Scanner;
public class Assignment5 {
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Please enter an integer");
int n = scan.nextInt();
int sum = 0;
Assignment5 obj = new Assignment5();
sum = obj.sumUpto(n);
System.out.println(sum);
System.out.println("Enter an integer");
int n = scan.nextInt();
sum = obj.sumUpto(n);
System.out.println(sum);
System.out.println("Enter a third number");
int n = scan.nextInt();
sum = obj.sumUpto(n);
System.out.println(sum);
scan.close();
}
public static int sumUpTo(int n)
{
int sum; //declaration
sum = 0; //initialization
for (int i = 1; i
{
sum = sum + i;
}
return sum;
}
}
I am getting errors because I have duplicate n variables and because the method sumUpto(int) is undefined for the type Assignment5. I'm unsure on how to fix them.
Thank you in advance!
Please enter an integer 5 15 Enter another number 10 Enter a third number 3 6
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
