2015-09-25 109 views
0

你好,这里是我的问题我似乎无法正确我想我有我的代码逻辑错误,当我把上升的号码,然后递减它不打印打印输出我。我对编程也很陌生。 代码:升序和降序的Java

import java.util.Scanner; 
    public class tester { 
     public static void main(String[] args) { 
      int n, i, k, j; 
      int asc = 0, 
      Scanner x = new Scanner(System.in); 

      do { 

       System.out.print("How many numbers to process : "); 
       k = x.nextInt(); 

       if(k<=1) { 
        System.out.println("Enter a number greater than 1"); 
       } 
      } while(k<=1); 

      System.out.printf("Please enter %d numbers: ",k); 
      n = x.nextInt(); 

      for(i=0; i<n-1; i++) { 
       j = x.nextInt(); 
       if(j < n) { 
        asc++;    // is this right? 
       } else { 
        asc--; 
       } 
      } 
      if (asc==k) { 
       System.out.print("Not Growing Up."); 
      } 
      if (asc!=k) { 
       System.out.print("Growing Up."); 
      } 
     } 
    } 

这里是输出

Example outputs (what i'm trying to get) 
How many numbers to process : 4 
Please enter 4 numbers : 1 2 3 4 
Growing up. 

How many numbers to process : 4 
Please enter 4 numbers : 4 3 2 1 
Not Growing up. 

这是我的问题:

How many numbers to process : 4 
Please enter 4 numbers : 1 2 1 3 
Growing up.   // it should be not growing up. 

回答

1

没有必要通过所有数字进行迭代。你可以检查前面的数字是否较低(如果增长)。如果没有,打印并返回。检查我的示例代码。

更换

n = x.nextInt(); 
for (i=0; i<n-1; i++) { 
    j = x.nextInt(); 
    if(j < n) { 
     asc++;    // is this right? 
    } else { 
     asc--; 
    } 
} 
if (asc==k) { 
    System.out.print("Not Growing Up."); 
} 
if (asc!=k) { 
    System.out.print("Growing Up."); 
} 

随着

int prev = x.nextInt(); 
for (i=0; i<k-1; i++) { 
    j = x.nextInt(); 
    if (j < prev) { System.out.print("Not Growing Up."); return; } 
    prev = j; 
} 
System.out.print("Growing Up."); 
0
String numbers = "1 2 3 4"; // Let's take this input for example 
    int temp = 0;    // This use to compare previous integer 
    boolean isAsc = false;  // This store whether the digits is growing up or not 

    StringTokenizer st = new StringTokenizer(numbers); // Declare StringTokenizer 
    while (st.hasMoreTokens()) { 

     int next = Integer.parseInt(st.nextToken()); // Put the first integer in next (1) 

     if(next > temp){ // if (1) > 0 

     temp = next;  // Assign 1 to temp, next time digit 2 will compare with digit 1   
     isAsc = true; // Assign the ascending to true 

     } else 

     isAsc = false; 
    } 

    if(isAsc) 
     System.out.print("Growing up."); 
    else 
     System.out.print("Not growing up."); 
    } 

您可以将用户输入存储为像变numbers我声明了一个字符串,并将其分解到每个令牌进行比较的目的。

-1
import java.lang.reflect.Array; 
import java.util.*; 

public class A1 { 
public static void main(String[] args) { 
    int a[]={2,5,0,1}; 
    Arrays.sort(a); 
    int b= a.length; 
    for(int i=0;i<a.length;i++) 
    { 

     System.out.println(+a[i]+"\t"+a[b-1]); 
     b--; 



    } 


} 

}