É necessário transformar char em minúsculas e substituí-lo em Java [duplicado]

Oct 09 2020

Portanto, preciso fazer uma caixa registradora básica que aceite 5 itens em uma matriz com um preço neles. No entanto, alguns itens terão o HST (imposto) incluso. Para saber quais itens têm imposto e quais não. O usuário pressionará h ou H antes ou depois de inserir o valor em dólares. A maior parte do programa está funcionando, mas não consigo fazer meu código reconhecer o H maiúsculo para inserir o imposto nele. Aqui está o meu código, Thx com antecedência para qualquer informação:

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

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

// Create scanner object and set 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");

// Initialize counter and index variables to use it in the while loop
int counter = 0;
int index = 0;

// Create a double array variable, and set the limit to 5
double[] numbers = new double[5];

// Create a boolean variable to use it in the while loop
boolean go = true;

while(go) {           
    String value = inp.nextLine();      
    value.toLowerCase();
    // Set the index value to "h" or "H"
    int indexOfh = value.indexOf('h');
    
    boolean containsh = indexOfh == 0 || indexOfh == (value.length()-1);
    

    if(containsh){ //Validate h at beginning or end
        numbers[index] = Double.parseDouble(value.replace("h", ""));
        index++;
          System.out.println("HST will be taken account for this value");
    }
    counter++;
    if (counter == 5){
      go = false;
    }
}
System.out.println("HST Values:");

for(int i=0; i< numbers.length; i++) {
        System.out.println(numbers[i]);
}
}
}

Respostas

KevinSeymour Oct 09 2020 at 16:45

Eu removeria indexOfh completamente: você pode ORum monte de declarações juntas. Isso é seguro porque >=é avaliado antes || .

// Set the index value to "h" or "H"
boolean containsh = value.indexOf('h') >= 0
    || value.indexOf('H') >= 0;

Além disso, você pode tornar seus requisitos um pouco mais rígidos usando startsWithe endsWithignorando um 'H' ou 'h' no meio.

// Set the index value to "h" or "H"
boolean containsh = value.startsWith("h")
    || value.startsWith("H") || value.endsWith("h")
    || value.endsWith("H");

Além disso, você tem um vazamento de recursos porque nunca fecha seu Scanner: você pode usar try-with-resources para que o Java gerencie isso para você. Isso, junto com algumas outras simplificações, produz uma nova versão como esta.

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

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

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

            // Initialize counter and index variables to use it in the while
            // loop
            int counter = 0;
            int index = 0;

            // Create a double array variable, and set the limit to 5
            double[] numbers = new double[5];

            while (counter++ < 5) {
                String value = inp.nextLine();
                value.toLowerCase();

                // Set the index value to "h" or "H"
                boolean containsh = value.startsWith("h")
                        || value.startsWith("H") || value.endsWith("h")
                        || value.endsWith("H");

                if (containsh) { // Validate h at beginning or end
                    numbers[index] = Double
                            .parseDouble(value.toLowerCase().replace("h", ""));
                    index++;
                    System.out.println(
                            "HST will be taken account for this value");
                }
            }
            System.out.println("HST Values:");

            for (int i = 0; i < numbers.length; i++) {
                System.out.println(numbers[i]);
            }
        }
    }
}

Resultados:

Press any key to start

Enter the amount of each item
Upto 5 inputs are allowed!

1
2H
HST will be taken account for this value
H3
HST will be taken account for this value
h4.7
HST will be taken account for this value
5.h6
HST Values:
2.0
3.0
4.7
0.0
0.0