Find Name


Submit solution

Points: 40 (partial)
Time limit: 1.0s
Memory limit: 256M

Authors:
Problem type
Allowed languages
Java 19, Java 8

題目說明

設計一程式,讓使用者輸入一串名字清單(中間以空格分開),並存放於ArrayList中,直到輸入.結束。
再輸入一個名字,找出他在ArrayList的index值,印出結果。

輸入

名字清單(中間以空格分開,輸入.結束)
要查詢的名字

輸出

若找得到,輸出名字 is in the list at index 位置
若找不到,輸出名字 is not in the list.

測試資料0 輸入

John Mike Sarah Tom David .
Tom

測試資料0 輸出

Tom is in the list at index 3

測試資料1 輸入

John Mike Sarah Tom David .
James

測試資料1 輸出

James is not in the list.

Comments


  • 0
    scu09156146  commented on May 14, 2024, 12:28 p.m.

    題解

    import java.util.ArrayList;
    import java.util.Scanner;
    
    public class FindName {
    
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            ArrayList<String> namesList = new ArrayList<String>();
    
            String name = scanner.next();
            while (!name.equals(".")) {
                namesList.add(name);
                name = scanner.next();
            }
    
            String findName = scanner.next();
            scanner.close();
    
            if (namesList.contains(findName)) { // 檢查ArrayList裡是否包含要找的名字
                System.out.println(findName + " is in the list at index " + namesList.indexOf(findName));
                // 用 indexOf() 找出要找的名字(第一次)出現在哪個位置
            } else {
                System.out.println(findName + " is not in the list.");
            }
    
        }
    
    }