java新手编程题
发布网友
发布时间:2022-05-20 11:48
我来回答
共2个回答
热心网友
时间:2023-10-18 06:38
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
public class T2 {
public static void main(String[] args) {
ArrayList<String> people = new ArrayList<String>();
Scanner kb = new Scanner(System.in);
System.out.println("enter names followed " + " by the word stop: ");
String name="";
do {
name = kb.next();
if (!people.contains(name))
people.add(name);
} while (!name.equals("stop"));
Collections.sort(people);
for (String p : people)
System.out.print(p + " ");
kb.close();
}
}
追问你好,这个程序里最后输入的stop也被算在里面了,该怎么把他排除在外
追答if (!people.contains(name) && !name.equals("stop"))
people.add(name);
热心网友
时间:2023-10-18 06:39
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
public class PreventDuplicatesInArrayList {
public static void main(String[] args) {
ArrayList<String> people = new ArrayList<String>();
Scanner kb = new Scanner(System.in);
System.out.println("enter names followed " + " by the word stop: ");
String name="";
do {
name = kb.next();
if(name.equals ("stop"))
break;
if (!people.contains(name))
people.add(name);
} while (true);
Collections.sort(people);
for (String p : people)
System.out.print(p + " ");
kb.close();
}
}