用数组列表跟踪用户输入总数

时间:2015-07-11 17:57:40

标签: java methods arraylist

任何人都可以看到为什么在我输入输入时不会更新总数?

这是一个程序的草稿,它应该继续提示用户输入(' apple',' blueberry''花生&#39 ;只有)直到用户表示他们想要退出(' q")。我为每个输入创建了ArrayLists,以跟踪每个输入的输入次数。

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);     
   }       
}

2 个答案:

答案 0 :(得分:1)

你的ONE调用getPie()不会返回,直到用户输入“q”...你迫使可怜的饥饿客户离开而没有任何馅饼:(

答案 1 :(得分:1)

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。

你可以扩展它,例如如果你感兴趣的字符串在运行时没有修复或知道使用地图,那么地图就会串到各自的计数器。

相关问题