How to create a Java method?

Hello, we are supposed to create a Java method that calculates the sum of all individual numbers up to an arbitrary number. We are supposed to code this task using while loops.

Can someone explain the task to me in words and give me an example, and then tell me how to get started?

thanks in advance

(2 votes)
Loading...

Similar Posts

Subscribe
Notify of
6 Answers
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
ohwehohach
2 years ago

Well, what do you need? A variable that stores the previous sum. They are initialized with 0.

int summe = 0;

Then you need a loop that counts up to the desired number and adds the current number to the sum:

int aktuelleZahl = 1;
while (aktuelleZahl <= zielZahl)
{
  summe += aktuelleZahl;
  aktuelleZahl++;
}

The method should now return the result:

return summe;

Target number must be transferred to the method as a parameter. Your task is to google or look into the documents of your computer science teaching, how to declare a method with a parameter in Java 😉 Then you pack the above code and call it.

ZaoDaDong
2 years ago
Reply to  ohwehohach

I guess it wasn’t the first time this question came up.

ohwehohach
2 years ago
Reply to  ZaoDaDong

Maybe I didn’t look.

ohwehohach
2 years ago

Ohso – nee, no copy & paste 😀 I can only type a bit fast…

ZaoDaDong
2 years ago

Thought only because the answer was almost 1 minute after creating the question.

daCypher
2 years ago

The task explained in simple words:

The program should ask for a number. For example, you enter a seven. Then the program should form the sum of all numbers up to 7.

So 1+2+3+4+5+6+7=28

Why you should do this with a while loop and not meaningfully with a for loop (or with the Gaussian cum formula), but I don't know. This is one of the peculiar special conditions that students are sometimes placed. Probably so that students learn to solve problems in different ways.

I used to make a few different variants:

 import java.util.*; import java.util.stream.*; public class GaussSum { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Bitte geben Sie ein, bis zu welcher Zahl die Summe gebildet werden soll: "); int ende = in.nextInt(); // Lösung mit for-Schleife int summe = 0; for (int i = 1; i <= ende; ++i) { summe += i; } System.out.println("Lösung mit for-Schleife: " + summe); // Lösung mit IntStream System.out.println("Lösung mit IntStream: " + IntStream.rangeClosed(1, ende).sum()); // Lösung mit der Gaussschen Summenformel System.out.println("Lösung mit der Gaussschen Summenformel: " + (ende * (ende + 1) / 2)); // Lösung mit while-Schleife // Ha, hier musst du selbst nachdenken :-P } }