我不太确定发生了什么事。它已经走了很长一段路,但它仍然不起作用。本练习的目的是让用户从预先确定的状态列表中猜测“您最喜欢的状态”。用户只有三次猜测,然后程序就停止了。
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));
*/
}
}发布于 2017-02-08 11:45:04
我可以很容易地为你解决这个问题,但我认为教你如何钓鱼会很好……就像他们说的那样。
把问题分解。
如果您发布一些代码来演示一次尝试,我很乐意提供进一步的帮助:)
发布于 2017-02-08 13:17:04
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;
}
}https://stackoverflow.com/questions/42104250
复制相似问题