0

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? `

4
  • 1
    Which part of that statement is not clear to you, and did you take a look at the official JavaDoc of the methods called and Classes used? Commented Oct 9, 2020 at 14:55
  • I posted the statement Commented Oct 9, 2020 at 14:56
  • 1
    Also: In your title you are asking about a "line ... using indexOf" while in your question itself you ask about a line that doesn't call the indexOf method at all. Having your title and actual question asking 2 different things is confusing at best and makes answering unnecessarily difficult. Commented Oct 9, 2020 at 14:58
  • Did you post this question yesterday (or before)? Commented Oct 9, 2020 at 16:01

1 Answer 1

2
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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.