Как бы я использовал hashMap? - PullRequest
0 голосов
/ 19 ноября 2018

Как hashmap применяется к этому конкретному коду, когда элемент может быть чем-то в периодической таблице, если он из другого источника вне кода.

public class element {
public static void main(String[] args)throws IOException{
    Scanner kbd = new Scanner(System.in);
    File file = new File("elements.txt");
    Scanner read = new Scanner(file);
    System.out.println("Enter a chemical compound: ");
    String compound = kbd.nextLine();
    compound = compound+" ";
    System.out.println("Chemical compound of "+compound);

    for (int x=0; x<compound.length();x++){
        if (compound.charAt(x)=='H'){
            String Hvalue = String.valueOf(compound.charAt(x+1));
            if (Character.isLetter(compound.charAt(x+1))) {
                Hvalue = String.valueOf(1);
            } else if (Character.isWhitespace(compound.charAt(x+1))){
                Hvalue = String.valueOf(1);
            }
            System.out.println(Hvalue+" part/s Hydrogen");
        } else if (compound.charAt(x)=='C'){
            String Cvalue = String.valueOf(compound.charAt(x+1));
            if (Character.isLetter(compound.charAt(x+1))) {
                Cvalue = String.valueOf(1);
            } else if (Character.isWhitespace(compound.charAt(x+1))){
                Cvalue = String.valueOf(1);
            }
            System.out.println(Cvalue+" part/s Carbon");
        } 
            } else if (Character.isWhitespace(compound.charAt(x+1))){
                Ovalue = String.valueOf(1);
            }
            System.out.println(Ovalue+" part/s Oxygen");
        }
    }

}

}

1 Ответ

0 голосов
/ 19 ноября 2018

Предполагая, что формат файла останется постоянным, ниже должно работать (на основе JDK 8):

import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class Element {
    public static void main(String[] args) throws IOException {
        Scanner kbd = new Scanner(System.in);
        Map<String, Map<String, Double>> elementsMap = new HashMap<>();
        File file = new File("elements.txt");
        Scanner read = new Scanner(file);
        while (read.hasNext()) {
            elementsMap.putIfAbsent(read.next(), Collections.singletonMap(read.next(), Double.valueOf(read.next())));
        }


        System.out.println("Enter a chemical compound: ");
        String compound = kbd.nextLine();
        compound = compound + " ";
        System.out.println("Chemical compound of " + compound);

        double compoundWeight = 0.0;
        for (int x = 0; x < compound.length(); x++) {

            String elementKey = String.valueOf(compound.charAt(x));
            if (elementsMap.containsKey(elementKey)) {
                Map<String, Double> element = elementsMap.get(elementKey);
                int noOfElements = 0;

                while (String.valueOf(compound.charAt(x + 1)).matches("([1-9])")) {
                    noOfElements = ((noOfElements * 10) + Integer.parseInt(String.valueOf(compound.charAt(x + 1))));
                    x++;
                }

                noOfElements = noOfElements > 0 ? noOfElements : 1;

                System.out.println(noOfElements + " part/s " + element.keySet().iterator().next());
                compoundWeight += (element.values().iterator().next() * noOfElements);

            }
        }

        System.out.println("Atomic mass of " + compound + " is : " + compoundWeight);

    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...