简体   繁体   English

如何在Java中为字符串数组列表分配双精度值?

[英]How Do You Assign Double Values to an Array List of Strings in Java?

For this code, I create an array list where a user is prompted to enter a coin of type String into a 'purse' which is then added to the array list. 对于此代码,我创建一个数组列表,提示用户在其中输入String类型的硬币到“钱包”中,然后将其添加到数组列表中。 I have a method that returns the array list, printing out the coins in the list. 我有一个返回数组列表的方法,可以打印出列表中的硬币。 I created several other methods that act upon the array list in several ways. 我创建了其他几种以多种方式作用于数组列表的方法。 The main issue that I am having is creating a class called Coin, in which I want to assign a value to each coin entered in the array list 'coins'. 我遇到的主要问题是创建一个名为Coin的类,在其中我想为数组列表“ coins”中输入的每个硬币分配一个值。 This would allow me to create a method to add up the values of each coin in the 'coins' array or a method to spend a coin from the 'coins' array. 这将使我能够创建一种方法来累加“硬币”数组中每个硬币的值,或者创建一种方法来花费“硬币”数组中的硬币。 I thought about adding a public void setType(String entered) method in the Coins class to assign each coin entered a value, but I am not entirely sure how to go about it. 我考虑过在Coins类中添加一个公共void setType(String输入)方法来为输入的每个硬币分配一个值,但是我不完全确定该怎么做。 Once it is made, however, I know that I want to create a list: List coinPocket = new ArrayList<>(); 但是,一旦完成,我知道我想创建一个列表:List coinPocket = new ArrayList <>(); and a private method that adds the values from the Coin class to the array list:ArrayList coins = new ArrayList();. 以及一个私有方法,该方法将Coin类中的值添加到数组列表中:ArrayList coin = new ArrayList();。 I was wondering if anyone knew how I would go about this. 我想知道是否有人知道我会怎么做。 Here is all of my code so far: 到目前为止,这是我的所有代码:

public class Coin 
{   
    private String type;
    private String currencyType;

    private double penny = 0.01;
    private double quarter = 0.25;
    private double dime = 0.10;
    private double nickle = 0.05;

    public void setType(String entered)
    {

    }
}

import java.util.ArrayList;
import java.util.Scanner;
import java.util.Collections;
import java.util.List;

/**
 * 
 * A class that contains methods and variables for adding and rearranging coins in a purse. An array list of coins; two variables, TERMINATE to stop adding coins and coinEntered to represent a coin in the purse; and a Scanner for user input are used.
 */
public class Purse 
{
    ArrayList<String> coins = new ArrayList<String>();
    List<Coin> coinPocket = new ArrayList<>();

    Scanner in = new Scanner(System.in);
    private final String TERMINATE = "Q";
    private String coinEntered = " ";

        private void addCoins(String coinType)
        {
            Coin cash = new Coin();
            cash.setType(coinType);
            coinPocket.add(cash);
        }

        /**
         * A method that allows the user to add coins to their purse and second purse, assuming it is American currency. If it is not American currency, the user is asked to enter the correct currency. The user will be prompted to press Q to quit adding coins once they have added them all.
         * @param coinName
         * 
         */
        public void addCoin(String coinName)
        {
            System.out.println("Which coin would you like to add? PENNY, NICKLE, DIME, or QUARTER? Press Q to stop adding coins.");

            while (!coinEntered.equals(TERMINATE))
            {
               coinEntered = in.nextLine();

               if (coinEntered.equals("PENNY") || coinEntered.equals("NICKLE") || coinEntered.equals("DIME") || coinEntered.equals("QUARTER") || coinEntered.equals(TERMINATE))
               {
                            coins.add(coinEntered);
                            coins.remove(TERMINATE);
               }
               else
               {
                System.out.println("Sorry! You can only add American currency to the purse. Please add American currency.");
               }
            }
        }

        /**
         * Prints out the purse and its contents after adding coins.
         * @return 
         * Purse with added coins.
         */
        public ArrayList<String> printPurseContents()
        {
            return coins; 
        }

        /**
         * Reverses the order of the coins in a purse, then prints out the contents of the purse in reverse order.
         * @return
         * Reverse order of array of coins.
         */
        public ArrayList<String> reverse()
        {
           Collections.reverse(coins);
           return coins;
        }

        /**
         * A method that allows the user to transfer coins in a purse to a different purse. The coins transfered from the original purse will leave that purse empty.
         * @param otherPurse
         * 
         */
        public void transfer(Purse otherPurse)
        {   
            coins.addAll(otherPurse.coins);
            otherPurse.coins.clear();
        }   

        /**
         * Method that checks whether one purse has the same coins in the same order as another purse.
         * @param otherPurse
         * @return Prints true if the contents of each purse have the same coins and the same order of coins, or false if the contents of each purse do not have the same coins and the same order of coins.
         */
        public boolean sameContents(Purse otherPurse)
        {
            if(otherPurse.coins.equals(coins))  
            {
                System.out.println("It is true that each purse has the same coins in the same order.");
                return true;
            }
            else
            {
                System.out.println("It is false that each purse has the same coins in the same order.");
                return false;
            }
        }

        /**
         * Method that checks whether one purse has the same coins as another purse regardless of the order of coins.
         * @param otherPurse
         * @return Prints true if each purse has the same coins as another purse regardless of order, or prints false if each purse does not have the same coins as another purse regardless of order.
         */
        public boolean sameCoins(Purse otherPurse)
        {
            if(otherPurse.coins.containsAll(coins))
            {
                System.out.println("It is true that each purse has the same coins regardless of order.");
                return true;
            }
            else
            {
                System.out.println("It is false that each purse has the same coins regardless of order.");
                return false;
            }
        }

        public void addTotalCoins()
        {

        }

        public void spendCoin()
        {

        }
}       

public class PurseMain 
{
    public static void main(String[] args) 
    {   
        Purse johnnysPurse = new Purse();
        Purse otherPurse = new Purse();

        johnnysPurse.addCoin(null);
        otherPurse.addCoin(null);

        System.out.println("Purse " + johnnysPurse.printPurseContents());
        System.out.println("Purse " + otherPurse.printPurseContents());

        System.out.println();

        System.out.println(otherPurse.sameContents(johnnysPurse));
        System.out.println();
        System.out.println(otherPurse.sameCoins(johnnysPurse));

        System.out.println();

    }
}

If I understand your question correctly, you want to ask the user to enter strings like "PENNY", "DIME" etc. and create a Coin out of this. 如果我正确理解了您的问题,那么您想请用户输入“ PENNY”,“ DIME”等字符串,并以此创建Coin

To do this you could use an enum with properties, eg: 为此,您可以使用带有属性的枚举,例如:

enum CoinType {
  PENNY(0.01),
  NICKLE(0.05)
  DIME(0.1),
  QUARTER(0.25);

  private final double value;

  private CoinType( double v ) {
    value = v;
  }

  public double getValue() {
    return value;
  }
}

Then ask the user for either a number (provide a selection list) or the name. 然后向用户询问一个数字(提供选择列表)或名称。 Assuming you ask for the name you could then do the following: 假设您要求输入名称,则可以执行以下操作:

CoinType type = CoinType.valueOf( coinEntered );

Catch the IllegalArgumentException in case the user entered a wrong name. 如果用户输入了错误的名称,请捕获IllegalArgumentException

I would use an enum, bt discourage use of double, use integer instead. 我会用一个枚举,不鼓励使用double,而改用integer。

Here's my Coin class: 这是我的硬币课:

public class Coin {

  public static enum Type {
    QUARTER(25),
    DIME(10),
    NICKEL(5),
    PENNY(1);

    int value;

    Type(int value) {
        this.value = value;
    }
  }

  private Type type;

  public Coin(Type type) {
    this.type = type;
  }

  public int getValue() {
    return type.value;
  }

  public String getName() {
    return type.name();
  }

}

A new coin may be created like this: 可以这样创建一个新硬币:

String coinEntered = //get string from user
Coin coin = new Coin(Coin.Type.valueOf(coinEntered));

Note that an java.lang.IllegalArgumentException will be thrown if the entered string does not match any coin type. 请注意,如果输入的字符串与任何硬币类型都不匹配,则将抛出java.lang.IllegalArgumentException You may want to catch this exception to generate a warning message to the user. 您可能想捕获此异常,以向用户生成警告消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从数组分配到 Java 中的字符串列表 - Assign from array to list of strings in Java 当您需要在Java中通过引用传递为多个参数赋值时,您是如何做到的? - When you need pass by reference in Java to assign values to multiple parameters, how do you do it? 如何从字符串返回双精度值数组? - How to return an array of double values from the strings? 如何使用do循环在数组列表中找到双精度值的平均值? - How to find the average of double values in an array list using a do loop? Java 如何识别对象列表中不存在字符串数组的哪些值? - Java How to identify which values of an Array of Strings are not present in a List of Objects? 如何在Java 8中为变量分配lambda? - How do you assign a lambda to a variable in Java 8? 你如何在游戏中加倍缓冲java? - How do you double buffer in java for a game? 如何将字符串分配给数组列表,并显示错误消息“非静态方法引用静态上下文”? - How do I assign strings to an array list with error message “Non Static method reference Static Context”? 您如何允许用户从 Java 列表中检索值? - How do you allow a user to retrieve values from a list in Java? 如何将逗号分隔和双引号的单词字符串转换为 Java 中的字符串列表/数组 - How to convert comma separated and double quoted words string to list/array of strings in Java
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM