troubles with creating objects in java - 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
}
}

Related

count the number of objects created by java

I'm trying to count the number of objects created but it always returns 1.
public class Drivertwo {
public static void main(String[] args) {
Employee newEmp = new Employee();
Employee newEmp2 = new Employee();
Calculate newcal = new Calculate();
Clerk newclerk = new Clerk();
float x;
int y;
newEmp.setEmp_no(2300);
newEmp.setEmp_name("W.Shane");
newEmp.setSalary(30000);
newEmp.counter();
newEmp2.setEmp_no(1300);
newEmp2.setEmp_name("W.Shane");
newEmp2.setSalary(50000);
newEmp2.counter();
newclerk.setEmp_name("Crishane");
newclerk.setEmp_no(1301);
newclerk.setGrade(2);
newclerk.setSalary(45000);
newclerk.counter();
System.out.println("Salary is:" + newcal.cal_salary(newclerk.getSalary(), newclerk.getEmp_no()));
System.out.println("Name is:" + newclerk.getEmp_name());
System.out.println("Employee number is:" + newclerk.getEmp_no());
System.out.println("Employee Grade is:" + newclerk.getGrade());
System.out.println("No of objects:" + newEmp.numb);
This is my class with the main method
public class Employee {
private int salary;
private int emp_no;
private String emp_name;
public int numb=0;
public int getSalary() {
return salary;
}
public int getEmp_no() {
return emp_no;
}
public String getEmp_name() {
return emp_name;
}
public void setSalary(int newSalary) {
salary = newSalary;
}
public void setEmp_no(int newEmp_no) {
emp_no = newEmp_no;
}
public void setEmp_name(String newEmp_name) {
emp_name = newEmp_name;
}
}
public int counter() {
numb++;
return numb;
This is my Employee class
I tried to run counter in my employee class as a starter but it always returns 1. I know I can make a counter in main class and everytime I make a new object I can get the counter but I want to automatically increase the numb by 1 when an object is made.
You need to make numb static so that there will only be one copy for every instance of the class. As it is, every single Employee object has its own copy of numb.
Also instead of creating a method to up the counter why not just put it in the constructor:
public Employee() {
numb++;
}
numb is an instance variable, meaning that each Employee object will have its own numb, that will be initialized by 0.
If you want all the Employee instances to share the same numb, you should make it static.
// Java program Find Out the Number of Objects Created
// of a Class
class Test {
static int noOfObjects = 0;
// Instead of performing increment in the constructor instance block is preferred
//make this program generic. Because if you add the increment in the constructor
//it won't work for parameterized constructors
{
noOfObjects += 1;
}
// various types of constructors
public Test()
{
}
public Test(int n)
{
}
public Test(String s)
{
}
public static void main(String args[])
{
Test t1 = new Test();
Test t2 = new Test(5);
Test t3 = new Test("Rahul");
System.out.println(Test.noOfObjects);
}
}
Since static members initialized only once and it will be same for each and every instances of class.
class YourClass {
private static int numb;
public YourClass() {
//...
numb++;
}
public static int counter() {
return numb;
}
}
So simple;-
make this modifications
make numb static like, public int numb=0;,
remove numb++; from method count() and
create constructor public Employee{numb++;}

"cannot find symbol" error when invoking a method using reference of class

I feel as if this is super simple but I cant get this to work. I am trying to use this:
import java.util.Scanner;
import java.lang.Math;
public class SammysRentalPriceWithMethods
{
public static void main(String[] args)
{
Rental rental = new Rental();
SammysRentalPriceWithMethods SRPWM = new SammysRentalPriceWithMethods();
getLogo();
getContractNum();
getHoursAndMinutes();
}
public static void getLogo()
{
rental.setlogo();
}
public static void getContractNum()
{
rental.setContractNumber();
}
public static void getHoursAndMinutes()
{
rental.setHoursAndMinutes();
}
}
to call this class and the methods contained inside:
import java.util.Scanner;
import java.lang.Math;
public class Rental
{
public final int minutes = 60;
public final double hourlyRate = 40.0;
private static String contractNum;
private static double hours;
private static int minutes2;
private static double price;
Scanner Input = new Scanner(System.in);
public static void setlogo()
{
System.out.println("*********************************");
System.out.println("*Sammy's makes it fun in the sun*");
System.out.println("*********************************");
}
public static void setContractNumber()
{
Scanner Input = new Scanner(System.in);
System.out.println("Please enter your contract number.");
contractNum = Input.nextLine();
}
public static void setHoursAndMinutes()
{
int timeOver;
Scanner Input2 = new Scanner(System.in);
System.out.println("Please enter the amount of time in minutes you rented the equipment.");
minutes2 = Input2.nextInt();
if (minutes2 > 60)
{hours = (minutes2/60);
price = (hours * 40);
timeOver = (minutes2%60);
price = (price + timeOver);
System.out.println("You rented the equipment for " + hours + " hours and " + timeOver + " minutes.");
System.out.println("Your total price is: " + price);
}
else if (minutes2 < 60)
{
price = (minutes2 * 1);
System.out.println(price);
}
}
}
but the compiler is saying "error: cannot find symbol" on every reference of rental in the SRPWM class. I already called the class in the main method. Any ideas?
The compiler is right.
The scope of the variables rental and SRPWM is restricted to the main method.
Either you pass the attributes to the methods of the class or you make them static fields of SammysRentalPriceWithMethods.
Because rental is declared in your main method, it will only be visible in that method. You should consider declaring this variable at the class level.
You need to declare the Rental class variable outside the main() function. If you declare it inside the main(), then you won't be able to use it in other functions. So, make your Rental variable global.
New file should be this:
import java.util.Scanner;
import java.lang.Math;
public class SammysRentalPriceWithMethods {
Rental rental = new Rental();
public static void main(String[] args) {
SammysRentalPriceWithMethods SRPWM = new SammysRentalPriceWithMethods();
getLogo();
getContractNum();
getHoursAndMinutes();
}
public static void getLogo() {
rental.setlogo();
}
public static void getContractNum() {
rental.setContractNumber();
}
public static void getHoursAndMinutes() {
rental.setHoursAndMinutes();
}
}
The problem is you are mixing both static and non-static members and invoking them inside your SammysRentalPriceWithMethods class, so change the class as shown in the below code with comments:
public class SammysRentalPriceWithMethods {
private Rental rental;
//Use constructor to inject Rental object
public SammysRentalPriceWithMethods(Rental rental) {
this.rental = rental;
}
public static void main(String[] args) {
//create Rental object
Rental rental = new Rental();
SammysRentalPriceWithMethods srpwm =new SammysRentalPriceWithMethods();
//invoke methods using srpwm reference
srpwm.getLogo();
srpwm.getContractNum();
srpwm.getHoursAndMinutes();
}
public void getLogo() {
rental.setlogo();
}
public void getContractNum() {
rental.setContractNumber();
}
public void getHoursAndMinutes() {
rental.setHoursAndMinutes();
}
}
You need to remember the following basics:
(1) Call static members of a class using classname and . operator (if you want to call static members within static methods you call them without classname and .)
(2) Call non-static members using the object and . operator
(3) Name the variables, method names with camel case (starting letter in lower case)

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.

Java CompareTO method issues

I am trying to sort out a simple list of students mark with a simple java program however I am getting
Exception in thread "main" java.lang.ClassCastException: Student cannot be cast to java.lang.Comparable
public class Student {
public String name;
public int mark;
public Student(String name, int mark){
this.name=name;
this.mark=mark;
}
public int compareTo(Student o){
return this.mark-o.mark;
}
public String toString(){
String s = "Name: "+name+"\nMark: "+mark+"\n";
return s;
}
public static void main(String[] args) {
Student Class[] = new Student[9];
Class[0] = new Student("Henry",100);
Class[1] = new Student("Alex", 10);
Class[2] = new Student("Danielle",100);
Class[3] = new Student("Luke",10);
Class[4] = new Student("Bob",59);
Class[5] = new Student("Greg",76);
Class[6] = new Student("Cass",43);
Class[7] = new Student("Leg",12);
Class[8] = new Student("Bobe",13);
Arrays.sort(Class);
for(int i = 0;i<Class.length;i++){
System.out.println(Class[i]);
Your Student class must implement the Comparable interface in order to use Arrays#sort passing Student[] array. The fact that your class currently have a compareTo method doesn't mean it implements this interface, you have to declare this:
public class Student implements Comparable<Student> {
//class definition...
}
Make your Student class implement Comparable<Student>. The compareTo() method doesn't work on it's own while sorting.
Also, Class doesn't look like a very good variable name. How about using students? Also, I see an issue in your compareTo method:
public int compareTo(Student o){
return this.mark-o.mark;
}
Never compare on the result of subtraction of 2 integers, or longs. The result might overflow. Rather use Integer.compare(int, int) method.
Also, get rid of public fields. Make them private, and provide public getters to access them.
public class Fawaz1 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// تجربه
String SS[]=new String[6];
double GG[]=new double[6];
SS[0]="fawaz";
SS[1]="ahmd";
SS[2]="hmd";
SS[3]="fos";
SS[4]="raid";
SS[5]="majd";
GG[0]=3.94;
GG[1]=2.50;
GG[2]=2.95;
GG[3]=4.92;
GG[4]=3.0;
GG[5]=3.78;
int i;
for (i=0; i<3; i++){
System.out.print(SS[i]+"\t"+GG[i]+"\t");
if (GG[i]>=4.75)
{System.out.println("A+");}
else if(GG[i]>=4.50){
System.out.println("A");
} else if(GG[i]>=3.70){
System.out.println("B+");
}else if(GG[i]>=3.59){
System.out.println("B");
}else if(GG[i]>=2.78){
System.out.println("C+");
}else if(GG[i]>=2.55){
System.out.println("C");
}else if(GG[i]>=1.52){
System.out.println("D");
}else if(GG[i]>=1.10){
System.out.println("F");
}
}
}
}

How to return 2 values from a Java method?

I am trying to return 2 values from a Java method but I get these errors. Here is my code:
// Method code
public static int something(){
int number1 = 1;
int number2 = 2;
return number1, number2;
}
// Main method code
public static void main(String[] args) {
something();
System.out.println(number1 + number2);
}
Error:
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - missing return statement
at assignment.Main.something(Main.java:86)
at assignment.Main.main(Main.java:53)
Java Result: 1
Instead of returning an array that contains the two values or using a generic Pair class, consider creating a class that represents the result that you want to return, and return an instance of that class. Give the class a meaningful name. The benefits of this approach over using an array are type safety and it will make your program much easier to understand.
Note: A generic Pair class, as proposed in some of the other answers here, also gives you type safety, but doesn't convey what the result represents.
Example (which doesn't use really meaningful names):
final class MyResult {
private final int first;
private final int second;
public MyResult(int first, int second) {
this.first = first;
this.second = second;
}
public int getFirst() {
return first;
}
public int getSecond() {
return second;
}
}
// ...
public static MyResult something() {
int number1 = 1;
int number2 = 2;
return new MyResult(number1, number2);
}
public static void main(String[] args) {
MyResult result = something();
System.out.println(result.getFirst() + result.getSecond());
}
Java does not support multi-value returns. Return an array of values.
// Function code
public static int[] something(){
int number1 = 1;
int number2 = 2;
return new int[] {number1, number2};
}
// Main class code
public static void main(String[] args) {
int result[] = something();
System.out.println(result[0] + result[1]);
}
You could implement a generic Pair if you are sure that you just need to return two values:
public class Pair<U, V> {
/**
* The first element of this <code>Pair</code>
*/
private U first;
/**
* The second element of this <code>Pair</code>
*/
private V second;
/**
* Constructs a new <code>Pair</code> with the given values.
*
* #param first the first element
* #param second the second element
*/
public Pair(U first, V second) {
this.first = first;
this.second = second;
}
//getter for first and second
and then have the method return that Pair:
public Pair<Object, Object> getSomePair();
You can only return one value in Java, so the neatest way is like this:
return new Pair<Integer>(number1, number2);
Here's an updated version of your code:
public class Scratch
{
// Function code
public static Pair<Integer> something() {
int number1 = 1;
int number2 = 2;
return new Pair<Integer>(number1, number2);
}
// Main class code
public static void main(String[] args) {
Pair<Integer> pair = something();
System.out.println(pair.first() + pair.second());
}
}
class Pair<T> {
private final T m_first;
private final T m_second;
public Pair(T first, T second) {
m_first = first;
m_second = second;
}
public T first() {
return m_first;
}
public T second() {
return m_second;
}
}
Here is the really simple and short solution with SimpleEntry:
AbstractMap.Entry<String, Float> myTwoCents=new AbstractMap.SimpleEntry<>("maximum possible performance reached" , 99.9f);
String question=myTwoCents.getKey();
Float answer=myTwoCents.getValue();
Only uses Java built in functions and it comes with the type safty benefit.
Use a Pair/Tuple type object , you don't even need to create one if u depend on Apache commons-lang. Just use the Pair class.
you have to use collections to return more then one return values
in your case you write your code as
public static List something(){
List<Integer> list = new ArrayList<Integer>();
int number1 = 1;
int number2 = 2;
list.add(number1);
list.add(number2);
return list;
}
// Main class code
public static void main(String[] args) {
something();
List<Integer> numList = something();
}
public class Mulretun
{
public String name;;
public String location;
public String[] getExample()
{
String ar[] = new String[2];
ar[0]="siva";
ar[1]="dallas";
return ar; //returning two values at once
}
public static void main(String[] args)
{
Mulretun m=new Mulretun();
String ar[] =m.getExample();
int i;
for(i=0;i<ar.length;i++)
System.out.println("return values are: " + ar[i]);
}
}
o/p:
return values are: siva
return values are: dallas
I'm curious as to why nobody has come up with the more elegant callback solution. So instead of using a return type you use a handler passed into the method as an argument. The example below has the two contrasting approaches. I know which of the two is more elegant to me. :-)
public class DiceExample {
public interface Pair<T1, T2> {
T1 getLeft();
T2 getRight();
}
private Pair<Integer, Integer> rollDiceWithReturnType() {
double dice1 = (Math.random() * 6);
double dice2 = (Math.random() * 6);
return new Pair<Integer, Integer>() {
#Override
public Integer getLeft() {
return (int) Math.ceil(dice1);
}
#Override
public Integer getRight() {
return (int) Math.ceil(dice2);
}
};
}
#FunctionalInterface
public interface ResultHandler {
void handleDice(int ceil, int ceil2);
}
private void rollDiceWithResultHandler(ResultHandler resultHandler) {
double dice1 = (Math.random() * 6);
double dice2 = (Math.random() * 6);
resultHandler.handleDice((int) Math.ceil(dice1), (int) Math.ceil(dice2));
}
public static void main(String[] args) {
DiceExample object = new DiceExample();
Pair<Integer, Integer> result = object.rollDiceWithReturnType();
System.out.println("Dice 1: " + result.getLeft());
System.out.println("Dice 2: " + result.getRight());
object.rollDiceWithResultHandler((dice1, dice2) -> {
System.out.println("Dice 1: " + dice1);
System.out.println("Dice 2: " + dice2);
});
}
}
You don't need to create your own class to return two different values. Just use a HashMap like this:
private HashMap<Toy, GameLevel> getToyAndLevelOfSpatial(Spatial spatial)
{
Toy toyWithSpatial = firstValue;
GameLevel levelToyFound = secondValue;
HashMap<Toy,GameLevel> hm=new HashMap<>();
hm.put(toyWithSpatial, levelToyFound);
return hm;
}
private void findStuff()
{
HashMap<Toy, GameLevel> hm = getToyAndLevelOfSpatial(spatial);
Toy firstValue = hm.keySet().iterator().next();
GameLevel secondValue = hm.get(firstValue);
}
You even have the benefit of type safety.
Return an Array Of Objects
private static Object[] f ()
{
double x =1.0;
int y= 2 ;
return new Object[]{Double.valueOf(x),Integer.valueOf(y)};
}
In my opinion the best is to create a new class which constructor is the function you need, e.g.:
public class pairReturn{
//name your parameters:
public int sth1;
public double sth2;
public pairReturn(int param){
//place the code of your function, e.g.:
sth1=param*5;
sth2=param*10;
}
}
Then simply use the constructor as you would use the function:
pairReturn pR = new pairReturn(15);
and you can use pR.sth1, pR.sth2 as "2 results of the function"
You also can send in mutable objects as parameters, if you use methods to modify them then they will be modified when you return from the function. It won't work on stuff like Float, since it is immutable.
public class HelloWorld{
public static void main(String []args){
HelloWorld world = new HelloWorld();
world.run();
}
private class Dog
{
private String name;
public void setName(String s)
{
name = s;
}
public String getName() { return name;}
public Dog(String name)
{
setName(name);
}
}
public void run()
{
Dog newDog = new Dog("John");
nameThatDog(newDog);
System.out.println(newDog.getName());
}
public void nameThatDog(Dog dog)
{
dog.setName("Rutger");
}
}
The result is:
Rutger
You can create a record (available since Java 14) to return the values with type safety, naming and brevity.
public record MyResult(int number1, int number2) {
}
public static MyResult something() {
int number1 = 1;
int number2 = 2;
return new MyResult(number1, number2);
}
public static void main(String[] args) {
MyResult result = something();
System.out.println(result.number1() + result.number2());
}
First, it would be better if Java had tuples for returning multiple values.
Second, code the simplest possible Pair class, or use an array.
But, if you do need to return a pair, consider what concept it represents (starting with its field names, then class name) - and whether it plays a larger role than you thought, and if it would help your overall design to have an explicit abstraction for it. Maybe it's a code hint...
Please Note: I'm not dogmatically saying it will help, but just to look, to see if it does... or if it does not.

Categories