How to check an input against many different poten

2019-08-24 14:33发布

Currently I'm trying to make a program that will ask for an input of an element from the periodic table, and then output some information about that element. My original idea was to create a method for it and then just call the method a bunch of times with the different information for each element, but I now see why that won't work since, if I have the method for Lithium first, it will only accept an input of Lithium. How could I accomplish this without just having a ton of nearly-identical if statements? I'm very new to Java, so a simple explanation as to how and why would be greatly appreciated.

import java.util.Scanner;
public class PeriodicTable {

    public static void askForElement(String symbol, String name, String group, Float weight) {
        do {
            Scanner reader = new Scanner(System.in);
            String input = reader.nextLine();
            if(input.trim().equalsIgnoreCase(symbol) || input.trim().equalsIgnoreCase(name)) {
                System.out.println("Element: " + name + " (" + symbol + ")" + "\nGroup: " + group + "\nAtomic Weight: " + weight);
                break;
            } else {
                System.out.println("Please input a valid symbol or name of an element.");
                continue;
            }
        } while (true);
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
            System.out.println("Please input the name or symbol of an element in the periodic table. ");
            askForElement("Li", "Lithium", "Alkali Metals", (float) 6.941);
            askForElement("Fe", "Iron", "Transition Metals", (float) 55.933);
    }

}

0条回答
登录 后发表回答