用Java语言编写出实现如下功能的程序每个任务至少提供一种解决方案提倡采用多种解决方案:1、比较线性表大小设线性表每个元素的类型为int从键盘输入m个元素组成A表输入n个元素组成B表比较A、B两表的大小输出比较结果。比较线性表A、B大小的规则如下:按照线性表中元素的逻辑顺序逐对比较A、B两表中的一对元素假设对Ak和Bk进行比较:1如果AkBk则比较结果为AB;2如果AkBk则比较结果为AB;3如果
解决方案1:
import java.util.Scanner;
public class CompareLists {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// 输入A表
System.out.print("请输入A表的元素个数:");
int m = scanner.nextInt();
int[] A = new int[m];
System.out.println("请输入A表的元素:");
for (int i = 0; i < m; i++) {
A[i] = scanner.nextInt();
}
// 输入B表
System.out.print("请输入B表的元素个数:");
int n = scanner.nextInt();
int[] B = new int[n];
System.out.println("请输入B表的元素:");
for (int i = 0; i < n; i++) {
B[i] = scanner.nextInt();
}
// 比较A、B两表的大小
int i = 0;
int j = 0;
while (i < m && j < n) {
if (A[i] < B[j]) {
System.out.println("A < B");
return;
} else if (A[i] > B[j]) {
System.out.println("A > B");
return;
} else {
i++;
j++;
}
}
if (i == m && j == n) {
System.out.println("A = B");
} else if (i == m) {
System.out.println("A < B");
} else {
System.out.println("A > B");
}
}
}
解决方案2:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class CompareLists {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// 输入A表
System.out.print("请输入A表的元素个数:");
int m = scanner.nextInt();
List<Integer> A = new ArrayList<>();
System.out.println("请输入A表的元素:");
for (int i = 0; i < m; i++) {
A.add(scanner.nextInt());
}
// 输入B表
System.out.print("请输入B表的元素个数:");
int n = scanner.nextInt();
List<Integer> B = new ArrayList<>();
System.out.println("请输入B表的元素:");
for (int i = 0; i < n; i++) {
B.add(scanner.nextInt());
}
// 比较A、B两表的大小
int i = 0;
int j = 0;
while (i < m && j < n) {
if (A.get(i) < B.get(j)) {
System.out.println("A < B");
return;
} else if (A.get(i) > B.get(j)) {
System.out.println("A > B");
return;
} else {
i++;
j++;
}
}
if (i == m && j == n) {
System.out.println("A = B");
} else if (i == m) {
System.out.println("A < B");
} else {
System.out.println("A > B");
}
}
}
解决方案3:
import java.util.Scanner;
public class CompareLists {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// 输入A表
System.out.print("请输入A表的元素个数:");
int m = scanner.nextInt();
Integer[] A = new Integer[m];
System.out.println("请输入A表的元素:");
for (int i = 0; i < m; i++) {
A[i] = scanner.nextInt();
}
// 输入B表
System.out.print("请输入B表的元素个数:");
int n = scanner.nextInt();
Integer[] B = new Integer[n];
System.out.println("请输入B表的元素:");
for (int i = 0; i < n; i++) {
B[i] = scanner.nextInt();
}
// 比较A、B两表的大小
int i = 0;
int j = 0;
while (i < m && j < n) {
if (A[i].compareTo(B[j]) < 0) {
System.out.println("A < B");
return;
} else if (A[i].compareTo(B[j]) > 0) {
System.out.println("A > B");
return;
} else {
i++;
j++;
}
}
if (i == m && j == n) {
System.out.println("A = B");
} else if (i == m) {
System.out.println("A < B");
} else {
System.out.println("A > B");
}
}
}
``
原文地址: https://www.cveoy.top/t/topic/hG9z 著作权归作者所有。请勿转载和采集!