我正在为学校做一个小程序,我需要输入一个数组。如果邻居小于Element,则必须检查数组中的每个元素。如果邻居较小 - >这些元素得到额外的*
但我遇到了边界问题,例如第一个和最后一个。第一个只有一个邻居。
public class Tops {
Scanner sc = new Scanner(System.in);
public void calculate(){
String number;
ArrayList<String> numbers; //def’s, decl’s ArrayList
ArrayList<String> after;
numbers = new ArrayList<>(); //creates numbers
after = new ArrayList<>();
number = sc.next();
while (!"0".equals(number)) {
numbers.add(number); //initializes each ArrayList element
number = sc.next();
}
for (int i = 0; i < numbers.size(); i++) {
if (Integer.parseInt(numbers.get(i)) > Integer.parseInt(numbers.get(i+1)) && Integer.parseInt(numbers.get(i)) > Integer.parseInt(numbers.get(i-1)) ){
String replace = numbers.get(i)+"*";
after.add(replace);
} else {
after.add(numbers.get(i));
}
}
for(int i=0;i<after.size();i++){
System.out.print(after.get(i)+ " ");
}
}
public static void main(String[] args) {
new Tops().calculate();
}
}
我希望你能帮助我
答案 0 :(得分:0)
由于你需要一个元素的两个邻居都要小一些来添加&#34; *&#34;,你可以跳过第一个和最后一个元素(因为它们缺少一个邻居)。
根据这一考虑调整代码:
import java.util.ArrayList;
import java.util.Scanner;
public class Tops {
private static final Scanner INPUT_SCANNER = new Scanner(System.in);
public static void calculate() {
// Initialize numbers
ArrayList<String> numbers = new ArrayList<>();
String number = INPUT_SCANNER.next();
while (!"0".equals(number)) {
numbers.add(number);
number = INPUT_SCANNER.next();
}
// Check the neighbours
ArrayList<String> after = new ArrayList<>();
// Check first element
if (numbers.get(0) > numbers.get(1)) {
after.add(numbers.get(0) + "*");
} else {
after.add(numbers.get(0));
}
// Check other elements
for (int i = 1; i < numbers.size() - 1; i++) {
int previous = Integer.parseInt(numbers.get(i - 1));
int current = Integer.parseInt(numbers.get(i));
int next = Integer.parseInt(numbers.get(i + 1));
String newElement = numbers.get(i);
if (current > next && current > previous) {
newElement = newElement + "*";
}
after.add(newElement);
}
// Check last element
if (numbers.get(numbers.size() - 1) > numbers.get(numbers.size() - 2)) {
after.add(numbers.get(numbers.size() - 1) + "*");
} else {
after.add(numbers.get(numbers.size() - 1));
}
after.add(numbers.get(numbers.size() - 1));
// Show the result
for (int i = 0; i < after.size(); i++) {
System.out.print(after.get(i) + " ");
}
}
public static void main(String[] args) {
calculate();
}
}
执行示例:
INPUT: 1 2 3 2 1 0
OUTPUT: 1 2 3* 2 1
请注意: