提示用户输入数组的大小并允许用户访问 输入整数值到您的数组。检查每个元素是否均匀 或奇怪的。如果是偶数,打印解决了elemets(升序),如果奇数,得到 使用条件语句的最大值和最小值。输出结果。
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number: ");
int n = sc.nextInt();
int s[] = new int[n];
for (int i = 0; i < n; i++) {
int e = sc.nextInt();
s[i] = e;
}
Arrays.sort(s);
System.out.println("\nEven numbers in ascending order:");
for (int j = 0; j < n; j++) {
if (s[j] % 2 == 0) {
System.out.print(s[j] + " ");
}
}
System.out.println("\nOdd numbers in descending order:");
for(int j = (n -1); j >= 0; j--) {
if (s[j] % 2 == 1) {
System.out.print(s[j] + " ");
}
}
}
我不知道如何为Odd
添加min / max答案 0 :(得分:1)
如果我理解你的问题,你可以试试这个:
int min = Integer.MAX_VALUE; // init min to the most max value
int max = 0; // store max value
for(int j = (n -1); j >= 0; j--) {
if (s[j] % 2 == 1) {
if (min > s[j]) {
min = s[j];
}
if (max < s[j]) {
max = s[j];
}
System.out.print(s[j] + " ");
}
}
System.out.println("min = " + min);
System.out.println("max = " + max);
完整代码:
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number: ");
int n = sc.nextInt();
int s[] = new int[n];
for (int i = 0; i < n; i++) {
int e = sc.nextInt();
s[i] = e;
}
Arrays.sort(s);
System.out.println("\nEven numbers in ascending order:");
for (int j = 0; j < n; j++) {
if (s[j] % 2 == 0) {
System.out.print(s[j] + " ");
}
}
//===========================================
System.out.println("\nOdd numbers in descending order:");
int min = Integer.MAX_VALUE; // init min to the most max value
int max = 0; // store max value
for(int j = (n -1); j >= 0; j--) {
if (s[j] % 2 == 1) {
if (min > s[j]) {
min = s[j];
}
if (max < s[j]) {
max = s[j];
}
System.out.print(s[j] + " ");
}
}
System.out.println(); // for new line
System.out.println("min = " + min);
System.out.println("max = " + max);
}
答案 1 :(得分:0)
我的问题的解决方案是:
Scanner sc = new Scanner(System.in);
while (true) {
System.out.print("Enter a Value: ");
int val = s.nextInt();
if (val == 0) {
break;
}
if (val < min) {
min = val;
}
if (val > max) {
max = val;
}
}
System.out.println("min: " + min);
System.out.println("max: " + max);