0

I am learning about basic techniques of parsing input.

The first one is given an integer N, read N lines and each line contains some information. The second one is read until special character (0). The third one is to read until the end of file. The out put will be 1 or 0 for each line of information.

Thanks to ctst's answer, I have edited my method to process each line of input:

public static void compareAnd(String a, String b) {
    if (a.equals("1") && b.equals("1")) {
        System.out.println("1");
    } else{
        System.out.println("0");
    }
}

public static void compareOr(String a, String b) {
    if (a == "0" && b == "0") {
        System.out.println("0");
    } else {
        System.out.println("1");
    }
}

I do not know how to read until the special character (0) and read until end of file...

I tried to do this for the second type of input:

        case 2:
            int counter = 0;
            while (!sc.nextLine().equals("0")) {
                counter += 1;
            }
            String[][] a2D = new String[counter][3];            
            for (int i = 0; i < counter; i++) {
                for (int j = 0; j < 3; j++) {
                    a2D[i][j] = (String)sc.next(); 
                }
            }
            for (int r = 0; r < a2D.length; r++) {
                if (a2D[r][0].equals("AND")) {
                    compareAnd(a2D[r][1], a2D[r][2]);
                } else {
                    compareOr(a2D[r][1], a2D[r][2]);
                }
            }
            break;

I want to create a 2D array to process the input. However, as the input stop only when the user input "0", I do not know the number of rows of the array. Besides, there is no ouput when I execute the above code... Although I input 0.

The Sample Input:

2
AND 1 1
OR 1 0
AND 1 0

output:

1
1
0

2 Answers2

1

Beware of the difference of == and equals. The first one checks, if it is the same Object (since String is not primitive, this yields false for e.g. "a"==StringWithValuea. equals compares two Objects (for String, if the value is the same). Try changing your ==to equals (and != to ! .equals) and tell, if the error persists.

Towards you first case: why dont you directly write:

public static void compareAnd(String a, String b) {
    if (a.equals("1") && b.equals("1")) {
        System.out.println("1");
    }
    else{
        System.out.println("0");
    }
}
ctst
  • 1,610
  • 1
  • 13
  • 28
0

while (sc.nextLine() != "0") ??

In java we don't use binary operators like this on strings use something like

while (!sc.nextLine().equals("0")) make sure u append ! operator before your condition.

Yati Sawhney
  • 1,372
  • 1
  • 12
  • 19