【发布时间】:2017-07-19 22:39:19
【问题描述】:
这是代码
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是最长的名字,长度是7
是最短的名字,长度为 0 DOES NOT GIVE ANSWER
列表中名字的平均长度:4.0
构建成功(总时间:12 秒)
当我将代码放在 main 方法中时,它会给出最短字符串和最长字符串的答案,但是,当代码放在 PeopleNames 方法中时,它只显示最长的字符串,但不显示最短的字符串。
【问题讨论】:
-
您能描述一下您自己调试此代码所采取的步骤吗? “它在 main 方法中起作用”可能有点含糊。
-
我已经添加了结果。
-
当我将代码放在 main 方法中时,它给出了最短字符串和最长字符串的答案,但是,当代码放在 PeopleNames 方法中时,它只显示最长的字符串,但它没有显示最短的字符串。
-
@AshmeenCloete 确保您的数组中没有值
""(空字符串)。这可能会导致查找最短名称时出现问题。 -
它没有,但我会仔细检查。
标签: java string arraylist methods