For my assignment, the our programs are tested by running them through the command line, as they take arguments in the forms of file names, so I have to make sure my program runs when run through the command line. When I compile it without issue through jGrasp and eclipse, but when I attempt to compile it through the command line, this is what I get:
Cleary.java.35: error: cannot access T Collections.sort(studentObjects, idSorter);
class file for T not found
I don't know what T is, and I've never used T as a class in my programs?
Relevant code:
Main Class:
package ClearyAssignment5;
import java.util.Scanner;
import java.util.ArrayList;
import java.io.*;
import java.util.*;
public class Cleary {
public static void main(String[] args) {
//import the input file and add each line to an ArrayList of the students
try{
File input = new File(args[0]);
Scanner source = new Scanner(input);
ArrayList<String> listOfStudents=new ArrayList<String>();
while(source.hasNextLine()){
listOfStudents.add(source.nextLine());
}
ArrayList<Student> studentObjects = new ArrayList<Student>();
StudentIDComparator idSorter = new StudentIDComparator();
Collections.sort(studentObjects, idSorter);
FileWriter writer = new FileWriter(args[1]);
PrintWriter printWriter = new PrintWriter(writer);
for(int i=0;i<listOfStudents.size();i++){
(studentObjects.get(i)).printStudent(printWriter);
}
printWriter.close();
} catch(Exception e) {
System.out.println("Usage: ClearyAssignment4.Cleary input_file output_file");
}
}
}
Student Class:
package ClearyAssignment5;
import java.io.*;
import java.util.ArrayList;
import java.lang.*;
import jva.util.*;
public class Student {
//Initialize varaibles
String name;
int ID;
float GPA;
public Student(String studentName, int studentID, float studentGPA){
//Take the parameters which are passed in, and set them to the variables.
name = studentName;
ID = studentID;
GPA = studentGPA;
}
public int getID() {
return ID;
}
}
Comparator Class:
package ClearyAssignment5;
import java.util.*;
import java.lang.*;
import java.io.*;
class StudentIDComparator implements Comparator<Student> {
public int compare(Student a, Student b) {
return a.ID - b.ID;
}
}
I've removed some of the code which doesn't seem necessary for brevity... any help would be appreciated!
TL;DR: T is a generic type param that javac choked on somehow
T is a conventional name given to a Generic Type Parameter, which is used for Java's Generics system*. I'm not sure why the compiler choked on it, but the generics system in general has some occasional weird hiccups.
*An explanation of Generics (in case you haven't heard of them)
Imagine you are writing a class to hold a list of students. You want to be able to query if a person is on that list, as well as add people to that list. For now, this class will represent a course roster, so that professors can ensure that nobody is sneaking into their classes. Here is what the class will look like:
public class StudentList {
public boolean isOnList(Student s) { ... }
public void addToList(Student s) { ... }
}
Then imagine you need to create a new version of this class for the staff party at the end of the year, because only some staff are eligible (those who passed their performance review).
public class StaffList {
public boolean isOnList(Staff s) { ... }
public void addToList(Staff s) { ... }
}
Next, somebody asks you to create a new version of this class to keep track of the TAs for a course, since you can only pass assignments to grade to eligible TAs. You'd create yet another class:
public class TAList {
public boolean isOnList(TA t) { ... }
public void addToList(TA t) { ... }
}
You eventually get tired of writing such similar classes, so you want to create a single class which can perform all these functions. You would do so using Generics, so that client code can make a PersonList<Student> to hold Students, a PersonList<Staff> to hold Staff, a PersonList<TA> to hold TAs, and any other type of class you want.
public class PersonList<T> {
public boolean isOnList(T t) { ... }
public void addToList(T t) { ... }
}
The T is a generic type parameter here. When creating an instance of the class PersonList, you pass it a type inside the angle brackets. Then that type replaces all instances of T. The convention is to use single letter names, such as T for type, E for element, K for key, V for value, etc.
Well, I rewrote this program in a completely new directory, and it compiled and ran without issues. I don't know why that fixed it, but I guess it did.
Related
Hello everyone I am having trouble writing my program since it keeps giving me the error: Cannot Instantiate the type. I'm new to abstracts/implements so I suspect that to be the problem with this program. This is what I have so far:
import java.util.*;
import java.net.URL;
import java.math.BigInteger;
import java.net.URL;
import java.net.HttpURLConnection;
public class Program5 {
public abstract static class Animal implements Comparable<Animal>{
String OwnerName;
int birthYear;
public int billBalance;
String Species;
String feature;
public Animal() {}
public Animal(String OwnerName,int birthYear,int billBalance,String Species,String feature) {
this.OwnerName = OwnerName;
this.birthYear = birthYear;
this.billBalance = billBalance;
this.Species = Species;
this.feature = feature;
}
public void storeFile(Animal[] x) throws Exception{
BigInteger size = new BigInteger("1");
URL url=new URL("http://yoda.com/~pawang/CPS1/Program5_veterinarian_input.txt");
Scanner input = new Scanner(url.openStream());
HttpURLConnection conn;
conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("HEAD");
conn.getInputStream();
size = BigInteger.valueOf(conn.getContentLength());
while (input.hasNext()){
for(int i = 1;i<size.bitLength();i++) {
x[i] = new Animal();
String line = input.nextLine();
}
}
}
public int getBalance() {
return billBalance;
}
public static void sorts(Animal[] x) {
}
}
}
It seems the problem is on line 33 : x[i] = new Animal();
Abstract means that there is something in the class only declared, and never defined.
For example, image a class Person that is being created to be extended, and have a method doThings: let's say that we create Worker and Student classes, Worker on the doThings should work, instead Student should study, where instead Person doesn't have to do anything, but in order to have inheritance, and so do something like ArrayList<Person> and then on each element, call doThings, we must have a doThing method on each element, but as already said, Person doesn't have to do anything... so in the Person class we just declare the doThing method like this:
public void abstract doThing();
With this statement we are telling the JVM that whenever we have an object of this type, there is a doThing method, also if we don't implement this: and this is why you can't create a new object if the class is abstract, because something declared is never been implemented.
If you want to instantiate objects of that class, you should create a new class that is overriding the abstract methods.
This is just a brief explanation, there is a lot more behind and a lot more thing you can do with this.
I have a 2 class, one of which extends the superclass.
when I call the sub-class from the main, I get an error because "the method I call isn't a part of the class", but as my programme goes on, it should work
I had to use it only with the casting of class, but my teacher told me that casting should not be used in such a work, so please I'd like to understand where I'm wrong and where I can do better
(Im providing the code of 3 classes, the sub-class, the super-class, and the main)
Main
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Type in the number");
int number = in.nextInt();
System.out.print("Type in the name");
String name = in.next();
Test testObj = new Test(number);
testObj = new TestSub(number);
testObj.setNameSub(name);
in.close();
}
}
Super class
public class Test {
protected int number;
protected String name;
public Test(int number){
this.number=number;
}
public void setName(String name){
this.name=name;
}
public String toString(){
return "the name is "+name+"the number is "+number;
}
}
Sub Class
public class TestSub extends Test {
public TestSub(int number){
super(number);
}
public void setNameSub(String name){
setName(name);
}
public String toStringSub(){
return toString();
}
}
The error I get is this:
The method setNameSub(String) is undefined for the type Test
In the main where there is this instruction : testObj.setNameSub(name);
The error here is (as indicated in the comments) that you initialize testObj as Test instead of TestSub, causing the error when the compiler isn't able to find setNameSub() between Test's methods.
So the easy solution is clearly to initialize testObj as a TestSub.
The correct solution that takes advantage of the methods inheritance would be to keep the initialization as it is but to call the method testObj.setName(name) instead, and deleting setNameSub() and toString() methods from TestSub class since they don't add any difference from the methods in the Test class.
I have just started coding in java and am trying to wrap my head around classes.
I seem to be having trouble using a public attribute in another class. I have 3 classes: one contains the main method; and the other 2 are input and output. I am using non-static variables and methods and I don't want to use static.
Even though I have instantiated the input class in the output class, the output class fails to recognize the public attribute. Why is that so?
Here are the 3 classes:
package random;
import java.util.Scanner;
import java.util.Arrays;
public class random
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter your first name: ");
input inputObject = new input();
inputObject.setFirstName();
output outputObject = new output();
outputObject.getFirstName();
}
}
package random;
import java.util.Scanner;
public class input
{
public String firstName;
public input() {}
public void setFirstName() {
Scanner keyboard = new Scanner(System.in);
this.firstName = keyboard.nextLine();
}
}
package random;
import java.util.Scanner;
public class output
{
public void getFirstName()
{
input inputObject = new input();
System.out.println("Your first name is " + inputObject.firstName);
}
}
The input object created in the getFirstName method in the output class is a separate instance from the one created in your main method. This means essentially you are creating a new instance of input where the input isn't set for firstName yet so when you print out that property there is nothing to print.
In addition the get and set methods for a single property should be inside the same class. The general way of doing this is like this:
class Foo {
private String property = "";
Foo () {}; //empty default constructor
//sets the property to what is passed in as a parameter
public void setProperty(String newProperty) {
this.property = newProperty;
}
//returns the property
public String getProperty() {
return this.property;
}
}
Generally all class properties should be private with public setters and getters. If you are new to programming I suggest reading up on this more.
It's because you're using two different input objects. We can tell this because your program has the following line twice
input inputObject = new input();
The input object you assign a name to is a different object from the one you try to read the name from.
It makes no sense for the class output to exist at all. You should just have a method getFirstName() in the input class.
(Also class names in Java usually begin with a capital letter.)
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
There are two classes
first class is
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Collections;
public class Hieracrhy
{
ArrayList<Tutor> Tutor_person=new ArrayList<Tutor>();
public static void main(String[] args)
{
Hieracrhy obj=new Hieracrhy();
obj.start();
}
public void start()
{
getDetails();
System.out.println(Tutor_person);
}
//Function to read the songs from the file
void getDetails()
{
try
{
File file=new File("SongsList.txt");//Represents a file
FileReader fileReader=new FileReader(file);//FileReader connects to a text file
BufferedReader reader=new BufferedReader(fileReader);//For Efficient reading of file
// We use String variable to hold each line when the line is read one-by-one
String line=null;
//Read a line of the string and assign it to a string if it is not null just doo the func
while((line=reader.readLine())!= null)
{
addDetails(line);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
void addDetails(String lineToParse)
{
String[] tokens=lineToParse.split("/");
Tutor nextPerson=new Tutor(tokens[0]);
Tutor_person.add(nextPerson);
}
}
Now there is another class
import java.util.ArrayList;
public class Tutor
{
int Tutor_id;
String Tutor_name;
String Tutor_place;
int Tutor_age;
public void Set_Things_for_Tutor(int Tutor_id,String Tutor_name,String Tutor_place,int Tutor_age)
{
this.Tutor_id=Tutor_id;
this.Tutor_name=Tutor_name;
this.Tutor_place=Tutor_place;
this.Tutor_age=Tutor_age;
}
public int getuserid()
{
return Tutor_id;
}
public String getname()
{
return Tutor_name;
}
public String getdesignation()
{
return Tutor_place;
}
public int getage()
{
return Tutor_age;
}
}
Now there are inputs in a text file
11/devrath/hassan/22
but when i run the complete setup im getting the error
constructor tutor(string) is undefined
What is the reason for this error ..... can someone help me with a good i/p on this
Thanks
constructor tutor(string) is undefined
The error says it all.There is no constructor in your Tutor class which accepts string as an argument.
public Tutor {
//instance vars
public Tutor(String s){
//assign s to appropriate member variable
}
}
Btw, the design of the Tutor class seems bad. you initialize you instance members in your constructor(which ther are meant to do). you are currently initializing Tutor state in a method. i'd advice you to initialize them in the constructor.
Since you have not defined any constructor with "String" parameternthe JVM is unable to find it.
Define the constructor as follows:
public Tutor(String name)
{
//Do required initialization here
}
Well I think you have to rename Set_Things_for_Tutor to Tutor in your Tutor class. And remove the void string.
Your Tutor class does not have a constructor that accepts String as its parameter. if you want to pass a String in your Tutor class then add this to your code
public class Tutor{
//Other member variables
public Tutor(String yourString){
//Do some initializations
}
}
when you create an instance of a class , the constructor is called
MyClass obj = new MyClass();
this calls the default constructor
public MyClass(){}
but since you haven't made any parameterized consstructor
then JVM itself creates it for you
but if you want to pass some parameter to the constructor
MyClass obj = new MyClass(someInteger,someString);
in this case , JVM doent create any default constructor as you already have created a parameterized constructor
public MyCLass(int someInteger,String someString){}
in your case , you have not made any constructor ,
thus JVM only creates the default constructor
public MyClass(){}
so all you have is a non parameterized constructor
but what you are trying to access is a parameterized constructor
so all you have to do is to create a parameterized constructor in the class whose object are you creating ...
in your case
public Tutor(String string) {
System.out.println("add the code to initialize the class parameters here");
}
you calling code has one argument constructor and called code (Tutor) class doesn't have one argument constructor.
add constructor
public Tutor (String str)
{
//do your initialization here about 'str' variable.
}
I have one class that declares an enumeration type as:
public enum HOME_LOAN_TERMS {FIFTEEN_YEAR, THIRTY_YEAR};
Is this type usable in another class? I'm basically trying to complete a homework assignment where we have two types of loans, and one loanManager class. When I try to use the HOME_LOAN_TERMS.THIRTY_YEAR in my loanManager class that does not extend or implement the loan class, I get an error saying it 'cannot find symbol HOME_LOAN_TERMS.' So I did not know if my loanManager class needed to implement the two different loan classes. Thanks.
I'm currently working on this so I know it's not complete, but here is where I tried to use it:
import java.util.ArrayList;
public class AcmeLoanManager
{
public void addLoan(Loan h)
{
loanArray.add(h);
}
/*
public Loan[] getAllLoans()
{
}
public Loan[] findLoans(Person p)
{
}
public void removeLoan(int loanId)
{
}
*/
private ArrayList<Loan> loanArray = new ArrayList<Loan>(5);
public static void main(String[] args)
{
AcmeLoanManager aLoanManager = new AcmeLoanManager();
Person aPerson = new Person("Crystal", "Twix", "619-111-1234", "ct#yahoo.com");
HomeLoan aHomeLoan = new HomeLoan(aPerson, 400000, 5, HOME_LOAN_TERMS.THIRTY_YEAR);
aLoanManager.addLoan(aHomeLoan);
}
}
You have to specify the type:
HOME_LOAN_TYPES type = HOME_LOAN_TYPES.FIFTEEN_YEAR;
By the way, don't use this naming convention for enums. Use the same camel case you do for classes so:
public enum HomeLoanType {
FIFTEEN YEAR,
THIRTY_YEAR
}
If you don't want to specify the type you can do a static import:
import static package.name.HomeLoanType.*;
...
HomeLoanType type = FIFTEEN_YEAR;
Lastly, one of the best things about Java enums is they can have state and behaviour. For example:
public enum HomeLoanType {
FIFTEEN YEAR(15),
THIRTY_YEAR(30);
private final int years;
HomeLoanType(int years) {
this.year = years;
}
public int getYears() {
returns years;
}
}
Yes, since it's public you can use it from another class.
If it's in your Loan class you write Loan.HOME_LOAN_TERMS.FIFTEEN_YEAR to refer to it from a different class.