-4

This is my code

import java.util.Scanner;
import java.io.*;

class Main {
public static void main (String[] args)throws IOException {
  Scanner scan = new Scanner(System.in);
  System.out.println ("Enter message board post:");
  String username = scan.nextLine();
  String check = username.substring (username.indexOf(" ")+3 , username.length()).toLowerCase()+" ";
  int a = check.indexOf(" ^^ ");
  int b = check.indexOf (" qey ");
  int c = check.indexOf (" $ ");
  String first = username.substring (0 , username.indexOf(" "));
  int x = 0;
  int y =0;
  int z = 0;
  while (a != -1) {
    x++;
  check = check.substring(a+1, check.length()); 
  a = check.indexOf(" ^^ "); }
  while (b != -1) {
    y++;
  check = check.substring(b+1, check.length());
  b = check.indexOf(" qey "); }
  while (c != -1) {
    z++;
  check = check.substring(c+1, check.length());
  c = check.indexOf (" $ "); }
  if ( x > 0  || y > 0 || z > 0){
    System.out.println ("");
    System.out.println ("BAD");
      System.out.println (first);
      System.out.println ("^^: " +x);
      System.out.println ("qey: " +y);
      System.out.println ("$: " +z);

  }else {
      System.out.println ("");
      System.out.println ("CLEAN");
    }
  }
}

In the end the result is:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -18
at java.lang.String.substring(String.java:1967)
at Main.main(Main.java:23)

Which parts do I have to change to get rid of the thread? I input B0rg - resistance is futile QeY hahahaha $$$ ^^

and it should show up as

BAD
B0rg
^^: 1

qey: 1 $: 0

But it showed up as exception... Please help me...

Berben
  • 1
  • 4
    [Why is “Can someone help me?” not an actual question?](https://meta.stackoverflow.com/q/284236/5221149) --- [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/q/25385173/5221149) – Andreas Oct 04 '17 at 16:00
  • Perhaps you should do `int b = check.indexOf (" qey ");` **after** the `a` loop, since the `a` loop modifies `check`. Also, **fix your indentations**, because they currently make code very difficult to read. – Andreas Oct 04 '17 at 16:03
  • For what's it worth, this seems to be an assignment from an AP computer science course (edhesive), so it's a beginner asking. – Conor O'Brien Oct 04 '17 at 16:09

1 Answers1

0

I assume you entered just one word because if you enter two, it works fine. It fails for two because it's looking to do a substring on something it can't unless there are two words separated by your delimiter which happens to be a space.

Steven
  • 59
  • 2