Scanner not working

Asked

Viewed 35 times

-1

I’m trying to do a little programming, but the scanner doesn’t seem to be working.

Whenever I put to print it returns 0 independent of the numbers, which was to return the highest number.

It works normal in the View class, but wanted to implement the Controller.

CODE:

Java controller.

import java.util.Scanner;
public class Controller {
  int num1, num2;

  public void getNums (){
    Scanner scan = new Scanner(System.in);
    num1 = scan.nextInt();
    num2 = scan.nextInt();
  }
}

Maiornumero.java

public class MaiorNumero {
  public int maiorNumero (int num1, int num2)
  {
    if (num1 > num2){
      return num1;
    }
    else {
      return num2;
    }
  }
}

View.java

public class View extends Controller {

  public void requestNums(){
    System.out.println("1º e 2º Número"
    +"\nex. 1 2"
    +"\n:");
  }

  public void printMaior(){
    MaiorNumero mn = new MaiorNumero();
    System.out.println(mn.maiorNumero(num1, num2));
  }
}

1 answer

0


First of all, I don’t know which MVC model you are using, but in my projects the View module never extends the controller, each of the modules must be completely independent! In your View class, in the printMaior() method you are calling the higher methodNumer and you pass two variables at 1 and 2 that have not yet been initialized (at least in the code you entered here). Try calling getNums before most:

public void printMaior(){
    MaiorNumero mn = new MaiorNumero();
    this.getNums();
    System.out.println(mn.maiorNumero(num1, num2));
  }
  • So, I’m starting yet and I’m just trying to get you to have a View and a Controller, but thanks for the warning.

  • and it’s true I didn’t call getNums. now it worked. just a doubt, really need this on the getNums part?

  • this is not necessary, it represents the object to which the method was passed. However it is good practice to write this because the code becomes clearer, you see?

  • hm, I understand.

  • in case MVC would be "right" I extend Controller p/ a View instead of View p/ o Controller?

  • no, in the MVC architecture no module can "know" or have direct access to the other, by extending one of them to the other is violating this rule. To "communicate" between them has to be the controller to pass the information, for example, if it receives a result from the model, the controller has to pass to the View for it to print on the screen.

  • ah, so I really was doing wrong. I appreciate!

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.