Home > Net >  Program won't break on fields (input) "9-16" (barbara), but only on field 76. Any sug
Program won't break on fields (input) "9-16" (barbara), but only on field 76. Any sug

Time:12-24

The program on fields 9 - 16 will not break, but it will break on fields 76-83. Code:

public class Main {
    private static String input = "p2ce9unfvbarbarbara2ehv29p4hrv2rn8h2cyr12gxbarsdg34rbarabarabarbarbarbarbarasdfgsfhhr"; // 
    private static int index = 0;

    public static void main(String[] args) {

        char c;
        while (true) {
            c = nextChar();
            if (c == 'b') {
                c = nextChar();
                if (c == 'a') {
                    c = nextChar();
                    if (c == 'r') {
                        c = nextChar();
                        if (c == 'b') {
                            c = nextChar();
                            if (c == 'a') {
                                c = nextChar();
                                if (c == 'r') {
                                    c = nextChar();
                                    if (c == 'a') {
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        System.out.println(index);

    }


    public static char nextChar() {
        return input.charAt(index  );
    }

}

I am new to Java as well as programming in general. The program should break after the entered input in case "barbara" is written. In the above case, it breaks only on field 76 but not on field 9 - 16.

CodePudding user response:

After you've read the first "barbar", you find a "b", so you contine the loop, but you should be backtracking to have a chance to match "barbara":

    char c;
    while (true) {
        c = nextChar();
        if (c == 'b') {
            int savedIndex = index;
            c = nextChar();
            if (c == 'a') {
                c = nextChar();
                if (c == 'r') {
                    c = nextChar();
                    if (c == 'b') {
                        c = nextChar();
                        if (c == 'a') {
                            c = nextChar();
                            if (c == 'r') {
                                c = nextChar();
                                if (c == 'a') {
                                    break;
                                }
                            }
                        }
                    }
                }
            }
            index = savedIndex;
        }
    }

CodePudding user response:

Why dont you use methods from the String class

a possibility would be to take the indexOf(String str) methods to get an index

Have a look here: https://docs.oracle.com/javase/7/docs/api/java/lang/String.html

  • Related