Replace ArrayList Values with new String Values - java

i have a arraylist called arrstatus which has a set of Numeric values stored dynamically.
I have to Replace those Numeric Values with Unique String values.
I tried various methods it doesnt seem to be working
i tries Set method, didnt work,
// int[] flags = new int[arrstatus_old.size()];
int [] c = new int [arrtaskid.size()];
Toast.makeText(MyTask.this, "C:"+c, Toast.LENGTH_LONG).show();
for(int j=1;j<= c.length;j++)
{
if(arrstatus.get(j).equals("1"))
{
arrstatus_old.set(j, "Saved");
}
else if(arrstatus.get(j).equals("2"))
{
arrstatus_old.set(j, "Assigned");
}
else if(arrstatus.get(j).equals("3"))
{
arrstatus_old.set(j, "Accepted");
}
else if(arrstatus.get(j).equals("4"))
{
arrstatus_old.set(j, "Rejected");
}
}
I am not getting the size of the arrastutus, it says 0
and hence no values are getting replaced,
any better idea to replace the value.?

Your ArrayList in which 1 i.e. numbers are stored should store numbers in String format.
Your arrayList should be like ArrayList<String>
ArrayList<String> arrstatus = new ArrayList<String>();
arrstatus.add("1");
arrstatus.add("2");
arrstatus.add("3");
As you are checking in arraylist using equals you'll have add numbers as a String.
if (arrstatus.get(i).equals("1")) {
arrstatus.set(i, "Saved");
}if (arrstatus.get(i).equals("2")) {
arrstatus.set(i, "Assigned");
}if (arrstatus.get(i).equals("3")) {
arrstatus.set(i, "Accepted");
}
and so on...

ArrayList<String> arrstatus = new ArrayList<String>();
arrstatus.add("1");
arrstatus.add("2");
arrstatus.add("3");
arrstatus.add("4");
for(int j=0;j< c.length;j++)
{
if(arrstatus.get(j).equals("1"))
{
arrstatus_old.set(j, "Saved");
}
else if(arrstatus.get(j).equals("2"))
{
arrstatus_old.set(j, "Assigned");
}
else if(arrstatus.get(j).equals("3"))
{
arrstatus_old.set(j, "Accepted");
}
else if(arrstatus.get(j).equals("4"))
{
arrstatus_old.set(j, "Rejected");
}
}

Related

Efficiently Looping through Object array with Multiple Variable types in Java

I'm writing a simple script in Java that is calling another class that holds all my information.
I am holding my information in the called class in Object[] Arrays and I am planning on calling the script to fetch that array.
Right now the function looks like this.
public void tradeShop() {
/*
*Variables must be initialized in order to call shopTrader
*The values are just non-null placeholders and they are
*replaced with the same values in the tradeValues Object array.
*/
String targetName = "NPC Name";
String itemName = "Item Name";
int itemQuantity = 1;
int minCoins = 1;
int minBuy = 1;
boolean stackable = false;
Object[] tradeValues = shop.defaultValues;
for (int i = 0; i < tradeValues.length; i++) {
if(String.class.isInstance(tradeValues[i])) {//String check
if(i==0) { //0 is NPC Name
targetName = (String) tradeValues[i];
} else if (i==1) { //1 is Item Name
itemName = (String) tradeValues[i];
}
} else if (Integer.class.isInstance(tradeValues[i])) { //Int check
if(i==2) { //2 is Item Quantity
itemQuantity = (Integer) tradeValues[i];
} else if (i==3) { //3 is Minimum coins
minCoins = (Integer) tradeValues[i];
} else if (i==4) { //4 is the Minimum Buy limit
minBuy = (Integer) tradeValues[i];
}
} else if (Boolean.class.isInstance(tradeValues[i])) { //Bool check
stackable = (Boolean) tradeValues[i]; //5 is the item Stackable
} else {
//TODO: Implement exception
}
}
//Calls ShopTrader() method shopTrader
ShopTrader trade = new ShopTrader();
trade.shopTrader(targetName, itemName, itemQuantity, minCoins, minBuy, worldHop, stackable);
}
I feel like using a for loop like this is not the correct way for me to be looping through these Objects, I shouldn't have to check i== for each variable.
Also it hinders me from adding overloads to the shopTrader method as I would have to write an entirely new for loop for each overload.
Does anyone have a more elegant solution for getting the variables from this array?
I think that instead of storing all of your information in Object[], you may want to create a new class to act as a data structure i.e.
public class TradeValue {
String targetName;
int itemQuantity;
// etc.
String getTargetName() {
return targetName;
}
String getItemQuantity() {
return itemQuantity;
}
// etc
}
You can then just access the information directly
TradeValue defaultValues = shop.defaultValues;
String targetName = defaultValues.getTargetName();
int itemQuantity = defaultValues. getItemQuantity();
...

How to Search ArrayList For Integer and Remove It If It Exists In Java

In my program I have to to be able to remove items from an arrayList. The user inputs a number and then if it exists in the arrayList it is removed. When I press the remove button the program would crash if it weren't for my try and catch statements, does anyone know what I should change for the removal to work properly?
public class SumElements extends javax.swing.JFrame {
ArrayList <Integer> values = new ArrayList();
...
private void removeButtonActionPerformed(java.awt.event.ActionEvent evt) {
try {
//declare variables
int searchVal = Integer.parseInt(valueInput.getText());
//search array for inputed value
int index = Collections.binarySearch(values, searchVal);
if (index >= 0){
//clear outputArea
outputArea.setText(null);
outputLabel.setText(null);
//remove from array
values.remove(valueInput.getText());
//display updated values
Collections.sort(values);
for (int i = 0; i < values.size(); i++)
{
outputArea.setText(outputArea.getText() + values.get(i) + "\n");
}
//clear input
valueInput.setText(null);
}
else {
outputLabel.setText("Data not found. Please try again.");
}
}
//set default
catch (NumberFormatException a)
{
outputLabel.setText("Please input a valid number.");
}
}

How do I make this JOptionPane load this large arrayList vertically with a JScrollBar

How do I make this JOptionPane List up to 100 items with a JScrollBar, I know it can be done. I'm asking for a little bit of guidance.
Here's my code
public static ArrayList<String> Matches = new ArrayList<String>();
private void itemSearch(String name) {
try{
String string;
BufferedReader reader = new BufferedReader(new FileReader("items.txt"));
while((string = reader.readLine()) != null) {
String[] args = string.split(" ");
for(int i = 0; i <= 19461; i++) {
if(args[i].contains(name)) {
itemID = Integer.parseInt(args[i-1]);
itemSearched = name;
Matches.add("Name: "+name+", ID: "+itemID+"");
System.out.println("Item name:"+args[i]+" Item ID:"+itemID+"");
}
}
if(Matches.size()<=1) {
continue;
} else {
JOptionPane.showMessageDialog(null, Matches);
}
AMItemDatabaseLabel3.setText(""+itemID+"");
}
} catch(Exception r) {
r.printStackTrace();
}
}
Check out the section from the Swing tutorial on Getting Users Input.
If the number of "possibilities" is greater than 20, then a JList will be used to display the values.
So you need to use an Array (not an ArrayList) containing your items. So based on your current code you would need to copy the items from the ArrayList to the Array.

App is crashing when I convert string to int

I use two dimensional array and suppose I want to convert a string to int in a specific element
like that arr[0][1]="12";. I am using this
int id=0; String[][] description=new String[obj.length][];
String[] temp;
for(int i=0; i<obj.length; i++) {
da[i]=obj[i].toString(); temp=da[i].split(",");
description[i]=new String[temp.length];
for(int j=0; j<temp.length; j++) {
// id=new String[temp.length];
description[i][j]=temp[j];
if(j==0) {
try {
id=Integer.parseInt(description[i][j]);
}
catch(NumberFormatException nfe) { // Log exception. }
//id=Integer.parseInt(description[i][j].toString());
Toast.makeText(getApplicationContext(),id, Toast.LENGTH_SHORT).show();
}
}
But it gives null pointer exception.
check if its not null then cast to integer:
try {
if(description[i][j]!=null && description[i][j].length()>0){
id=Integer.parseInt(description[i][j]);
Toast.makeText(getApplicationContext(),id, Toast.LENGTH_SHORT).show();
}
}
instead of
try {
id=Integer.parseInt(description[i][j]);
}
i hope its work but description[i][j] must returns string.
if id getting value then print toast.otherwise no toast print..

How to create an array in recursive function in java

I have a recursive method that prints out the values in command line. I need to create a temp array with the result an display it using Swing. how do I create the array and store the values each time it loops ?
static void listSnapshots(VirtualMachine vm)
{
if(vm == null)
{
JOptionPane.showMessageDialog(null, "Please make sure you selected existing vm");
return;
}
VirtualMachineSnapshotInfo snapInfo = vm.getSnapshot();
VirtualMachineSnapshotTree[] snapTree = snapInfo.getRootSnapshotList();
printSnapshots(snapTree);
}
static void printSnapshots(VirtualMachineSnapshotTree[] snapTree)
{
VirtualMachineSnapshotTree node;
VirtualMachineSnapshotTree[] childTree;
for(int i=0; snapTree!=null && i < snapTree.length; i++)
{
node = snapTree[i];
System.out.println("Snapshot name: " + node.getName());
JOptionPane.showMessageDialog(null, "Snapshot name: " + node.getName());
childTree = node.getChildSnapshotList();
if(childTree != null)
{
printSnapshots(childTree);
}
}//end of for
so instead of JOptionPane I have only onew window with the list of names and can reuse later.
A general tactic for building something recursively is to use a Collecting Parameter.
This can be applied in your case by:
static List<String> listSnapshotNames(VirtualMachineSnapshotTree[] snapTree) {
ArrayList<String> result = new ArrayList<String>();
collectSnapshots(snapTree, result);
return result;
}
static void collectSnapshots(VirtualMachineSnapshotTree[] snapTree, List<String> names)
{
VirtualMachineSnapshotTree node;
VirtualMachineSnapshotTree[] childTree;
for(int i=0; snapTree!=null && i < snapTree.length; i++)
{
node = snapTree[i];
names.add(node.getName());
childTree = node.getChildSnapshotList();
if(childTree != null)
{
collectSnapshots(childTree, names);
}
}//end of for
}
Of course, if you really want it in an array, you can convert it afterwards:
static String[] getSnapshotNames(VirtualMachineSnapshotTree[] snapTree) {
List<String> result = listSnapshotNames(snapTree);
return result.toArray(new String[0]);
}
With an unknown size, arrays are painful, so a List works better for this.

Categories