您好我的问题我似乎无法正确打印输出我猜我的代码中存在逻辑错误,当我输入升序然后降序时它不会打印。我也是编程的新手。 代码:
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.
答案 0 :(得分: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.");
答案 1 :(得分: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
一样,并将它们分解为每个标记以进行比较。
答案 2 :(得分:-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--;
}
}
}