Home > OS >  Split long sting in new lines and check each line first word in java
Split long sting in new lines and check each line first word in java

Time:06-27

I have a string that I split based on delimiter on new lines. I'm wondering now how to check the first word index[0] what word is but can't find a way to actually go trough the elements and check.

May be my approach is totally wrong.

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    String line = scanner.nextLine();
    String[] stringArr = line.split(">>");
  int ask = 0;
    for (int i = 0; i < stringArr.length; i  ) {

        if (stringArr[0].equals("radio")) {
            ask = 10;
        } else if (Objects.equals(stringArr[0], "tv")) {
            ask = 15;
        } else {
            System.out.println("Invalid media.");
        }

    }
  System.out.println(ask);
}  

Then when I input radio 3 7210>>tv 4 2345>>radio 9 31000>>

The output should be:

10
15
10

Instead - got nothing. Empty line and the program ends.

CodePudding user response:

Is something like this what you want:

Scanner scanner = new Scanner(System.in);
String line = scanner.nextLine();
String[] stringArr = line.split(">>");
for (int i = 0; i < stringArr.length; i  ) {
  int ask = 0;
  String[] words = stringArr[i].split(" ");
  if (words[0].equals("radio")) {
      ask = 10;
      System.out.println(ask);
  } else if (words[0].equals("tv")) {
      ask = 15;
      System.out.println(ask);
  } else {
      System.out.println("Invalid media.");
  }
}

Input:

radio 3 7210>>tv 4 2345>>radio 9 31000>>

Output:

10
15
10

First of all, I defined the scanner, not sure if you did that but pretty sure you did.

The elements of stringArr will include the random numbers between each ">>". That means, in each element, we should create a new list split by " " to isolate the "radio" and "tv" as the first element.

Additionally, I just rewrote the else-if statement that checks if the first word of the phrases separated by ">>" is "tv" by using the .equals() method as your original if statement did.

Finally, since you are printing out a number EACH time the code encounters a ">>", we should print out ask inside of the for loop.

EDIT:

Moved the System.out.println(ask) inside of the if and else-if statements so it will only run with valid media.

Other than that your code worked perfectly :> , let me know if you have any further questions or clarifications!

  •  Tags:  
  • java
  • Related