四道编程题
1.
Java1.8代码:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class A1 {
public static void main(String[] args){
int i = 0;
int j = 0;
//控制台输入两组数据,每组数据中的元素用空格分割开,敲击回车结束输入
ArrayList<Integer> a1 = new ArrayList<>();
ArrayList<Integer> b1 = new ArrayList<>();
Scanner sc = new Scanner(System.in);
System.out.println("Input a1:");
String s = sc.nextLine();
Scanner sc2 = new Scanner(s);
System.out.println("Input b1:");
String s1 = sc.nextLine();
Scanner sc3 = new Scanner(s1);
while (sc2.hasNextInt()) {
a1.add(sc2.nextInt());
}
System.out.println();
while (sc3.hasNextInt()) {
b1.add(sc3.nextInt());
}
//从第一组数据中寻找待修定元素,其中i、j分别保存待修订元素在数组中的位置和值
for (int k = 1; k < a1.size(); k++) {
if (a1.get(k-1) >= a1.get(k)) {
i = k;
j = a1.get(k);
break;
}
}
//将第二组数据从小到大排序
Collections.sort(b1);
//从第二组数据的最大值开始检索,寻找满足修订的一组数据的元素,失败则返回"NO"
for (int k = b1.size() - 1; k >= 0 ; k--) {
if (b1.get(k) < a1.get(i+1) && b1.get(k) > a1.get(i-1)){
a1.set(i,b1.get(k));
break;
}
if (b1.get(k) <= a1.get(i-1)){
System.out.println("NO");
break;
}
}
//若成功找到可替换的元素(即曾经保存第一组数据待修订的值发生了变化),则输出重新修订后的一组数据
if (j != a1.get(i)){
System.out.println("Output:");
for (Integer k: a1) {
System.out.print(k + " ");
}
}
}
}
2.
Java1.8代码:
import java.util.Scanner;
public class B {
public static void main(String[] args){
//从控制台输入字符串
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
//将字符串转换成字符数组
char a[] = s.toCharArray();
//通过流程控制对字符串转换得来的字符数组进行判断,返回对应结果
for (int i = 0; i < a.length; i++) {
if (a[i] == ' ' && a[i-1] != a[i+1]){
System.out.println("false");
break;
}
if (i == a.length-1 && a[i] != a[0]){
System.out.println("false");
break;
}
if (i == a.length-1 && a[i] == a[0]){
System.out.println("true");
break;
}
}
}
}
3.
4.