Patriko
Patriko

Reputation: 25

Interval in Java with user choosing min and max value

I've been sitting with this problem for literally 3 hours and I'm starting to get real frustrated. I've got a few assignments from school that I'm supposed to solve and present for the teacher/students. I've solved everything except for this ONE problem that I just can't wrap my head around in any way.

So, the instructions for this problem are as follows:

The method should ask for an interval where the user gets to choose a minimum and maximum number. The method will write a series of numbers that start with the minimum value and then every 7th number. It should never write a number that is greater than the maximum value. To clarify (example):

Min = 26
Max = 57

The program writes: 26, 33, 40, 47, 54

This is my code:

String minimum, maximum;
    int mini, maxi;

        minimum = JOptionPane.showInputDialog("Insert smallest number");
        mini = Integer.parseInt(minimum);
        maximum = JOptionPane.showInputDialog("Insert biggest number");
        maxi = Integer.parseInt(maximum);
        for(int i = mini ; i <= maxi ; i++ ) {
        if(i<maxi) {
            System.out.print( mini + ", ");
        } else {
            System.out.print( mini );
        }
        mini +=7;

I realize what i <= maxi ; does, but I don't know what to replace it with. I've tried to come up with a formula to make it work, but failed every time... I've only been studying Java for like a week so please take it easy. I hope there is a kind soul out there SOMEWHERE who can clarify this for me. I will return the favor to the community down the line when I have more knowledge. Cheers.

Upvotes: 1

Views: 1240

Answers (4)

urs_ng
urs_ng

Reputation: 33

You do not need to change the mini value, let it be as it is and use i instead of mini for the for loop, this much should do, further do you want the last comma to be printed ?

for(int i = mini ; i <= maxi;i=i+7) {
    if(i<maxi) {
        System.out.print( i + ", ");
    }   
}

Upvotes: 0

Wale
Wale

Reputation: 1806

there is really no need to check if i is less than maxi again, I guess it's for the comma sake but it can be simplify as below.

 for(int i = mini ; i <= maxi; i+=7) {System.out.println(i); }

Upvotes: 0

Mahamudul Hasan
Mahamudul Hasan

Reputation: 2823

You can use this solution:

 for(; mini <= maxi ; mini+=7 ) {
        if(mini <maxi) {
            System.out.print( mini + ", ");
        } else {
            System.out.print( mini );
        }
}

Upvotes: 0

GBlodgett
GBlodgett

Reputation: 12819

A simple way to do this is change mini to i for everything except the assignment of i and then change i++ to i +=7

for(int i = mini ; i <= maxi; i+=7) {
    if(i<maxi) {
        System.out.print(i + ", ");
    } else {
        System.out.print(i);
    }       
}

Output:

26, 33, 40, 47, 54

Upvotes: 1

Related Questions