1

My code is for a java 101 course and it works fine until the while loop. I put in the last input for the t, c, r, q options but it always goes to the else option where it shows "invalid input". The if statements just don't catch the 'answer' variable and always goes to the else statement.

import java.util.Scanner;

public class homework { public static void main(String[] args) {

      Scanner input = new Scanner (System.in);
      System.out.printf ("Enter number of rows: ");
      int rows = input.nextInt();
      Scanner input2 = new Scanner (System.in);
      System.out.printf ("Enter number of columns: ");
      int column = input2.nextInt();
      int[][] array = new int[rows][column];

      for (int i =0; i < rows ; i++) {
          for(int j = 0; j < column; j++) {
              array[i][j] = (i*10)+j;
              System.out.printf("%4d", array[i][j]);
          }
          System.out.println();
      }

      System.out.printf("T transpose - Rows become columns (and vice versa)%n");
      System.out.printf("C columnSum - Calculate the sum of the values in each column%n");
      System.out.printf("R reverseRows - Reverse all elements in every row of the matrix%n");
      System.out.printf("Q quit - Exit the program%n");

      boolean isValid = true;
      while (isValid) {
          Scanner input3 = new Scanner (System.in);
          String answer = input3.next().toLowerCase();

          if (answer == "t") {
              for (int i =0; i < rows ; i++) {
                  for(int j = 0; j < column; j++) {
                      array[i][j] = (j*10)+i;
                      System.out.printf("%4d", array[i][j]);
                  }
                  System.out.println();
              }
              isValid = false;


          }

          if (answer == "c") {

          }

          if (answer == "r") {


          }

          if (answer == "q") {
              System.out.println("Goodbye");
              isValid = false;

          }

          else {
              System.out.println("Invalid input, please try again...");
              isValid = true;
          }

      }



  }

}

Kimchi
  • 11
  • 1
  • Don't compare Strings using `==` or `!=`. Use the `equals(...)` or the `equalsIgnoreCase(...)` method instead. Understand that `==` checks if the two *object references* are the same which is not what you're interested in. The methods on the other hand check if the two Strings have the same characters in the same order, and that's what matters here. – Hovercraft Full Of Eels Mar 15 '19 at 02:43
  • So not `if (answer == "t") {`, rather `if (answer.equals("t")) {` or `if (answer.equalsIgnoreCase("t")) {` – Hovercraft Full Of Eels Mar 15 '19 at 02:43
  • use else if condition rather than using continue if block Last time it checks this block "if (answer == "q")" and failed and goes to the else block – Faiz Akram Mar 15 '19 at 03:11
  • Solved! Thanks a bunch! – Kimchi Mar 15 '19 at 08:36

0 Answers0