这是代码
Package labone;
import java.util.*;
public class LabOne {
static Scanner reader = new Scanner(System.in);
static ArrayList<String> names = new ArrayList<>();
public static void main(String[] args) {
System.out.println("type\n 1: Exercise 1 'People's names'\n '");
int choose = reader.nextInt();
switch(choose) {
case 1 :
PeopleNames();
break;
default:
System.out.println("invaild choice");
break;
}
}
public static void PeopleNames() {
//////// PEOPLES NAMES ////////
System.out.println("Enter names of people, if done enter 'done'");
String Name = reader.nextLine();
while(!"done".equals(Name)){ //if user type done exit from adding names
names.add(Name); // otherwise add names
Name = reader.nextLine(); //reads what user entered
}
//User typed 'done' and it displays the names in the arraylist
PrintArray(); // method
//Find Longest String
int largestString = names.get(0).length();
int index = 0;
for (int i = 0; i<names.size(); i++){
if(names.get(i).length() > largestString) {
largestString = names.get(i).length();
index = i;
}
}
System.out.println(names.get(index) + " is the longest name and the length is " + largestString);
//Find Shortest String
int shortestString = names.get(0).length();
int index1 = 0;
for (int i = 0; i<names.size(); i++){
if(names.get(i).length() < shortestString) {
shortestString = names.get(i).length();
index1 = i;
}
}
System.out.println(names.get(index1) + " is the shortest name and the length is " + shortestString);
//Find the Average of all the Strings
double num = names.size(); //number of elements in arraylist(size())
double length =-1;
for(String str : names){
length = length + str.length(); //sum of the lengths in the arraylist
}
length = length + names.size()-1;
num = length/num; //divide the sum with the size()
System.out.println("The average length of the names in the list: "+num);
}
//Method to view arrayList ( names )
public static void PrintArray() {
System.out.println("---------");
for(String Name : names){
System.out.println(Name);
}
}
}
结果
运行:
类型
1:练习1'人名'
1
输入人名,如果完成输入'完成'
ashmeen
布洛姆
完成了
当我将代码放在main方法中时,它给出了最短字符串和最长字符串的答案,但是,当代码放在PeopleNames方法中时,它只显示最长的字符串,但它不显示最短的字符串。
答案 0 :(得分:0)
请将reader.nextLine()
更改为reader.next()
,因为nextLine()
函数正在向arrayList添加一个空字符串作为第一个成员。代码如下所示:
String Name = reader.next();
while(!"done".equals(Name)){ //if user type done exit from adding names
names.add(Name); // otherwise add names
Name = reader.next(); //reads what user entered
}
问候。