Home > Mobile >  Producing a series based on the input: START, STEP, and END
Producing a series based on the input: START, STEP, and END

Time:11-25

So I was tasked to produced a series of numbers based on what I input on START, STEP, and END. For example: If I input 5 on the START, 2 on the STEP, and 13 on the end, then the output would be:

5, 7, 9, 11, 13

import java.util.Scanner;
public class SeriesOfNumbers {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int [] numbers = {1 ,2 ,3 ,4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20};
        int start = 0;
        int step = 0;
        int end = 0;
        boolean foundNum = false;
        
        
        System.out.print("START: ");
        start = scan.nextInt();
        for(start = 0; start <= numbers.length; start  ) {
            if(start == numbers.length) {
                foundNum = true;
                break;
            }
        }
                
        System.out.print("STEP: ");
        step = scan.nextInt();
        for(step = 0; step <= numbers.length; step  ) {
            if(start == numbers.length) {
                foundNum = true;
                break;
            }
        }
        System.out.print("END:");
        end = scan.nextInt();
        for(end = 0; end <= numbers.length; end  ) {
            if(end == numbers.length) {
                foundNum = true;
                break;
            }
        }
        if(foundNum) {
            System.out.print("The output will be: ");
        }
        }
    }

Expected output:

START: 5

STEP: 3

END: 20

The output will be: 5 8 11 14 17 20

Since I'm new to JAVA and it's my first programming language, I have no idea what I am doing. A little assistance might help. Thank you!

CodePudding user response:

You don't need multiple loops here. Your start, step and end variables are sufficient to produce your output in one loop.

for (int i = start; i <= end; i  = step) {
  System.out.print(i   " "); // just an example - you could add the number to a list instead
}

CodePudding user response:

Here's a simple program according to your description.

Notes:

  1. The variable int[] numbers and boolean foundNum was never used

  2. You only needed a single for loop for your said program.

  3. Closing your object Scanner is a good practice.

import java.util.Scanner;

public class SeriesOfNumbers {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        System.out.print("START: ");
        int start = scan.nextInt();
        
        System.out.print("STEP: ");
        int step = scan.nextInt();
        
        System.out.print("END: ");
        int end = scan.nextInt();

        System.out.print("The output will be: ");
        for (int i = start; i <= end; i  = step) {
            System.out.print(i   " ");
        }

        scan.close();
    }
    
}
  •  Tags:  
  • java
  • Related