题目要求
题目分析
方法一:
定义一个ArrayList,然后用永真条件的while循环接收输入,如果输入的是一个点,就退出循环,否则就将输入的这个字符串添加到list中。待输入完毕,查看list的长度,分别有小于2,大于等于2但小于14和大于等于14三种情况,分别和题目的三种情况对应。
方法二:(这种方法好像很麻烦)
设置一个计数器count和name1,name2三个变量,每输入一次就让计数器增1,并判断count的值,如果count等于2,给name1赋值,等于14给name2赋值。最后根据count的值对应输出name1和name2(或者不输入)。
示例代码1
import java.util.ArrayList;
import java.util.Scanner;
public class L1_035 {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
Scanner sc = new Scanner(System.in);
while(true) {
String str = sc.nextLine();
if(str.equals(".")) {
break;
}else {
list.add(str);
}
}
sc.close();
if(list.size() < 2) {
System.out.println("Momo... No one is for you ...");
}else if(list.size() < 14) {
System.out.println(list.get(1) + " is the only one for you...");
}else {
System.out.println(list.get(1) + " and " + list.get(13) + " are inviting you to dinner...");
}
}
}
示例代码2
import java.util.Scanner;
public class L1_035 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//记录输入人数的计数器变量
int count = 0;
String name1 = null;
String name2 = null;
String name = null;
do {
name = input.nextLine();
count++;
if(count == 2) {
name1 = name;
}
if(count == 14) {
name2 = name;
}
} while(!".".equals(name)) ;
input.close();
if(count <= 2) {
System.out.println("Momo... No one is for you ...");
} else if(count > 2 && count <= 14) {
System.out.println(name1 + " is the only one for you...");
} else {
System.out.println(name1 + " and " + name2 + " are inviting you to dinner...");
}
}
}