简体   繁体   中英

ascending order or not

if it's in ascending order I need to print "Ascending". And if otherwise, print "Otherwise".

        int [] a = new int[args.length];

        for (int i = 0; i < args.length; i++) 
        {       
            a[i] = Integer.parseInt(args[i]);
        }
            if (a[0] <= args.length || a[0] == a[0])
            {
                System.out.println("Ascending");
            }
            else 
            {
                System.out.println("Otherwise");
            }

You seem to be having a lot more trouble with this exercise than you should. So I'll only give a hint, since this looks like homework: You should make n-1 comparisons in order to determine the order. Do that using a for loop.

To clarify: the code you presented does not contain a for loop that compares numbers, and does some comparisons that have nothing to do with verifying order of the numbers.

Hints:

  1. The following two comparisons don't do anything useful: a[0] <= args.length and a[0] == a[0] .
  2. You need to use a loop.

For one, the expression a[0] == a[0] will always evaluate to true, meaning that your current code will always enter the first condition and print "Ascending".

For another, you can't establish that a list of n elements is in ascending order without some kind of iteration. You need to use a loop or recursion to check your array's elements against each other.

Try this code

    public class Ascending 
{
    public static void main(String[] args) 
    {

        int [] a = new int[args.length];
        boolean otherwise = false;
        for (int i = 0; i < args.length; i++) 
        {       
            a[i] = Integer.parseInt(args[i]);
        }
        for(int i=1;i<a.length;i++){
            if(a[i-1]>a[i]){
                otherwise = true;
            }
        }

        if (!otherwise)
        {
            System.out.println("Ascending");
        }
        else 
        {
            System.out.println("Otherwise");
        }

    }  
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM