I'm very new to programming and I'm having a bit of trouble. Basically what I'm trying to do is to have the findCar method loop through the LinkedList called cars and have it printout the ids of the car objects. It will compile however nothing is being printed, could someone please explain why this is?
Here is the main class
import java.io.*;
import java.util.*;
public class CarManger {
private LinkedList<Car> cars = new LinkedList<Car>();
public void setup()
{
cars.add(new Car(1));
cars.add(new Car(2));
cars.add(new Car(3));
}
public void main() {
char choice;
while ((choice = readChoice()) !='x' ) {
switch(choice) {
case 'a': findCar(); break;
}
}
}
private char readChoice() {
System.out.print("Your choice: ");
return In.nextChar();
}
public void findCar()
{
for (Car i: cars)
{
int value = i.getId();
System.out.println(value);
}
}
}
And here is the Car Object
public class Car {
private int id;
public Car(int id)
{
this.id = id;
}
public int getId() {
return this.id;
}
}
And here is the In class for gathering input
import java.util.*;
public class In
{ private static Scanner in = new Scanner(System.in);
public static String nextLine()
{ return in.nextLine(); }
public static char nextChar()
{ return in.nextLine().charAt(0); }
public static int nextInt()
{ int i = in.nextInt();
in.nextLine();
return i; }
public static double nextDouble()
{ double d = in.nextDouble();
in.nextLine();
return d; }
Here is also the revised code
import java.io.*;
import java.util.*;
public class CarManger {
private LinkedList<Car> cars = new LinkedList<Car>();
public static void main(String [ ] args) {
CarManager carManager = new CarManager();
}
public CarManager () {
setup();
main();
}
Your setup() method is never called, and so no Cars appear to be added to your cars list.
Note that your main method needs to be static and to have an array of Strings parameter (unless this is not the starting point main method for your program). Without a main method, the program will compile, but won't run.
I suggest that you create a valid main method:
public static void main(String[] args) {
}
And inside create a CarManager object, call setup() on it, etc...
Note: if I had a method called findCar(), I'd probably have it accept a parameter, here, the best parameter would likely be an int to represent the Car's id number, I'd declare the method to return a Car object, and inside the method body, I'd search for a Car whose id matched that of the method parameter. The method signature would look something like this:
public Car findCar(int id) {
// TODO:
// write code to loop through the cars list
// if we find a car whose getId() matches our parameter id int
// return it!
}
Your main method would look like this:
public static void main(String[] args) {
CarManager carManager = new CarManager();
// here you'd call methods on carManager
// for instance if CarManager had an addCar(...) method
Car car = new Car(4);
carManager.addCar(car);
}
Note, I'm not calling your current setup() method or readChoice() because they don't look right to me, but without your specific assignment requirements, it's hard to guess.
You are not defining the main method correctly. It should be like this:
public static void main(String [ ] args)
Also, you should call the setup() method to load the array of cars.
Related
Hi i am trying to solve the problem I am facing
public class exam {
public static void main(String[] args) {
test1 a = new test1();
}
int zahl(int x, int y) {
int e;
if(x>y) {
e=x-y;
}else {
e=y-x;
}
if(e==0) {
return 0;
}
int z=0;
int i=1;
while(i<=e) {
z=z+i;
i++;
}
return z;
}
}
what I want to do is to call the zahl method to the test1 class
public class test1{
private exam b;
public void init() {
b = new exam();
}
void test() {
int result = b.zahl(2, 2);
assertEquals(1, result);
}
}
this is what I have tried, but it returns nothing, even though it's supposed to show me error.
You should probably be declaring your functions with the public tag i.e. public void test() if you intend to access them from other functions outside of that package. The usual Class naming convention in Java is with capital first letter, which makes your code more readable for you and others.
For your question, I don't think you are actually invoking the test() method of the test1 class. If you want that method to get called every time, you could place it inside the default Constructor.
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)
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
}
}
I want each element of an enum to have different variables but I can't reach them.
public class Employee {
public GENERAL[] general = GENERAL.values();
public static void main(String[] args) {
Employee e = new Employee();
e.general[GENERAL.INCOME.ordinal()].salary = 10; //this line doesn't compile
}
enum GENERAL{
INCOME{
public int salary;
public int tips;
},SATIFACTION{
//some variables
},EFFICIENCY{
//some variables
};
}
}
I've tried casting to (GENERAL.INCOME) but it didn't work. Is there a way to do it? If this is not possible, what is the best work around? Thanks in advance.
Try defining variables at enum level rather than individual elements:
public static void main(String[] args) {
MainClass e = new MainClass();
e.general[GENERAL.INCOME.ordinal()].salary = 10; //this line doesn't compile
System.out.println(e.general[GENERAL.INCOME.ordinal()].salary);
}
enum GENERAL{
INCOME(0,0), SATIFACTION(0, 0), EFFICIENCY(0,0);
int salary;
int tips;
GENERAL(int salary, int tips){
this.salary = salary;
this.tips = tips;
}
}
This is because INCOME is an anonymous subclass of GENERAL, it is something like this
static class GENERAL {
public static GENERAL INCOME = new GENERAL() {
public int salary;
public int tips;
};
}
there is no way to access fields of an anonymous class in Java (except reflection)
This is the cleanest way I can do it. I still have an array that I can use to iterate. Each element of the General holds its own variables. Each element has an ordinal to use as the index number.
The problem with this approach is this cannot make use of GENERAL.values(). If a new element is added later, It must be added to the getList() method manually and in the correct order. It is easy to make mistakes when adding new elements to the code.
public class Employee {
public Object general[] = General.getList();
public static void main(String[] args) {
Employee e = new Employee();
General.Income i = (General.Income) e.general[General.Income.ordinal];
i.salary = 10; //eclipse doesn't let me to combine these 2 lines into 1 expressions.
System.out.println(i.salary);
// following lines demonstrates that the salary of the e.general[General.Income.ordinal] is changed. Not just the i.
General.Income t = (General.Income) e.general[General.Income.ordinal];
System.out.println(t.salary);
}
public static class General {
public static Object[] getList() {
Object general[] = { new Income(), new Satisfaction(), new Efficiency() };
return general;
}
public static class Income {
public static final int ordinal = 0;
public int salary;
public int tips;
}
public static class Satisfaction {
public static final int ordinal() {return 1;}//using method instead of int saves memory. (8 bytes I think. Neglettable).
// some variables
}
public static class Efficiency {
public static final int ordinal = 2;
// some variables
}
}
}
If each enumeration would contain a single value, why not use that?
You can even add a method to retrieve some descriptive name:
enum General {
INCOME, SATIFACTION, EFFICIENCY;
int value = 0;
String getName() {
switch(this) {
case INCOME:
return "salary";
case SATIFACTION:
return "etc";
}
}
}
These can be set/get by General.values()[i].value and General.INCOME.value or add setValue(int value) and getValue() methods and make value private.
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");
}
}
}
}