user13836307
user13836307

Reputation:

What does this particular line in java using indexOf mean?

My Code:

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

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

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");

int counter = 0;
int index = 0;
double[] numbers = new double[5];

boolean go = true;

while(go) {           
    String value = inp.nextLine();      
    
    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", ""));
          System.out.println("HST will be taken account for this value");
    }
    counter++;
    if (counter == 5){
      go = false;
    }
}
System.out.println("Printing Valid values");

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

What does this line in my code mean?: `numbers[index] = Double.parseDouble(value.replace("h", ""));

I am new to java arrays, so can you explain it in a simple and easy way? `

Upvotes: 0

Views: 75

Answers (1)

Joop Eggen
Joop Eggen

Reputation: 109567

int indexOfH = value.indexOf("h");
boolean containsH = indexOfH == 0 || indexOfH == (value.length()-1);

indexOfH is the char position in the string where "h" is found. More clear would have been:

int indexOfH = value.indexOf("h");
boolean containsH = value.startsWith("h") || value.endsWith("h");

Evidently "h" was a marker.

The value is stripped by

String numValue = value.replace("h", "");

And can then be converted to a double:

    numbers[index] = Double.parseDouble(numValue);

(So value might have contained "3.14h" or "h2.89".)

An other note: value.indexOf('h') would have been more logical, as now the position of a char instead of an entire String is sought.

Upvotes: 2

Related Questions