Object-Oriented Programming with Java, part I – Exercise 31

This program gets the user to add in the first and last number and then prints the numbers between.

My Code

import java.util.Scanner;

public class LowerLimitAndUpperLimit {

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

        // write your code here
        System.out.print("First: ");
        int first = Integer.parseInt(reader.nextLine());
        
        System.out.print("Last: ");
        int last = Integer.parseInt(reader.nextLine());
        
        while (last >= first){
            System.out.println(first);
            first ++;
        }

    }
}

Model Code

import java.util.Scanner;

 

public class LowerLimitAndUpperLimit {

 

    public static void main(String[] args) {

        Scanner reader = new Scanner(System.in);

 

        // write your code here

 

        System.out.print("First: ");

        int first = Integer.parseInt(reader.nextLine());

        System.out.print("Last: ");

        int last = Integer.parseInt(reader.nextLine());

 

        int number = first;

        while (number <= last) {

            System.out.println(number);

            number++;

        }

    }

}

Comments

In this case, I think I might have done better than the model solution. It adds an extra variable number which really isn’t needed.

Leave a Reply

Your email address will not be published. Required fields are marked *