Arraylist doesn't add - java

I've a problem that I don't understand about adding an element into the ArrayList.
The result show me that it hasnt added the two computers.
Someone can help me ?
Computer computer;
GenerateXML xml;
Parser dom = new Parser();
List computers = new ArrayList();
computer = new Computer("2", "fisso", "Corsair", "Venom 2X", 1029971511, 4.5f, 12, 32, 600, 24.0f, 1900, "Linux", "21-10-2021");
computers.add(computer);
computer = new Computer("3", "laptop", "Microsoft", "Surface", 1000091801, 4.5f, 12, 32, 600, 24.0f, 1900, "Linux", "21-10-2021");
computers.add(computer);
try {
xml = new GenerateXML(computers);
xml.printToFile("computer.xml");
} catch (ParserConfigurationException | TransformerException exception) {
System.out.println("Errore generate!");
}
try{
computers = dom.parseDocument("computer.xml");
} catch (ParserConfigurationException | SAXException | IOException exception){
System.out.println("Errore parsing!");
}
System.out.println("Numero computers: " + computers.size());
for (int i = 0; i < computers.size(); i++)
System.out.println(computers.get(i));
The result is:
Numero computers: 0

You initialize computers to be an empty list.
List computers = new ArrayList();
Then you add two computers to your list.
computer = new Computer("2", "fisso", "Corsair", "Venom 2X", 1029971511, 4.5f, 12, 32, 600, 24.0f, 1900, "Linux", "21-10-2021");
computers.add(computer);
computer = new Computer("3", "laptop", "Microsoft", "Surface", 1000091801, 4.5f, 12, 32, 600, 24.0f, 1900, "Linux", "21-10-2021");
computers.add(computer);
At this point, your computers list will contain two computers. The size of the list will be two.
Then you assign a new value to the computers list in your second try/catch block. By doing this, you lose the list you had created and populated before. After this, computers will be a completely new list.
computers = dom.parseDocument("computer.xml");

Related

Convert String Array to int using JOptionPane

I'm doing a train ticket program. I want to convert certain text in the string array to a certain price using JOptionPane.
ex.
String[] option_1 = {"location1","location2", "location3","location4","location5"};
where location1 = $10, location2 = $23, etc.
all I know is I could use Interger.parseInt or double, but I don't know where to go next. Should I go with a loop or make a whole new array and make it equal to the string array. I'm wondering if there is a more easier method to execute this.
code :
public static void main (String [] args) {
String name;
String[] option_1 = {"North Avenue","Quezon Avenue", "Kamuning","Cubao","Santolan","Ortigas","Shaw","Boni","Guadalupe","Buendia","Ayala","Magallanes","Taft"};
String[] option_2 = {"North Avenue","Quezon Avenue", "Kamuning","Cubao","Santolan","Ortigas","Shaw","Boni","Guadalupe","Buendia","Ayala","Magallanes","Taft"};
name = JOptionPane.showInputDialog("Welcome to DME Ticketing System!\n\nEnter your name:");
String leave = (String)JOptionPane.showInputDialog(null, "Leaving from",
"Train Station", JOptionPane.QUESTION_MESSAGE, null, option_1, option_1[0]);
String going = (String)JOptionPane.showInputDialog(null, "Leaving from",
"Train Station", JOptionPane.QUESTION_MESSAGE, null, option_2, option_2[0]);
// int pay = (Integer)JOptionPane.showInputDialog(null, "From: "+leave+"\nTo: "+going+"\nFare Price: "+"\n\nEnter your payment amount:",
// null, JOptionPane.PLAIN_MESSAGE, null, null,null);
// int op1 = Integer.parseInt(going);
// int op2 = Integer.parseInt(leave);
JOptionPane.showMessageDialog(null, "DME Ticketing System\nMalolos, Bulacan\n\n"
+ "Name: "+name
+"\nLocation: "+leave
+"\nDestination: "+going
+"\nFare: "
+"\nPayment: "//+pay
+"\nChange: "
, "RECEIPT",JOptionPane.INFORMATION_MESSAGE);
}
-The codes I turned into comments are giving me errors
showInputDialog always returns the input of the user as a String object, except from a variation where it returns the selected Object from the supplied ones. I am talking for Java version 8 for the sake of example.
Based on your question and comments, you basically want to:
Match String objects (their name) to integers (their value), so that you can calculate how much they will have to pay, plus the change afterwards.
Receive as input from the user the amount they will give, in order to calculate the change.
If so, then:
For the first case you can use some data structure(s) from which you will be able to match the locations with their value. For example a HashMap<String, Integer> can match the locations with their value, like so:
//Set up the origin options, along with their value:
HashMap<String, Integer> leavingOptions = new HashMap<>();
leavingOptions.put("North Avenue", 10);
leavingOptions.put("Quezon Avenue", 11);
leavingOptions.put("Kamuning", 12);
leavingOptions.put("Cubao", 13);
leavingOptions.put("Santolan", 14);
leavingOptions.put("Ortigas", 15);
leavingOptions.put("Shaw", 16);
leavingOptions.put("Boni", 17);
leavingOptions.put("Guadalupe", 18);
leavingOptions.put("Buendia", 19);
leavingOptions.put("Ayala", 20);
leavingOptions.put("Magallanes", 21);
leavingOptions.put("Taft", 22);
//Get user input for origin:
Object[] leavingOptionsArray = leavingOptions.keySet().toArray();
String leaving = (String) JOptionPane.showInputDialog(null, "Leaving from:", "Train Station", JOptionPane.QUESTION_MESSAGE, null, leavingOptionsArray, leavingOptionsArray[0]);
//Show output depending on user's input or cancel:
if (leaving != null)
JOptionPane.showMessageDialog(null, "You shall pay: " + leavingOptions.get(leaving));
else
JOptionPane.showMessageDialog(null, "Quiting...");
(note here that the casting of the returned value of the showInputDialog to a String reference is safe, just because the way we set up the options' array to contain only String objects)
Or you can use a String array with the locations along with an int array with the corresponding values, like so:
//Set up the origin options, along with their price:
String[] leavingOptions2 = new String[]{"North Avenue","Quezon Avenue", "Kamuning","Cubao","Santolan","Ortigas","Shaw","Boni","Guadalupe","Buendia","Ayala","Magallanes","Taft"};
int[] price = new int[]{10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22};
//Get user input for origin:
Object leaving2 = JOptionPane.showInputDialog(null, "Leaving from:", "Train Station", JOptionPane.QUESTION_MESSAGE, null, leavingOptions2, leavingOptions2[0]);
//Show output depending on user's input or cancel:
if (leaving2 != null) {
//Find the price of the selected location:
int p = -1;
for (int i = 0; i < price.length; ++i)
if (leaving2.equals(leavingOptions2[i])) {
p = price[i];
break;
}
JOptionPane.showMessageDialog(null, "You shall pay: " + p);
}
else
JOptionPane.showMessageDialog(null, "Quiting...");
Or even better, you can use another object type other than String for the options array, for example a class named Location which will have the name and the price as properties, the toString method of which will return the name.
For the second part, obtain the user's input as a String from a JOptionPane and use Integer.parseInt(...) method on the user's input so as to be able to calculate the change afterwards, like so:
String paymentString = JOptionPane.showInputDialog(null, "Enter payment amount:", "Payment", JOptionPane.QUESTION_MESSAGE);
if (paymentString != null) {
try {
int payment = Integer.parseInt(paymentString);
JOptionPane.showMessageDialog(null, "You chose to pay: " + payment);
//Calculate change here...
}
catch (final NumberFormatException exception) {
JOptionPane.showMessageDialog(null, "The input was invalid (not an 'int').");
}
}
else
JOptionPane.showMessageDialog(null, "Quiting...");
Remember that parseInt will throw a NumberFormatException (which is a RuntimeException) if its input String is not an int, so you will have to check for that using a try-catch block.

Why is reading from file and storing details in classes providing garbage values? [duplicate]

This question already has answers here:
Why does the default Object.toString() include the hashcode?
(3 answers)
Closed 4 years ago.
Following is the code I am using to read from a file and saving details from it in ArrayList of two classes Iphone and Ipad, but apparently something is going wrong with this.
The output I am getting for this code is:
Iphone#28d93b30 and IndexOutOfBoundException for ipads.get(0)
try {
fScanner = new Scanner(new File("apple.txt"));
}
catch (FileNotFoundException e) {
System.out.println(e.toString());
}
ArrayList<Iphone> iphones = new ArrayList<>();
ArrayList<Ipad> ipads = new ArrayList<>();
while(fScanner.hasNextLine()) {
String line = fScanner.nextLine();
Scanner lineScanner = new Scanner(line);
if(lineScanner.next().equals("IPHONE")) {
String model = "IPHONE"+lineScanner.useDelimiter(",").next();
String scrSze = lineScanner.useDelimiter(",").next();
String proc = lineScanner.useDelimiter(",").next();
String simT = lineScanner.useDelimiter(",").next();
String clr = lineScanner.useDelimiter(",").next();
String rom = lineScanner.useDelimiter(",").next();
String is3dtouch = lineScanner.useDelimiter(",").next();
String pric = lineScanner.useDelimiter(",").next();
iphones.add(new Iphone(model,scrSze,proc,simT,clr,rom,is3dtouch,pric));
}
else if(lineScanner.next().equals("IPAD")) {
String model = "IPAD"+lineScanner.useDelimiter(",").next();
String scrSze = lineScanner.useDelimiter(",").next();
String proc = lineScanner.useDelimiter(",").next();
String iswifi = lineScanner.useDelimiter(",").next();
String clr = lineScanner.useDelimiter(",").next();
String memo = lineScanner.useDelimiter(",").next();
String pric = lineScanner.useDelimiter(",").next();
ipads.add(new Ipad(model,scrSze,proc,iswifi,clr,memo,pric));
}
}
System.out.println(iphones.get(2)+"\n");
System.out.println(ipads.get(0)+"\n");
The file is like this:
IPHONE 7, 4.7, A10, GSM, JET BLACK, 32GB, TRUE, 700
IPAD AIR 2, 9.7, A8, TRUE, SILVER, 64GB, 400
IPHONE SE, 4, A9, CDMA, SILVER, 16GB, FALSE, 490
IPAD PRO, 9.7, A9, TRUE, SPACE GREY, 32GB, 650
IPHONE X, 7, A11, LTE, BLACK, 128GB, TRUE, 999
IPAD PRO X, 12, A12, TRUE, SPACE GREY, 256GB, 700
I'd appreciate a good explanation of the above problem.
You get Iphone#28d93b30 because you're printing an Iphone, and you haven't overridden the toString() method in the Iphone class, which means that the default Object.toString() method is being executed.
You get an exception because you're trying to get the first Ipad in the list, and there isn't any in the list. There isn't any because you're calling next() twice (once in the first if condition, and once in the second else if condition, so the token you're comparing with "IPAD" is the second one of the line, and not the first one.

Want to print full Array.asList , Only printing one line

I am developing an Application in Android Studio to that prints how many of each item you can buy with the given amount of currency. It printed flawlessly when run as a Java program in Eclipse but I can not get it to print more than one line in the TextView Box.
I've noticed it will pick the most Expensive item you can afford 1 of and print it alone, leading me to believe it runs through the list and only prints the last one that passes as affordable. I've read about needing to use a StringBuilder and such but have found little information on how to convert my Array.asList over to this. Here is my code.
gCalc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText diamondInput = (EditText) findViewById(R.id.diamondInput);
try {
int diamonds = Integer.parseInt(diamondInput.getText().toString());
List<Gifts> gift = Arrays.asList(new Gifts[]{new Gifts("Gold star", 10), new Gifts("Love Bear", 10), new Gifts("Lillies", 10), new Gifts("Box Of Chocolate", 20), new Gifts("Taco", 20), new Gifts("Thumbs Up", 30), new Gifts("Panda", 40), new Gifts("Beer", 40), new Gifts("Patriot", 52), new Gifts("Eagle", 52), new Gifts("Gold Chain", 80), new Gifts("Roses", 100), new Gifts("Champagne", 100), new Gifts("Snow", 100), new Gifts("Candy", 100), new Gifts("Kiss", 200), new Gifts("Candy Hearts", 250), new Gifts("Peach", 300), new Gifts("EggPlant", 300), new Gifts("Fireworks", 500), new Gifts("GemDrop", 600), new Gifts("Crown", 600), new Gifts("Cupcakes", 700), new Gifts("Heart Balloon", 800), new Gifts("Sports Car", 1000), new Gifts("Smoke Rings", 1000), new Gifts("purple Diamond", 2500), new Gifts("Cupid", 5000), new Gifts("Gold Watch", 5000), new Gifts("Castle", 5000), new Gifts("Yacht", 10000), new Gifts("Jet", 20000)});
double coins = (double) diamonds / 2.5D;
Iterator var5 = gift.iterator();
while(var5.hasNext()) {
Gifts Gifts = (Gifts)var5.next();
int qty = (int)Gifts.getQty(coins);
if(qty > 0) {
result.setText("You can buy " + qty + " " + Gifts.name);
}
}
}
catch (Exception e) {
// friendly error to the user: field is incorrect
}
I need it to print as this EX:
You can buy X amount of Y
You can buy X amount of Y
You can buy X amount of Y
:end
Printing every item that can be bought and it's quantity.
If you look into Android API documentation (https://developer.android.com/reference/android/widget/TextView.html) , this is what it states:
void setText (CharSequence text) - sets the text to be displayed. - this means that each time you call this method, new text overrides the old one.
It seems that you are looking for append() method:
void append(CharSequence text) - convenience method to append the specified text to the TextView's display buffer, upgrading it to EDITABLE if it was not already editable. append() method doesn't override previously set text.
Another way to append text to the previously stored in TextView is to combine these methods:
result.setText(result.getText() + "text that you want to append to the previous one")

Read file into HashMap Java

I'm trying to read lines from file into Arraylist. Here is my writer :
private Map<Integer, ArrayList<Integer>> motPage =
new HashMap<Integer, ArrayList<Integer>>();
private void writer() throws UnsupportedEncodingException, FileNotFoundException, IOException{
try (Writer writer = new BufferedWriter(
new OutputStreamWriter(
new FileOutputStream("/home/kdiri/workJuno/motorRecherche/src/kemal.txt"), "utf-8"))) {
for(Map.Entry<Integer, ArrayList<Integer>> entry : motPage.entrySet()){
writer.write(entry.getKey() + " : " + entry.getValue() + "\n");
}
}
}
And this is an exemple result in the file kemal.txt :
0 : [38, 38, 38, 38, 199, 199, 199, 199, 3004, 3004, 3004, 3004, 23, 23]
My question is how can I read it these lines efficiently into Hashmap again ? Because size of file is about 500MB. Thank you in advance.
As JonSkeet said, you should start with something working. Find below one possible way. The snippet is kept quite verbose to show the principle.
String line = "0 : [38, 38, 38, 38, 199, 199, 199, 199, 3004, 3004, 3004, 3004,
23, 23]";
int firstSpace = line.indexOf(" ");
int leftSquareBracket = line.indexOf("[");
int rightSquareBracket = line.indexOf("]");
String keyString = line.substring(0, firstSpace);
String[] valuesString = line.substring(leftSquareBracket + 1, rightSquareBracket)
.split(", ");
int key = new Integer(keyString);
List<Integer> values = new ArrayList<>(valuesString.length);
for (String value : valuesString) {
values.add(new Integer(value));
}
Map<Integer, List<Integer>> motPage = new HashMap<>();
motPage.put(key, values);
Btw. read ... these lines efficiently into Hashmap depends on your requirements. Efficiency could be for example:
read speed of the huge file
convertion speed String to Integer
small size of the bytecode
less object generation
... there could be other as well
When the snippet does not fulfil your efficiency criteria. Start to tune the part which impacts your criteria.

Android Line Chart x-axis Values

I am having some problem when trying to populate data to line chart using ACHartEngine library in Android. Basically I am trying to create a line chart with x-axis from Jan-Dec no matter the amount of the particular month:
As from the x-axis, there is Jan - Dec although some of the months were with 0 amount. My problem now is I only managed to plot a graph with the months with amount. Let's say currently my database have these records:
So basically my graph will only have Jun, Aug and Sep instead of Jan - Dec.
Here is how I set up my line chart:
private void openTotalMonthlyChart() {
int[] x = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
// Creating an XYSeries for Expenses
XYSeries expensesSeries = new XYSeries("Expenses");
// Adding data to Expense Series
for (int i = 0; i < trans_list.size(); i++) {
expensesSeries.add(x[i], trans_list.get(i).getAmount());
}
// Creating a dataset to hold each series
XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
// Adding Expenses Series to the dataset
dataset.addSeries(expensesSeries);
// Creating XYSeriesRenderer to customize expensesSeries
XYSeriesRenderer expensesRenderer = new XYSeriesRenderer();
expensesRenderer.setColor(Color.rgb(124, 181, 236));
expensesRenderer.setPointStyle(PointStyle.CIRCLE);
expensesRenderer.setFillPoints(true);
expensesRenderer.setLineWidth(2);
expensesRenderer.setDisplayChartValues(true);
// Creating a XYMultipleSeriesRenderer to customize the whole chart
XYMultipleSeriesRenderer multiRenderer = new XYMultipleSeriesRenderer();
multiRenderer.setXLabels(0);
multiRenderer.setChartTitle("Total Monthly Expenses");
multiRenderer.setXTitle("");
multiRenderer.setYTitle("Amount");
multiRenderer.setZoomButtonsVisible(true);
for (int j = 0; j < trans_list.size(); j++) {
multiRenderer.addXTextLabel(j + 1, trans_list.get(j).getDate());
}
multiRenderer.addSeriesRenderer(expensesRenderer);
// Get the component from XML file
RelativeLayout chartContainer = (RelativeLayout) totalMonthlyView
.findViewById(R.id.chart_totalMonthly);
// Creating a Line Chart
chartOverall = ChartFactory.getLineChartView(getActivity(), dataset,
multiRenderer);
// Adding the Line Chart to the RelativeLayout
chartContainer.addView(chartOverall);
}
And my database SQL statement which return the data as the second image above:
public ArrayList<TransactionRecModel> getTotalMonthly() {
try {
String sql = "SELECT SUM(amount) AS total, SUBSTR(date,4,2) AS Month FROM transactionRec WHERE type = 'W' GROUP BY Month";
Cursor mCur = mDb.rawQuery(sql, null);
Log.e(TAG, "Data Grab RECORD Success");
if (mCur.getCount() != 0) {
if (mCur.moveToFirst()) {
do {
TransactionRecModel trm = new TransactionRecModel();
trm.setAmount(mCur.getInt(mCur.getColumnIndex("total")));
trm.setDate(mCur.getString(mCur.getColumnIndex("Month")));
transList.add(trm);
} while (mCur.moveToNext());
}
}
return transList;
} catch (SQLException mSQLException) {
throw mSQLException;
}
}
I wonder is there any way to do this? Thanks in advance and sorry for my poor grammar.
You can use MathHelper.NULL_VALUE for the values that you want to be skipped. See the sensor values chart AChartEngine example to see how to do this.

Categories

Resources