I just can't get the numbers with decimals to display and I am trying to display it with a 2 dimension array. Is it possible to do so?
import java.util.ArrayList;
public interface VendingMachineDriver
{
public static void main(String[] args)
{
double [][] itemPQ =
{
{1.25, 20}, //Lays Chips
{1.25, 20}, //Sun Chips
{1.25, 15}, //Cheetos Chips
{1.25, 15}, //Fritos Chips
{1.25, 20}, //Doritos Chips
{1.75, 16}, //Popcorn
{1.75, 20}, //Ruffles
{1.75, 14}, //Cookie
{1.50, 9}, //Reese's
{1.50, 15}, //KitKat
{1.50, 20}, //Snickers
{1.50, 20}, //m&m's
{2.00, 20}, //Donuts
{2.00, 20}, //Pretzels
{2.00, 10}, //Cheez-it
{2.00, 15} //Chex Mix
};
String[] itemNumbers = {"A1", "A2", "A3", "A4", "B1", "B2", "B3", "B4", "C1", "C2", "C3", "C4", "D1", "D2", "D3", "D4"};
String[] itemDisplay = {"Price", "Quantity"};
VendingItem vi = new VendingItem(itemPQ, itemNumbers, itemDisplay);
vi.displayItem();
}
}
This is the second class with the methods. The array displayed when I made the itemPQ into an int, but when I make it a double it seems to stop working.
import java.util.Scanner;
public class VendingItem
{
private double[][] itemPQ;
private String[] itemNumbers;
private String[] itemDisplay;
String item;
double quantity;
double cost;
double cost1;
double quantity1;
public VendingItem(double[][] pq, String[] n, String[] d)
{
itemPQ = pq;
itemNumbers = n;
itemDisplay = d;
}
//************************************************************************************************
public VendingItem setItem(String item, double quantity, double cost)
{
this.item = item;
this.quantity = quantity;
this.cost = cost;
return this;
}
//************************************************************************************************
public void displayItem()
{
final String NUM_FMT_STR = "%5s";
final String IPQ_FMT_STR = "%5d";
final String DISP_FMT_STR = "%5s";
System.out.printf(DISP_FMT_STR, "");
for (int col=0; col<itemDisplay.length; col++)
{
System.out.printf(DISP_FMT_STR, itemDisplay[col]);
}
System.out.println();
for (int row=0; row<itemPQ.length; row++)
{
System.out.printf(NUM_FMT_STR, itemNumbers[row]);
for (int col=0; col<itemPQ[0].length; col++)
{
System.out.printf(IPQ_FMT_STR, itemPQ[row][col]);
}
System.out.println();
}
}
}
Assuming that the array is
itemPQ
, and the number you are trying to print is atitemPQ[x][y]
,he best way is either useDouble.toString(itemPQ[x][y])
or make an explicit cast by using this codeThe formatting code you seem to be using is unnecessary, as the values shown in the original are precise by two decimal places maximum.
Because a
double
extendsObject
, this means it inherits thetoString()
method