简体   繁体   中英

How do I avoid using if statements with a large amount of variables in java

I am attempting to create a program that asks for the user to input the name of 6 items out of a large list. It then totals up all the attributes of said items and displays the total of all the attributes as well as the cost. The only way I can see doing this would require a huge amount of if and else if statements along with a for loop. With the amount of items I need to use it would be atleast 1000 lines long of if and else statements and that would take a whole lot of time to write out.

Here is a sample of my code

import java.util.Scanner;
public class MyProgram
{
public static void main(String[] args)
  {
    Scanner one = new Scanner(System.in);
    System.out.print("Champion: ");
    String champion = one.next();
    System.out.print("Item 1: ");
    String item1 = one.next();
    System.out.print("Item 2: ");
    String item2 = one.next();
    System.out.print("Item 3: ");
    String item3 = one.next();
    System.out.print("Item 4: ");
    String item4 = one.next();
    System.out.print("Item 5: ");
    String item5 = one.next();
    System.out.print("Item 6: ");
    String item6 = one.next();
    int totalhealth = 0;
    int totalad = 0;
    int totalap = 0;
    int totalarmor = 0;
    int totalmr = 0;
    int totalcdr = 0;
    int totalmana = 0;
    int totalcstr= 0;
    int totalls = 0;
    int totalatcksp = 0;
    int totalcost = 0;
    for(int i = 0; i < 6; i++)
    {
        int itemhealth = 0;
        int itemad = 0;
        int itemap = 0;
        int itemarmor = 0;
        int itemmr = 0;
        int itemcdr = 0;
        int itemmana = 0;
        int itemcstr = 0;
        int itemls = 0;
        int itematcksp = 0;
        int itemcost = 0;
        if(i == 0)
        {
            if(item1.equals("abyssal mask"))
        {
            itemhealth = 350;
            itemmana = 300;
            itemmr = 55;
            itemcdr = 10;
            itemcost = 2900;
        }
        else if (item1.equals("adaptive helm"))
        {
            itemhealth = 350;
            itemmr = 55;
            itemcdr = 10;
            itemcost = 2800;
        }
        else if (item1.equals("aegis of the legion"))
        {
            itemarmor = 30;
            itemmr = 30;
            itemcost = 1100;
        }
        else if (item1.equals("aether wisp"))
        {
            itemap = 30;
            itemcost = 850;
        }
        else if (item1.equals("amplifying tome"))
        {
         itemap = 20;
         itemcost = 435;
        }
        else if (item1.equals("ancient coin"))
        {
            itemcdr = 5;
            itemcost = 350;
        }
        else if (item1.equals("archangel's staff"))
        {
            itemap = 80;
            itemmana = 250;
            itemcost = 3100;
        }
        else if (item1.equals("ardent censer"))
        {
            itemap = 60;
            itemcdr = 10;
            itemcost = 2300;
        }
        else if (item1.equals("athene's unholy grail"))
        {
            itemap= 30;
            itemmr = 30;
            itemcdr = 10;
            itemcost = 2100;
        }
        else if (item1.equals("b.f.sword"))
        {
            itemad = 40;
            itemcost = 1300;
        }
        else if (item1.equals("bami's cinder"))
        {
            itemhealth = 200;
            itemcost = 900;
        }
    }
        if(i == 1)
    {
        if(item2.equals("abyssal mask"))
        {
            itemhealth = 350;
            itemmana = 300;
            itemmr = 55;
            itemcdr = 10;
            itemcost = 2900;
        }
        else if (item2.equals("adaptive helm"))
        {
            itemhealth = 350;
            itemmr = 55;
            itemcdr = 10;
            itemcost = 2800;
        }
        else if (item2.equals("aegis of the legion"))
        {
            itemarmor = 30;
            itemmr = 30;
            itemcost = 1100;
        }
        else if (item2.equals("aether wisp"))
        {
            itemap = 30;
            itemcost = 850;
        }
        else if (item2.equals("amplifying tome"))
        {
         itemap = 20;
         itemcost = 435;
        }
        else if (item2.equals("ancient coin"))
        {
            itemcdr = 5;
            itemcost = 350;
        }
        else if (item2.equals("archangel's staff"))
        {
            itemap = 80;
            itemmana = 250;
            itemcost = 3100;
        }
        else if (item2.equals("ardent censer"))
        {
            itemap = 60;
            itemcdr = 10;
            itemcost = 2300;
        }
        else if (item2.equals("athene's unholy grail"))
        {
            itemap= 30;
            itemmr = 30;
            itemcdr = 10;
            itemcost = 2100;
        }
        else if (item2.equals("b.f.sword"))
        {
            itemad = 40;
            itemcost = 1300;
        }
        else if (item2.equals("bami's cinder"))
        {
            itemhealth = 200;
            itemcost = 900;
        }

    }
    if(i == 2)
    {
        if(item3.equals("abyssal mask"))
        {
            itemhealth = 350;
            itemmana = 300;
            itemmr = 55;
            itemcdr = 10;
            itemcost = 2900;
        }
        else if (item3.equals("adaptive helm"))
        {
            itemhealth = 350;
            itemmr = 55;
            itemcdr = 10;
            itemcost = 2800;
        }
        else if (item3.equals("aegis of the legion"))
        {
            itemarmor = 30;
            itemmr = 30;
            itemcost = 1100;
        }
        else if (item3.equals("aether wisp"))
        {
            itemap = 30;
            itemcost = 850;
        }
        else if (item3.equals("amplifying tome"))
        {
         itemap = 20;
         itemcost = 435;
        }
        else if (item3.equals("ancient coin"))
        {
            itemcdr = 5;
            itemcost = 350;
        }
        else if (item3.equals("archangel's staff"))
        {
            itemap = 80;
            itemmana = 250;
            itemcost = 3100;
        }
        else if (item3.equals("ardent censer"))
        {
            itemap = 60;
            itemcdr = 10;
            itemcost = 2300;
        }
        else if (item3.equals("athene's unholy grail"))
        {
            itemap= 30;
            itemmr = 30;
            itemcdr = 10;
            itemcost = 2100;
        }
        else if (item3.equals("b.f.sword"))
        {
            itemad = 40;
            itemcost = 1300;
        }
        else if (item3.equals("bami's cinder"))
        {
            itemhealth = 200;
            itemcost = 900;
        }
    }
        if(i == 3)
    {
        if(item4.equals("abyssal mask"))
        {
            itemhealth = 350;
            itemmana = 300;
            itemmr = 55;
            itemcdr = 10;
            itemcost = 2900;
        }
        else if (item4.equals("adaptive helm"))
        {
            itemhealth = 350;
            itemmr = 55;
            itemcdr = 10;
            itemcost = 2800;
        }
        else if (item4.equals("aegis of the legion"))
        {
            itemarmor = 30;
            itemmr = 30;
            itemcost = 1100;
        }
        else if (item4.equals("aether wisp"))
        {
            itemap = 30;
            itemcost = 850;
        }
        else if (item4.equals("amplifying tome"))
        {
         itemap = 20;
         itemcost = 435;
        }
        else if (item4.equals("ancient coin"))
        {
            itemcdr = 5;
            itemcost = 350;
        }
        else if (item4.equals("archangel's staff"))
        {
            itemap = 80;
            itemmana = 250;
            itemcost = 3100;
        }
        else if (item4.equals("ardent censer"))
        {
            itemap = 60;
            itemcdr = 10;
            itemcost = 2300;
        }
        else if (item4.equals("athene's unholy grail"))
        {
            itemap= 30;
            itemmr = 30;
            itemcdr = 10;
            itemcost = 2100;
        }
        else if (item4.equals("b.f.sword"))
        {
            itemad = 40;
            itemcost = 1300;
        }
        else if (item4.equals("bami's cinder"))
        {
            itemhealth = 200;
            itemcost = 900;
        }
    }
        if(i == 4)
    {
        if(item5.equals("abyssal mask"))
        {
            itemhealth = 350;
            itemmana = 300;
            itemmr = 55;
            itemcdr = 10;
            itemcost = 2900;
        }
        else if (item5.equals("adaptive helm"))
        {
            itemhealth = 350;
            itemmr = 55;
            itemcdr = 10;
            itemcost = 2800;
        }
        else if (item5.equals("aegis of the legion"))
        {
            itemarmor = 30;
            itemmr = 30;
            itemcost = 1100;
        }
        else if (item5.equals("aether wisp"))
        {
            itemap = 30;
            itemcost = 850;
        }
        else if (item5.equals("amplifying tome"))
        {
         itemap = 20;
         itemcost = 435;
        }
        else if (item5.equals("ancient coin"))
        {
            itemcdr = 5;
            itemcost = 350;
        }
        else if (item5.equals("archangel's staff"))
        {
            itemap = 80;
            itemmana = 250;
            itemcost = 3100;
        }
        else if (item5.equals("ardent censer"))
        {
            itemap = 60;
            itemcdr = 10;
            itemcost = 2300;
        }
        else if (item5.equals("athene's unholy grail"))
        {
            itemap= 30;
            itemmr = 30;
            itemcdr = 10;
            itemcost = 2100;
        }
        else if (item5.equals("b.f.sword"))
        {
            itemad = 40;
            itemcost = 1300;
        }
        else if (item5.equals("bami's cinder"))
        {
            itemhealth = 200;
            itemcost = 900;
        }
    }
        if(i == 5)
    {
        if(item6.equals("abyssal mask"))
        {
            itemhealth = 350;
            itemmana = 300;
            itemmr = 55;
            itemcdr = 10;
            itemcost = 2900;
        }
        else if (item6.equals("adaptive helm"))
        {
            itemhealth = 350;
            itemmr = 55;
            itemcdr = 10;
            itemcost = 2800;
        }
        else if (item6.equals("aegis of the legion"))
        {
            itemarmor = 30;
            itemmr = 30;
            itemcost = 1100;
        }
        else if (item6.equals("aether wisp"))
        {
            itemap = 30;
            itemcost = 850;
        }
        else if (item6.equals("amplifying tome"))
        {
         itemap = 20;
         itemcost = 435;
        }
        else if (item6.equals("ancient coin"))
        {
            itemcdr = 5;
            itemcost = 350;
        }
        else if (item6.equals("archangel's staff"))
        {
            itemap = 80;
            itemmana = 250;
            itemcost = 3100;
        }
        else if (item6.equals("ardent censer"))
        {
            itemap = 60;
            itemcdr = 10;
            itemcost = 2300;
        }
        else if (item6.equals("athene's unholy grail"))
        {
            itemap= 30;
            itemmr = 30;
            itemcdr = 10;
            itemcost = 2100;
        }
        else if (item6.equals("b.f.sword"))
        {
            itemad = 40;
            itemcost = 1300;
        }
        else if (item6.equals("bami's cinder"))
        {
            itemhealth = 200;
            itemcost = 900;
        }
    }
System.out.println("Champion: " + champion);
System.out.println("Total health: " + totalhealth);
System.out.println("Total AD: " + totalad);
System.out.println("Total AP: " + totalap);
System.out.println("Total armor: " + totalarmor);
System.out.println("Total magic resist" + totalmr);
System.out.println("Total CDR: %" + totalcdr);
System.out.println("Total mana: " + totalmana);
System.out.println("Total Critical Strike Chance: " + totalcstr);
System.out.println("Total Life Steal: %" + totalls);
System.out.println("Total Attack Speed: " + totalatcksp);
System.out.println("Total Cost: " + totalcost + "g");


    }
  }
}

I am a highschool student on my first year of CS. This may have a simple answer that I am unaware of so I am open to all answers, even the most obvious.

Re-think the problem.

The task the program needs to do is calculate a total cost for a user-defined set of items.

The code for calculating a sum of X items is identical. The item names and their costs are not.

So the data can be defined outside the logic of calculation and queried according to user input.

There are many ways to do this, and Stack Overflow is not a place to do your homework for you.

In general terms, use a collection or self-defined class to store the data and write code to look up an item's data based on its name. Java has multiple native collections that fit the use case. That should get you started.

Create a class that has attributes like itemap, itemcdr, itemcost (and the rest). Create get() and set() methods for each attribute. When instantiating the class, pass in values for those variables.

I'm a Garen player myself, so I recognized these instantly :)

I'm going to put aside the fact that you never actually use the variables you set in the conditions.

As far as I can see, you're always setting the same values for each of the strings. For example:

    if(i == 0)
    {
        if(item1.equals("abyssal mask"))
    {
        itemhealth = 350;
        itemmana = 300;
        itemmr = 55;
        itemcdr = 10;
        itemcost = 2900;
    }
    // ...

    if(i == 1)
    {
        if(item2.equals("abyssal mask"))
    {
        itemhealth = 350;
        itemmana = 300;
        itemmr = 55;
        itemcdr = 10;
        itemcost = 2900;
    }

The only difference here is the i , and the name of the variable that you are comparing to abyssal mask .

If that's the case, you can reuse the code for i == 0 by using an array . Assign the values you are currently assigning to an array:

String[] items = new String[6];
for (int i = 0; i < items.length; ++i) {
  System.out.printf("Item %d: %n", i + 1);
  items[i] = one.next();
}

Now, the code above can become:

if (items[i].equals("abyssal mask")) {
  itemhealth = 350;
  itemmana = 300;
  // etc.
}

without the check for if (i == 0) , if (i == 1) etc, because it's picking the right value to compare against via the items[i] array access.


This will only get you so far in the shrinking of your code. To go better, you'll need some sort of custom object.

Before getting to how to define that custom object, it's worth showing how you can use it:

// Initialize once.
Map<String, CustomObject> map = /* initialize somehow */;

// In your loop:
CustomObject obj = map.get(item[i]);
// Then use the values in obj somehow:
System.out.printf("Item %s has health %d%n", item[i], obj.health);
System.out.printf("Item %s has mana %d%n", item[i], obj.mana);

So, you can store items in a map - a lookup between some key and a corresponding value - in order to hide the conditions between them.

Now, you can declare this custom object simply like this:

class CustomObject {
  int health;
  int mana;
  int mr;
  // etc.
}

A bad (*) (but easy) way to declare instances of this is like this:

CustomObject abyssalMask = new CustomObject{{
  health = 350;
  mana = 300;
  mr = 55;
  // etc.
}};
CustomObject adaptiveHelm = new CustomObject{{
  health = 350;
  mr = 55;
  cdr = 10;
  // etc.
}};

Now you can put these into a Map :

Map<String, CustomObject> map = new HashMap<>();
map.put("abyssal mask", abyssalMask);
map.put("adaptive helm", adaptiveHelm);
// ...

And then you use this in your program, as I have shown above.


This is an awful , awful practice. It's called double-brace initialization , and has a lot of pitfalls.

A much better way of doing this would be to use a language with named parameters, like Python, where you could simply invoke the constructor with the parameters you want:

abyMask = CustomObject(health=350, mana=300, mr=55)
adapHellm = CustomObject(health=99, cdr=50)

But if you're stuck in Java, the Builder pattern is about as good as you can do:

class CustomObject {
  final int health;
  final int mana;

  private CustomObject(Builder b) {
    this.health = b.health;
    this.mana = b.mana;
  }

  static Builder builder() { return new Builder(); }

  static class Builder {
    int health;
    int mana;

    CustomObject build() { return new CustomObject(this); }

    Builder setHealth(int health) { this.health = health; return this; }
    Builder setMana(int mana) { this.mana = mana; return this; }
  }
}

Now you can create instances of this like:

CustomObject abyssalMask = CustomObject.builder().setHealth(350).setMana(300).build();

and then put them into the map like before.

I broke down the logic into something much more simple. Using an arraylist of strings you can cut down the number of if/else checks significantly.

public static void main(String[] args){
ArrayList<String> allItems = new ArrayList<>();
int numberOfItems = 6;
Scanner one = new Scanner(System.in);

System.out.println("Champion: ");
String champion = one.nextLine();

for(int i = 0; i < numberOfItems; i++)
{
    System.out.println("Item " + (i + 1) + ": ");
    String item = one.nextLine();
    System.out.println("Adding item: " + item + " to index " + i + " of the list");
    allItems.add(item);
}
int totalhealth = 0;
int totalad = 0;
int totalap = 0;
int totalarmor = 0;
int totalmr = 0;
int totalcdr = 0;
int totalmana = 0;
int totalcstr= 0;
int totalls = 0;
int totalatcksp = 0;
int totalcost = 0;

for(int i = 0; i < allItems.size(); i++)
{   
    if(allItems.get(i).equals("abyssal mask"))
    {
        totalhealth += 350;
        totalmana += 300;
        totalmr += 55;
        totalcdr += 10;
        totalcost += 2900;
    }
    else if(allItems.get(i).equals("adaptive helm"))
    {
        totalhealth += 350;
        totalmr += 55;
        totalcdr += 10;
        totalcost += 2800;
    }
    //... for all the items using the += for total values
    else {
        System.out.println("Not a valid item: " + allItems.get(i));
        allItems.remove(i);
        i--;
    }
}

System.out.println("Champion: " + champion);
System.out.println("Total health: " + totalhealth);
System.out.println("Total AD: " + totalad);
System.out.println("Total AP: " + totalap);
System.out.println("Total armor: " + totalarmor);
System.out.println("Total magic resist " + totalmr);
System.out.println("Total CDR: %" + totalcdr);
System.out.println("Total mana: " + totalmana);
System.out.println("Total Critical Strike Chance: " + totalcstr);
System.out.println("Total Life Steal: %" + totalls);
System.out.println("Total Attack Speed: " + totalatcksp);
System.out.println("Total Cost: " + totalcost + "g");
}

Output

Champion: 
alexlchico
Item 1: 
abyssal mask
Adding item: abyssal mask to index 0 of the list
Item 2: 
adaptive helm
Adding item: adaptive helm to index 1 of the list
Item 3: 
pikachu
Adding item: pikachu to index 2 of the list
Item 4: 
adaptive helm
Adding item: adaptive helm to index 3 of the list
Item 5: 
abyssal mask
Adding item: abyssal mask to index 4 of the list
Item 6: 
ball of lint
Adding item: ball of lint to index 5 of the list
Not a valid item: pikachu
Not a valid item: ball of lint

Champion: alexlchico
Total health: 1400
Total AD: 0
Total AP: 0
Total armor: 0
Total magic resist 220
Total CDR: %40
Total mana: 600
Total Critical Strike Chance: 0
Total Life Steal: %0
Total Attack Speed: 0
Total Cost: 11400g

All you have left to do is use the same logic i used for the abyssal mask and adaptive helm for the other items you want and using the total values with += you can add to your existing calculated totals of the previous items. That way when the program finishes looping the items your champion has, you will have the totals calculated and the final print will reflect what your champion has with all the items you gave him. Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM