Reputation: 25
So I need my code to print out in increments on 3 user inputs, I have a 2nd java file to use dot notation to execute methods from. So it's supposed to run kinda like this.
Pick > Starting Value - Pick Increment value - Pick > Ending Value All these are user input and I need to have it if the starting value > then the ending then count up from starting value with user input increments. But if end
import java.util.Scanner;
public class logic {
public static void main(String [] args) {
//new scanner
Scanner input = new Scanner(System.in);
//Data
char ch = 0;
int start = 0;
int end = 0;
int inc = 0;
String printStr = "";
final int SENTINEL = -1;
String menu ="Looping (Demo)" +
"\nStart Value\t [S]" +
"\nIncrement value [I]" +
"\nEnd Value\t [E]" +
"\nFor Looping\t [F]" +
"\nQuit\t\t [Q]" +
"\nEnter Option > ";
while(ch != SENTINEL) {
switch(ch) {
case 'S':
case 's':
start = UtilsDM.readInt("Enter loop start value: ", false);
break;
case 'I':
case 'i':
inc = UtilsDM.readInt("Enter loop increment value: ", false);
break;
case 'E':
case 'e':
end = UtilsDM.readInt("Enter loops end value: ", false);
break;
case 'F':
case 'f':
if(start <= end){
for (int i=start; i<=end; i+=inc) {
System.out.print(i + " ");
}//end loop +
}//end if
else if(start >= end){
for (int i=end; i<=start; i-=inc) {
System.out.print(i + " ");
}//end loop -
}//end else if
System.out.println("\n");
break;
case 'Q':
case 'q':
System.out.println("Terminating upon user command.");
System.exit(0);
break;
default:
System.out.println("Unrecognized character");
break;
}//end switch
ch = UtilsDM.readChar(menu, false);
}//end loop
//computations, algorithms
//outputs, formatting, display
} //end main
}//end class
Upvotes: 2
Views: 51
Reputation:
Change the case 'F' to as follows, i have commented the changes :-
case 'F':
case 'f':
if(start < end || (start < 0 && end < 0 && end > start)) // start < end or start = -3 and end = -7
{
for (int i=start; i<=end; i+=inc)
{
System.out.print(i + " ");
}
}
else if(start > end || (start < 0 && end < 0 && start > end)) // if start = - 7 and end = -3
{
for (int i=end; i>=start; i-=inc) // should be greater than
{
System.out.print(i + " ");
}
}
else if(start == end)
{
System.out.println(end);
}
Upvotes: 2