A
A
Alex2018-03-01 15:45:47
Java
Alex, 2018-03-01 15:45:47

Why doesn't the roof variable change its value?

import java.util.Scanner;

public class House {
  
Scanner in = new Scanner(System.in);

int chooseRoof(int roof) {
  for( ; ; ) {
    System.out.println("Choose your roof material:");
    System.out.println("Default roof - 45 \t Tile roof - 95 \t Slate roof - 126");
    System.out.println("Enter a number of the choosen material:");
    String input = in.nextLine();
    
    // checking input, if input is empty, warn user about it
    // and ask to try again, after that - continue loop.
            
    if(input.isEmpty()) {
      System.out.println("You don't enter anything.");
      System.out.println();
      continue;
    }
    
    // checking input, if input have any characters, warn user about it
    // and ask to try again, after that - continue loop.
    
    if(!input.matches("[-+]?\\d+")){
      System.out.println("The number must consists only numerals.");
      System.out.println();
      continue;
    }
    
    if (input.equals("45") || input.equals("95") || input.equals("126")) {
      roof = Integer.parseInt(input);
      return roof;
    }
    else {
      System.out.println("Your enter wrong number. Pls choose the material and "
          + "use his number.");
      System.out.println();
      continue;
    }
  }
  
}

public class Building {
  public static void main(String args[]) {
        int roof = 45;
        House home = new House();
        home.chooseRoof(roof); // Переменная roof должна поменять свое значение
        System.out.println(roof); // Но когда мы ее выводим, видим старое значение,
                                             // почему? Как это исправить?
        }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
D3lphi, 2018-03-01
@cocaine4ik

How are primitive types passed in java? By value or by reference? By value, of course. This means that changing the value of this variable in the chooseRoof() method will not affect the value of the variable in the main() method.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question