'Print l1.processor in a method
I want to print the l1.processor (an attribute of object l1) in a method but I can't do that. Here's my code:
package com.company;
import java.util.Scanner;
public class Laptop {
String processor;
int gen;
int ram;
int hdd;
int ssd;
void output(){
System.out.println(l1.processor);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Laptop l1 = new Laptop();
Laptop l2 = new Laptop();
Laptop l3 = new Laptop();
l1.processor = sc.nextLine();
System.out.println("Processor: " + l1.processor);
}
}
Solution 1:[1]
Your output method is wrong. Since the variable processor is global, you can change it like this:
void output(){
System.out.println(processor);
}
Or, pass an instance of Laptop and keep the method body the way it was before.
void output(Laptop l1){
System.out.println(l1.processor);
}
Of course, l1 is not a good variable name.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | hfontanez |
