Home > Enterprise >  x-- causes if to loop infinitely
x-- causes if to loop infinitely

Time:10-14

I want to make something that if I type "1" the numbers will be ascending(x ) and if I type "2" it will be descending. x works fine but if I use x--, it will loop infinitely

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

    System.out.print("Enter starting loop:");
    int start = scan.nextInt();
    
    System.out.print("Enter ending loop:");
    int end = scan.nextInt();
    
    System.out.print("Choose Order:");
    int n = scan.nextInt();
    if(n==1){
    for (int x=start;x<=end;x--){
        System.out.print(x   "\t");
    
    
        }
    {
        
    }
        
        
    }
    }}

CodePudding user response:

Change it to x>=end instead of the current x<=end for the 2nd loop. Basically you have to make two for loops:

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


System.out.print("Enter starting loop:");
int start = scan.nextInt();

System.out.print("Enter ending loop:");
int end = scan.nextInt();

System.out.print("Choose Order: ");
int n = scan.nextInt();


  if(n==1)
    {
    for (int x=end;x>=start;x--){  //If they want to go from end to 0
        System.out.print(x   "\t");
        }
else
{
for (int x=start;x<=end;x  ){  //So when they want it to go from 0 to end
        System.out.print(x   "\t");
        }

 

CodePudding user response:

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

    System.out.print("Enter starting loop:");
    int start = scan.nextInt();

    System.out.print("Enter ending loop:");
    int end = scan.nextInt();

    System.out.print("Choose Order:");
    int n = scan.nextInt();

    boolean isAscending = n == 1;
    for (int i = start; (isAscending) ? i <= end : i >= end; i = (isAscending) ? i   1 : i - 1) {
        System.out.print(i   "\t");
    }
}

Examples: from 1 to 10 with order 1

Enter starting loop:1
Enter ending loop:10
Choose Order:1
1   2   3   4   5   6   7   8   9   10

Examples: from 10 to 1 with order 2

Enter starting loop:10
Enter ending loop:1
Choose Order:2
10  9   8   7   6   5   4   3   2   1
  • Related