Jak sprawić, by program sprawdzał wystąpienie listu w java?

Oct 08 2020

Tworzę kasę fiskalną, w której muszę używać skanera i mogę mieć tylko 5 kwot wejściowych. Musi również zawierać hst, a to oznacza tylko „h” przed lub przed kwotą. Moje pytanie brzmi: w jaki sposób program rozpoznałby, że wstawiłem „h” przed lub po kwocie? Wydaje się, że jest to zrobione tylko przy użyciu zmiennej łańcuchowej, więc jak mam to osiągnąć? Muszę przechowywać dane wejściowe w tablicy, więc mam to do pracy.

Mój kod:

 // Import scanner class
 import java.util.Scanner;

// Create class and method
class Main {
public static void main(String[] args) {

// Declare the scanner object and create scanner variables
Scanner inp = new Scanner(System.in);
System.out.println("Press any key to start");
String key = inp.nextLine();
System.out.println("\nEnter the amount of each item");
System.out.println("Upto 5 inputs are allowed!\n");

// Define an array double variable, set the limit to 5 inputs
double[] numbers = new double[5];

// Create a for loop to input any numbers 5 times
for (int i = 0; i < numbers.length; i++){

    // Add a scanner input to let the user type out the values
    numbers[i] = inp.nextDouble();
    }
  }
} 

Odpowiedzi

1 Hades Oct 08 2020 at 16:01

poniższy kod prosi użytkownika o wprowadzenie danych 5 razy, a w tablicy będą znajdować się tylko prawidłowe wartości, wartości prawidłowe to wartości z „h” na początku lub na końcu i powinny wystąpić tylko raz. tj. „h” zarówno na końcu, jak i na początku lub więcej niż raz jest nieważne.

public static void main(String[] args) throws ParseException {
    int counter = 1;
    Double[] result = new Double[5];
    
    int index = 0;
    while(counter <= 5) {           
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter an Amount ");
        String value = scanner.nextLine();      
        int indexOfH = value.indexOf("h");
        int lastIndexOfH = value.lastIndexOf("h");
        boolean containsHatstartsOrEnd = indexOfH == 0 || indexOfH == (value.length()-1);
    
        if(containsHatstartsOrEnd && indexOfH==lastIndexOfH){ //Validate h at begins or end and should contains only once
            result[index] = Double.parseDouble(value.replace("h", ""));
            index++;
        }
        counter++;
    }
    System.out.println("Printing Valid values");

    for(int i=0; i< result.length; i++) {
        if(result[i]!=null) {
            System.out.println(result[i]);
        }
    }
}

wejście i wynik

Enter an Amount 13.45h
Enter an Amount 55h.65
Enter an Amount 32h.33h
Enter an Amount h100.23
Enter an Amount h20
Printing Valid values
13.45
100.23
20.0