Java 使用数组列表跟踪用户输入总计
有人能看到为什么我输入输入时总数不更新吗 这是一个程序的草稿,该程序应该一直提示用户输入‘苹果’、‘蓝莓’、‘花生’,直到用户表示要退出‘q’。我为每个输入创建了ArrayList,以跟踪每个输入的次数Java 使用数组列表跟踪用户输入总计,java,methods,arraylist,Java,Methods,Arraylist,有人能看到为什么我输入输入时总数不更新吗 这是一个程序的草稿,该程序应该一直提示用户输入‘苹果’、‘蓝莓’、‘花生’,直到用户表示要退出‘q’。我为每个输入创建了ArrayList,以跟踪每个输入的次数 import java.util.ArrayList; import javax.swing.JOptionPane; import java.util.*; public class ArrayListLoop { public static void main(String[] ar
import java.util.ArrayList;
import javax.swing.JOptionPane;
import java.util.*;
public class ArrayListLoop {
public static void main(String[] args) {
String pie = getPie();
int aTotal = fillApple(pie);
int bTotal = fillBlueberry(pie);
int pTotal = fillPeanut(pie);
if (pie.equalsIgnoreCase("q")) {
print(aTotal, bTotal, pTotal);
}
}
public static String getPie() {
String pie;
do {
pie = JOptionPane.showInputDialog("Enter type of pie");
} while(!pie.equalsIgnoreCase("q"));
return pie;
}
public static int fillApple(String pie) {
int appleTotal = 0;
ArrayList<String> apple = new ArrayList<String>();
if (pie.equalsIgnoreCase("apple")) {
apple.add(pie);
appleTotal++;
}
return appleTotal;
}
public static int fillBlueberry(String pie) {
int blueberryTotal = 0;
ArrayList<String> blueberry = new ArrayList<String>();
if (pie.equalsIgnoreCase("blueberry")) {
blueberry.add(pie);
blueberryTotal++;
}
return blueberryTotal;
}
public static int fillPeanut(String pie) {
int peanutTotal = 0;
ArrayList<String> peanut = new ArrayList<String>();
if (pie.equalsIgnoreCase("peanut")) {
peanut.add(pie);
peanutTotal++;
}
return peanutTotal;
}
public static void print(int appleTotal, int blueberryTotal, int peanutTotal) {
JOptionPane.showMessageDialog(null, appleTotal + "\n" + blueberryTotal + "\n" + peanutTotal);
}
}
您对getPie的一个调用在用户输入q之前不会返回。您正在迫使饥饿的可怜客户离开,而不带任何pie:
do {
pie = JOptionPane.showInputDialog("Enter type of pie");
} while(!pie.equalsIgnoreCase("q"))
这是程序的主循环。在得到字符串q之前,您一直在查询用户
你可能得到的每一根绳子都会被扔掉
您还需要将处理其他字符串的代码作为q放入该循环:
int aTotal = fillApple(pie);
int bTotal = fillBlueberry(pie);
int pTotal = fillPeanut(pie);
虽然那不容易
如果我没听错的话,你基本上想要的是计算某些字符串的出现次数。因此,您需要为感兴趣的每个字符串设置一个计数器:
int apples = 0;
int blueberries = 0;
int peanuts = 0;
然后进入主循环
do {
向用户查询字符串
String pie = JOptionPane.showInputDialog("Want pie! ");
然后检查该字符串是否与您感兴趣的字符串之一匹配
if (pie.equalsIgnoreCase("apple")) {
apples = apples + 1;
} else if // and so on
并运行该命令,直到字符串与q比较:
} while(! pie.equalsIgnoreCase ("q"));
之后,您可以按照预期的方式呈现结果
这里不需要ArrayList
例如,如果您感兴趣的字符串在运行前不固定或不知道如何使用映射,则可以将其展开,这样可以将字符串映射到各自的计数器。这是正确的。与其在每个方法中都有本地ArrayList对象,不如将它们设置为全局对象或使用HashMap来保持计数。。。这还有意义吗?你忽略了每一个输入,你的列表对你的程序也没有任何价值。