在Java中进行状态猜测 - arrayLists和用户输入

时间:2017-02-08 03:38:17

标签: java parsing input javac

我不确定发生了什么。它距离它的位置还有很长的路要走,但它仍然不起作用。这个练习的目的是让用户从预定状态列表中猜出“你最喜欢的状态”。用户只进行三次猜测,然后程序停止。

import java.io.*;
import java.util.*;

    class stateHelper {
    public static void getUserInput() { 
        ArrayList<String> stateList = new ArrayList<String>();
        stateList.add("Georgia");
        stateList.add("Hawaii");
        stateList.add("Arizona");
        stateList.add("New York");
        stateList.add("Montana");

        Scanner scan = new Scanner(System.in);
        String userInput = scan.next();
        System.out.println("Guess my favorite state: ");

        //loop three times
        int num = stateList.size();
        for (int i = 0; i < num ; i++) {
            // if state is in line, print you guessed it
            String st = stateList.get(i);
            System.out.println(st);
            /*if (userInput.equals(stateList.get(i))) {
                System.out.println("It is a hit."); 
                }               
            }
            if (!userInput.equals(stateList.get(i))) {
                System.out.println("It is a miss.");    
                } */
        }
    /*
    System.out.println(stateList.get(0)+
    stateList.get(1)+stateList.get(2)+stateList.get(3)+
    stateList.get(4));
    */

        }
    }

2 个答案:

答案 0 :(得分:0)

我可以轻松地为你解决这个问题,但我认为教你如何钓鱼会很好....正如他们所说。

解决问题。

  1. 从用户那里获取数字。谷歌java用户输入,提示:使用System.in 例如How can I get the user input in Java?

  2. 打印用户输入回屏幕的内容,System.out

  3. 一旦你有了数字,例如1 2 3作为输入,您可以将这些数字拆分成一个数组,例如请参阅Convert a string of numbers into an array

  4. 循环数组,添加所有数字并使用数组的计数或长度来跟踪分隔符。例如(1 + 2 + 3 + 4 + 7 + 8)/ 6 =平均

  5. 如果您发布了一些代码来展示尝试,我们很乐意进一步提供帮助:)

答案 1 :(得分:0)

import java.util.Iterator;
import java.util.LinkedList;
import java.util.Scanner;


public class Averager {
    public static void main(String[] args) {
        LinkedList<Integer> numbers = new LinkedList<Integer>();

        System.out.println("Enter a number to add to the list, or QUIT to stop:");
        Scanner scanner = new Scanner(System.in);
        String userInput = scanner.next();
        while (!userInput.equalsIgnoreCase("QUIT")) {
            try {
                numbers.add(Integer.parseInt(userInput));
            } catch (NumberFormatException e)    {
                // IGNORE
            }
            userInput = scanner.next();
        }
        scanner.close();

        System.out.println("The average of these numbers is: " + average(numbers));

    }

    private static double average(LinkedList<Integer> numbers) {

        Integer top = 0, bottom = 0;

        for (Iterator<Integer> iterator = numbers.iterator(); iterator.hasNext();) {
            top += (Integer) iterator.next(); // Sum the numbers
            bottom++;  // count how many there are
        }

        if (bottom > 0) {
            return top/bottom;  // calculate the average
        }

        return 0;
    }

}