Should getters and setters used in pairs? - java

I am learning getters and setters in Java. I wrote the code below :
import java.util.*;
class test{
private int num1;
private int num2;
Scanner sc=new Scanner(System.in);
void mult(){
num1=sc.nextInt();
num2=sc.nextInt();
System.out.println("Multiply = "+(num1*num2));
}
public int getnum1(){
return num1;
}
public int getnum2(){
return num2;
}
}
class TestDemo{
void add(){
test ob=new test();
System.out.println("Num 1 = "+ob.getnum1());
System.out.println("Num 2 = "+ob.getnum2());
}
}
public class Main
{
public static void main(String[] args) {
System.out.println("Hello World");
test ob=new test();
ob.mult();
TestDemo ob2=new TestDemo();
ob2.add();
}
}
Inside the class TestDemo, I am trying to access the value of the variables num1 and num2 but in the output, I am getting 0 as shown here:
output
Can anyone help me, how can I access the data inside the num1 and num2 inside TestDemo?

You should pass existing instance of test class to TestDemo instead of creating a new one. Like,
class TestDemo{
private test ob;
//set test instance through constructor or setter
TestDemo(test ob) {
this.ob=ob;
}
void add(){
System.out.println("Num 1 = "+ob.getnum1());
System.out.println("Num 2 = "+ob.getnum2());
}
}
public class Main
{
public static void main(String[] args) {
System.out.println("Hello World");
test ob=new test();
ob.mult();
TestDemo ob2=new TestDemo(ob);
ob2.add();
}
}

Related

The method areEqualByThreeDecimalPlace(double, double) is undefined for the type DecimalComparator

My main java.
public class Main {
DecimalComparator dc = new DecimalComparator();
DecimalComparator rt = new DecimalComparator();
public static void main(String[] args) {
dc.areEqualByThreeDecimalPlace(1.256, 2.632);
}
}
My DecimalComparator code
public class DecimalComparator {
public void areEqualByThreeDecimalPlace(double num1,double num2) {
String Str1 = String.format("%.3g%n",num1);
System.out.println("The value of Str1"+Str1);
}
}
and in Min.class I have error "The method areEqualByThreeDecimalPlace(double, double) is undefined for the type DecimalComparator"
Your main method is static. You cannot get a non-static instance of DecimalComparator from a static method. You have to get an instance of your Main class to get an instance of your DecimalConverter class.
Field names in Java always start with a lower-case character.
Here's the complete runnable code I used. I made your DecimalComparator class an inner class so I could post the code as one block.
public class DecimalComparatorMain {
public static void main(String[] args) {
DecimalComparatorMain dcm = new DecimalComparatorMain();
DecimalComparator dc = dcm.new DecimalComparator();
dc.areEqualByThreeDecimalPlace(1.256, 2.632);
}
public class DecimalComparator {
public void areEqualByThreeDecimalPlace(double num1, double num2) {
String str1 = String.format("%.3g%n", num1);
System.out.println("The value of str1: " + str1);
}
}
}

multiple classes in Dr. Java

The JDK compiler says it compiles, but when it runs I get this error:
Static Error: This class does not have a static void main method accepting String[].
I am used to putting my methods class in one file and putting the main class in a sperate file.
How do I go about solving this issue?
import java.util.Scanner;
public class Test{
private final int classSize = 35;
private int numEnrolled, numNeeded;
public void Input(){
Scanner in = new Scanner(System.in);
System.out.println("Enter the amount enrolled in your class");
numEnrolled = in.nextInt();
System.out.println("Your input is " + numEnrolled);
// Other parts of code that needs to be coded
}
}
class testRunner{
static void main(String args[]){
Test newTest = new Test();
newTest.Input();
}}
In one file you can have only one public class, and multiple
non-public classes
Your filename has to match with the only public
class
To make your class runnable it should contain a public static
void main(String args[]) method, preferably in the public class
Your TestRunner.java should look like this
class Test{
private final int classSize = 35;
private int numEnrolled, numNeeded;
public void Input(){
Scanner in = new Scanner(System.in);
System.out.println("Enter the amount enrolled in your class");
numEnrolled = in.nextInt();
System.out.println("Your input is " + numEnrolled);
// Other parts of code that needs to be coded
}
}
public class TestRunner{
public static void main(String args[]){
Test newTest = new Test();
newTest.Input();
}}
Edit:
If you want to leave the file name Test.java, this works too:
public class Test {
private final int classSize = 35;
private int numEnrolled, numNeeded;
public void Input() {
Scanner in = new Scanner(System.in);
System.out.println("Enter the amount enrolled in your class");
numEnrolled = in.nextInt();
System.out.println("Your input is " + numEnrolled);
// Other parts of code that needs to be coded
}
}
class TestRunner {
public static void main(String args[]) {
Test newTest = new Test();
newTest.Input();
}
}
Change:
class testRunner{
static void main(String args[]){
Test newTest = new Test();
newTest.Input();
}}
to:
public class testRunner {
public static void main(String args[]) {
Test newTest = new Test();
newTest.Input();
}}
main() must always be declared public

simple java program find mistake

I try to learn JAVA language. I write simple program, but it don't work. Could somebody give to me advice how solve problem.
My program:
class WriteOut {
private static int sumas;
public void sud(int sds) {
sumas = sds;
}
public static void main(String arg[]) {
WriteOut sum =new WriteOut();
sum.sud(5);
System.out.println("suma: "+sum);
}
}
Output I get "suma: bandymas.WriteOut#70dea4e";
I want get answer "suma: 5"
System.out.println() calls toString() method, which comes from basic Object class.
There are two ways of fixing this code:
1) Override the standart toString() method:
class WriteOut {
private static int sumas;
#Override
public String toString(){
return String.valueOf(sumas); // returns a string with sumas value
}
public static void main(String arg[]) {
WriteOut sum =new WriteOut();
sum.sud(5);
System.out.println("suma: "+sum);
}
}
2) Or just change the System.out.println() call:
class WriteOut {
public static int sumas; // To allow System.out.println() to see this variable
public void sud(int sds) {
sumas = sds;
}
public static void main(String arg[]) {
WriteOut sum =new WriteOut();
sum.sud(5);
System.out.println("suma: "+sum.sumas);
}
}
change what's inside System.out.println() to :
System.out.println("suma: "+sum.sumas);
Exmple:
class WriteOut {
private static int sumas;
public void sud(int sds) {
sumas = sds;
}
public static void main(String arg[]) {
WriteOut sum =new WriteOut ();
sum.sud(5);
System.out.println("suma: "+sum.sumas);
}
}
Output :
suma: 5

Java objects of classes not returning the same values

I am creating an object of a class from 2 separate classes and both objects are returning different values for the same method. I suspect it may be an issue with the while loop but here are the classes. The main class works, the setup class is the class that is being turned into and object and the game loop class has the object that doesn't return the right values. it returns the values defined at the beginning of setup and not the modified versions.
import java.util.Scanner;
public class MainClass {
static Scanner input = new Scanner(System.in);
//String x = input.nextLine();
public static void main(String[] args)
{
setup setupGov = new setup();
gameLoop gameLoop = new gameLoop();
setupGov.statsSetup();
System.out.println("happyness: " + setupGov.getHappyness() + " money: £" + setupGov.getMoney() + " population: " + setupGov.getPopulation());
gameLoop.loop();
}
}
import java.util.Scanner;
public class setup {
static Scanner input = new Scanner(System.in);
String goverment;
int happyness;
double money;
int population = 1000000;
public setup()
{
}
public void statsSetup()
{
System.out.println("Choose a goverment: 1. democracy 2. monarchy 3. dictatorship");
goverment = input.nextLine();
if (goverment.equals("1"))
{
happyness = 75;
money = 250000.0;
}
else if (goverment.equals("2"))
{
happyness = 50;
money = 500000.0;
}
else if (goverment.equals("3"))
{
happyness = 25;
money = 750000.0;
}
else
{
System.out.println("ENTER A VALID VALUE");
}
}
public int getHappyness()
{
return happyness;
}
public double getMoney()
{
return money;
}
public int getPopulation()
{
return population;
}
}
import java.util.Scanner;
public class gameLoop
{
static Scanner input = new Scanner(System.in);
static int turn = 0;
int happyness;
double money;
int population;
public gameLoop()
{
}
setup setupGov = new setup();
public static void main(String[] args)
{
}
public void loop()
{
while (true)
{
System.out.println("Turn: "+turn);
input.nextLine();
turn++;
}
}
}
You are creating two different instances of class setup. One is created directly in main function and other is created in gameLoop object. They do not share their attributes so methods may return different value. Every time you use 'new' operator, a new instance of class is created with it's own attributes (only static member are shared since static member belongs to class instead of instances). If you want to have same instances you could write:
public class gameLoop
{
static Scanner input = new Scanner(System.in);
static int turn = 0;
int happyness;
double money;
int population;
public gameLoop(setup setupGov)
{
this.setupGov = setupGov;
}
setup setupGov;
public static void main(String[] args)
{
}
public void loop()
{
while (true)
{
System.out.println("Turn: "+turn);
input.nextLine();
turn++;
}
}
}
And in main:
public class MainClass {
static Scanner input = new Scanner(System.in);
//String x = input.nextLine();
public static void main(String[] args)
{
setup setupGov = new setup();
gameLoop gameLoop = new gameLoop(setupGov);
setupGov.statsSetup();
System.out.println("happyness: " + setupGov.getHappyness() + " money: £" + setupGov.getMoney() + " population: " + setupGov.getPopulation());
gameLoop.loop();
}
}
Now both of objects setupGov will be the same instance.
Please note:
It is good practice to have class name written with capitalized first letter eg. GameLoop instead of gameLoop
I don't really understand what you're trying to do or what the question is, but in your main class you have an object with the same exact name of the class.
gameLoop gameLoop = new gameLoop();
I don't know if that's the exact cause of your problem, but I'm almost sure that that isn't supposed to be like that.

troubles with creating objects in java

Hello So I have a entire class called tractor with different data's stored in it but now I'm suppose to create an object call tractor with a zero parameter constructor but This is the code I have so far and its giving em errors
First off this my Tractor Class which is in a different file:
import java.util.Scanner;
class Tractor
{
private int RentalRate;
private int RentalDays;
private int VehicleID;
private int RentalProfit;
public void setRentalRate(int r)
{
Scanner input = new Scanner(System.in);
System.out.println("What's the Rental Rate?");
int num = input.nextInt();
num = r;
if(r<0 || r >1000)
RentalRate = r;
RentalRate= 1;
}
public int getRentalRate()
{
return RentalRate;
}
public void setVehicleID(int v)
{
Scanner input = new Scanner(System.in);
System.out.println("What's the vehicleID?");
int num1 = input.nextInt();
num1 = v;
if(v<0)
VehicleID = v;
VehicleID = 1;
}
public int getVehicleID()
{
return VehicleID;
}
public void setRentalDays(int d)
{
Scanner input = new Scanner(System.in);
System.out.println("How many rental days?");
int num2 = input.nextInt();
num2 = d;
if(d<0)
RentalDays = d;
RentalDays = 1;
}
public int getRentalDays()
{
return RentalDays;
}
public String toString()
{
String str;
str = "RentalDays:" + RentalDays +"\nRenalRate:" + RentalRate + "\nVehicleID " + VehicleID;
return str;
}
public void RentalProfit(int RentalRate, int RentalDays)
{
RentalProfit = RentalRate * RentalDays;
}
}
import java.util.Scanner;
public class testTractor
{
public static void main(String[] args)
{
public tractor()
{
this.RentalDays = d;
this.RentalRate = r;
this.VehicleID = v;
}
}
}
The error is :
testTractor.java:7: error: illegal start of expression
public tractor()
^
testTractor.java:7: error: ';' expected
public tractor()
^
2 errors
You have compilation errors. You need to first declare the Tractor class then add the constructor inside it. One way to do is declare in a separate file. Also in Java unless you had defined d you couldnt have assigned it. Maybe you wanted to assign the day as a String look in the examples I provide below.
You need to to first create a file call Tractor.java and then define variables there. For example contents of Tractor.java:
public class Tractor {
String rentaldays,someOtherValue;
public Tractor(){
rentaldays ="monday";
someOtherValue="value";
}
//or
public Tractor(String rentalDays){
this.rentaldays = rentalDays;
someOtherValue = "asf";
}
}
Then in your main method You can do Tractor trac = new Tractor(); or Tractor trac = new Tractor("tuesday"); also after that you can print the rentaldays of trac using System.out.println(trac.rentaldays);
From the looks of it you will probably be making a tractor rental system. In that case, rentalDays may be an array of Strings. And then you would have an array of Tractor objects to store in the rental system. You can look at these terms and keywords to point you in the right direction.
You are defining it wrong, define your methods inside class then call them in main() method.
class Test{
public void greeting(){
System.out.print("hello to JAVA..");
}
public static void main(String[] args){
Test testObj = new Test();
testObj.greeting();
}
}
you use an illegal of java syntax, if you already have class tractor in your project. for calling it to in other class, try below code
public class TestTractor(){
Tractor objTractor;
public static void main(String[] args){
//create new tractor object with no parameter
objTractor = new Tractor();
//create new tractor object with parameter
objTractor = new Tractor(parameter here);
//do some action of object here
...........
}
}
//This is just a sample
in your tractor class add below code
public tractor()
{
this.RentalDays = d;
this.RentalRate = r;
this.VehicleID = v;
}
And keep your TestTractor class as
public class TestTractor(){
public static void main(String[] args){
Tractor objTractor = new Tractor();
// objTractor.yourMethodName
}
}

Categories