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");
}
}
}
}
Related
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++;}
I am trying to sort an ArrayList in increasing order in reference to a certain variable. This is the problem question.
q5: Create a public class named Snow with private instance variables vast, prior, ethnic, and remarkable each of type int. You may add any other methods and variables you'd like to this class.
Outside of Snow (in the Problem Set class) write a public static method named sortSnow that takes an ArrayList of Snows as a parameter and returns void. This method will sort the input by the variable remarkable in increasing order
This is what I wrote.
public class snow implements Comparable<snow> {
private int vast;
private int prior;
private int ethnic;
private int remarkable;
public snow( int vast , int prior, int ethnic ,int remarkable) {
this.vast=vast;
this.prior = prior;
this.ethnic = ethnic;
this.remarkable = remarkable;
}
public int getEthnic() {
return ethnic;
}
public void setEthnic(int ethnic) {
this.ethnic = ethnic;
}
public int getPrior() {
return prior;
}
public void setPrior(int prior) {
this.prior = prior;
}
public int getVast() {
return vast;
}
public void setVast(int vast) {
this.vast = vast;
}
public int getRemarkable() {
return remarkable;
}
public void setRemarkable(int remarkable) {
this.remarkable = remarkable;
}
public int compareTo(snow compareSnow) {
// TODO Auto-generated method stub
int compareThese = ((snow) compareSnow).getRemarkable();
//ascending order
return this.remarkable - compareThese;
}
}
public static void sortSnow(ArrayList<snow>input){
Collections.sort(input);
}
I am not understanding what the error means. The autolab is giving me this error:
Could not find class submission.ProblemSet$Snow
Java is case sensitive i.e. snow is not Snow is not sNoW. Rename your class to Snow and try again. Also, it is ArrayList and not arraylist.
Then to sort a List, you can use Collections.sort.
I think this is you want to achieve
Save below code in file called "Snow.java" compile it and try to run it.
import java.util.ArrayList;
import java.util.Collections;
//As ".java" file can contain only single public java class
//I made Problem set class non-public so we can use its main method
//to run and see output
class ProblemSet {
public static void main(String[] args) {
Snow one = new Snow(1,1,1,1);
Snow two = new Snow(1,1,1,2);
Snow three = new Snow(1,1,1,3);
Snow four = new Snow(1,1,1,4);
Snow five = new Snow(1,1,1,5);
Snow six = new Snow(1,1,1,6);
ArrayList arrayList = new ArrayList();
arrayList.add(one);
arrayList.add(three);
arrayList.add(five);
arrayList.add(two);
arrayList.add(six);
arrayList.add(four);
System.out.println("Without sort");
System.out.println(arrayList);
sortSnow(arrayList);
System.out.println("With sort");
System.out.println(arrayList);
}
//this is your static method which takes argument as array list of Snow
//And it applies sorting logic based on compareTo method which you wrote
//in Snow class. As per java best practice Class name should start with
//Upper case letters and follow camel casing I renamed your class from
//"snow" to "Snow"
public static void sortSnow(ArrayList<Snow> input){
Collections.sort(input);
}
}
//This is you public class Snow
//If you want to keep it in separate java file put it
public class Snow implements Comparable<Snow> {
private int vast;
private int prior;
private int ethnic;
private int remarkable;
public Snow(int vast, int prior, int ethnic, int remarkable) {
this.vast = vast;
this.prior = prior;
this.ethnic = ethnic;
this.remarkable = remarkable;
}
public int getEthnic() {
return ethnic;
}
public void setEthnic(int ethnic) {
this.ethnic = ethnic;
}
public int getPrior() {
return prior;
}
public void setPrior(int prior) {
this.prior = prior;
}
public int getVast() {
return vast;
}
public void setVast(int vast) {
this.vast = vast;
}
public int getRemarkable() {
return remarkable;
}
public void setRemarkable(int remarkable) {
this.remarkable = remarkable;
}
public int compareTo(Snow compareSnow) {
// TODO Auto-generated method stub
int compareThese = ((Snow) compareSnow).getRemarkable();
//ascending order
return this.remarkable - compareThese;
}
//This is added because when you use array list to print
//it will print remarkable of particular Snow object
#Override
public String toString() {
return String.valueOf(remarkable);
}
}
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 need to take a collection of objects using the CompareTo() command, and then have these stored in a list, and then use the collections.sort() command to sort them alphabetically by last name, then by first name if the last name isn't strong enough, and then print off the entire list at the end.
This is the code I have so far:
package sortlab;
import java.io.*;
import java.util.*;
public class SortLab {
public static void main(String[] args) throws Exception {
File youSaidUseOurRelativeFileNameForStudentData =
new File("C:/My192/SortLabProj/src/sortlab/student.data");
Scanner sc = new Scanner(youSaidUseOurRelativeFileNameForStudentData);
ArrayList<Student> StudentList = new ArrayList<Student>();
while (sc.hasNextLine()) {
Student testStudent = new Student(sc.next(), sc.next(), sc.next());
sc.nextLine();
StudentList.add(testStudent);
}
}
}
And the next class:
package sortlab;
import java.util.*;
class Student implements Comparable<Student> {
private String first;
private String last;
private String address;
public Student(String f, String l, String a) {
first = f;
last = l;
address = a;
}
#Override
public int compareTo(Student other) {
if (last.hashCode() > other.last.hashCode()) return 1;
if (last.hashCode() < other.last.hashCode()) return -1;
if (first.hashCode() > other.first.hashCode()) return 1;
if (first.hashCode() < other.first.hashCode()) return -1;
return 0;
}
}
If you want to compare them ASCIIbetically use the String.compareTo method. It would never occur to me to compare hashCodes.
If you want to ignore case, you can use String.compareToIgnoreCase
First of all I would add getters for first and last name. Then try this code:
#Override
public int compareTo(Student other) {
int result = l.compareTo(other.getLastName());
if (result == 0) {
return f.compareTo(other.getFirstName());
} else {
return result;
}
}
Then add a toString() method to your Student class:
#Override
public String toString() {
return f+" "+l+", "+a;
}