用户输入后如何存储选择的值?目标是在用户完成操作后将array2作为带有所有选定处理的收据打印出来

问题描述

String[][] array = {{"Checkup","60"},{"Repairing tooth","150"},{"Cleaning","30"}};  // Menu of treatments

String[] array2 = new String [10];  // New array that saves up to 10 elements(treatments)

int cost = 0;  
int treatment = 0;

Scanner input = new Scanner(system.in);

System.out.println("Control" + " " + "1");
System.out.println("Repair tooth:" + " " + "2");
System.out.println("Cleaning:" + " " + "3");

int n = array.length;
for (int i=0; i<n; i++) {
    for (int j=0; i<n ; j++) {
        System.out.println();
        treatment = input.nextInt();
        if (treatment==1) {
            cost += Integer.parseInt(array[i][1]);
            System.out.print("Total cost so far: " + cost);
        }
        if (treatment==2) {
            cost += Integer.parseInt(array[i+1][1]);
            System.out.print("Total cost so far: " + cost);
        }
        if (treatment==3) {
            cost += Integer.parseInt(array[i+2][1]);
            System.out.print("Total cost so far: " + cost);
        }
    }
}

如何从这里继续前进?我认为必须将输入存储在新数组中,并在10次处理后退出循环,或者向用户添加一个选项以在完成后打印出收据。

收据需要打印所有选择的治疗以及每个治疗的费用。我还需要添加一个变量,为所有选择的治疗方法总计。

解决方法

这是您要尝试执行的操作,因为处理是固定的,所以您可以将它们索引为0、1、2。您可以做的一件事是制作一个哈希图,在其中可以存储处理名称和用户每次输入时的成本(String,int)。 看下面的代码

import java.util.*;
import java.util.HashMap;

public class treatment {

public static void main(String []args) {
    
    String[][] array = {{"Checkup","60"},{"Repairing tooth","150"},{"Cleaning","30"}};  // Menu of treatments

     // New array that saves up to 10 elements(treatments)
    HashMap<String,Integer> treat = new HashMap<String,Integer>();


    int cost = 0;  
    int treatment = 0;

    Scanner input = new Scanner(System.in);



    int n = array.length;
    int i =0;
    char c = '\0';

    do {
        System.out.println("\n\nControl" + " " + "1");
        System.out.println("Repair tooth:" + " " + "2");
        System.out.println("Cleaning:" + " " + "3");
        System.out.println("Exit: " + "-1");
        System.out.println();
        System.out.print("Enter treatment value (1,2,3): ");
        treatment = input.nextInt();

        if (treatment==1){ 
            i = 0;
            cost += Integer.parseInt(array[0][1]);
            System.out.println("\nTotal cost so far: " + cost);

        }
        else if (treatment==2) {
            i = 1;
            cost += Integer.parseInt(array[1][1]);
            System.out.println("\nTotal cost so far: " + cost);
        }
        else if (treatment==3) {
            i = 2;
            cost += Integer.parseInt(array[2][1]);
            System.out.println("\nTotal cost so far: " + cost);
        }
        treat.put(array[i][0],cost);

    } while (treatment != -1);

    System.out.println("Total COst is : " + cost);
    System.out.println("The treatements you opt for are:\n");
    System.out.println(treat);
    System.out.println("\n");
    
   }
}