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.
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
You can use this solution:
for(; mini <= maxi ; mini+=7 ) {
if(mini <maxi) {
System.out.print( mini + ", ");
} else {
System.out.print( mini );
}
}
确实没有必要再次检查我是否小于maxi,我想这是出于逗号的原因,但可以将其简化如下。
for(int i = mini ; i <= maxi; i+=7) {System.out.println(i); }
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 + ", ");
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.