Could you tell me why it still works? | Sololearn: Learn to code for FREE!
Neuer Kurs! Jeder Programmierer sollte generative KI lernen!
Kostenlose Lektion ausprobieren
+ 1

Could you tell me why it still works?

I tried to intentionally make an wrong code that doesn't work well, but mysteriously it works just fine!! It's a rectangle area calculator that you input numbers and it calculates the area. So I defined 'int a' and 'int b' to make it only calculate 4*5, but it calculates whatever number you put in 😲😲. How can it work? import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner read = new Scanner(System.in); int width = read.nextInt(); int height = read.nextInt(); printArea(width, height); int a = 4; int b = 5; } public static void printArea(int a,int b) { System.out.println(a*b); } }

11th Jun 2021, 9:13 AM
Jay Kay
3 Antworten
+ 2
You assigned a,b in main method which are different, not belong to printArea() method. and exist in main() only as it's local variables. printArea() method has its own local variables a,b which are assigned values passed as width,height from main method. check this code import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner read = new Scanner(System.in); int width = read.nextInt(); int height = read.nextInt(); int a = 4; int b = 5; printArea(width, height); // this works for input values , same as yours. intended code printArea(a, b); // this works as you expecting.. 4*5 printArea(width, height); // this works for input values , same as yours. intended code, no change done here a=8,b=10; //changing values printArea(a,b); //now this output 8*10 } public static void printArea(int a,int b) { System.out.println(a*b); } }
11th Jun 2021, 9:19 AM
Jayakrishna 🇮🇳
+ 2
Jayakrishna🇮🇳 thank you for the answer!
11th Jun 2021, 9:56 AM
Jay Kay
+ 1
You're welcome...Jay Kay
11th Jun 2021, 10:00 AM
Jayakrishna 🇮🇳