Storing an object in an array of objects - java

I'm trying to link the trainee object with the training session object, but this error shows up: TrainingSession cannot be converted to TrainingSession[] (it's in the last line).
I can't use an array list or anything similar because I have to follow the UML diagram in the assignment. I have used the following variables sessionName, traineeNo, and sessionNo to know which trainee and training session I'm dealing with.
public class Trainee extends Person {
private TrainingSession [] ST;
public TrainingSession [] getST() {
return ST;
}
public void setST(TrainingSession [] ST) {
this.ST = ST;
}
}
public class TrainingSession {
private int trainingSessionID;
public int getTrainingSessionID() {
return trainingSessionID;
}
public void setTrainingSessionID(int trainingSessionID) {
this.trainingSessionID = trainingSessionID;
}
}
public class TMS2 {
public static void main(String[] args)
throws FileNotFoundException, ParseException {
File file = new File("input.txt");
Scanner read = new Scanner(file);
Trainee [] trainee = new Trainee[15];
int traineeID = read.nextInt();
int trainingSessionID = read.nextInt();
String sessionName = TrainingSession(trainingSession, trainingSessionID);
int traineeNo = TraineeNo( trainee, traineeID);
int sessionNo = SessionNo( trainingSession, sessionName);
trainee[traineeNo].setST(trainingSession[sessionNo]);
}
}

trainingSession[sessionNo] is a TrainingSession object, not an array.
Perhaps you're looking for something like...
trainee[traineeNo].setST(new TrainingSession[] { trainingSession[sessionNo]});

Related

Sort an Object list with Collections having only list as parameter in Java

I have an assignment says printing a object list with given main class:
public static void main(String[] args) throws IOException {
ArrayList<LoaiPhong> ds = new ArrayList<>();
Scanner in = new Scanner(new File("xx.in"));
int n = Integer.parseInt(in.nextLine());
while(n-->0){
ds.add(new LoaiPhong(in.nextLine()));
}
Collections.sort(ds); //this only include object list
for(LoaiPhong tmp : ds){
System.out.println(tmp);
}
}
static class LoaiPhong {
String line;
public LoaiPhong(String line) {
this.line = line;
}
}
So that's mean i have to do something outside the main class to sort the list. Can anyone suggest what to do to sort the object list by its property?
Edit: Thanks to Gus i have the answer, the new class look something like this
static class LoaiPhong implements Comparable<LoaiPhong> {
...
#Override
public int compareTo(LoaiPhong_.LoaiPhong o) {
return <Some logic here>;
}
}

Java string array with setter getter

I wanted to create a simple program for user to insert 3 strings to a private string array in a class and then print it back by creating a new object using object reference but I think I am facing problem in the setter/getter.(Pretty new to class and setter/getter) Here is what I have so far:
import java.util.Scanner;
public class Stringtest {
public static void main(String[] args)
{ Scanner input=new Scanner(System.in);
Stringer Strung=new Stringer();
System.out.println("Strings:"+Strung.print());
}
}
class Stringer
{ Scanner input=new Scanner(System.in);
private String[] aa=new String[3];
aa[0]="zero";
aa[1]="one";
aa[2]="two";
Stringer()
{}
{ System.out.println("Please enter 3 strings:");
for(int i=0;i<4;i++)
{
aa[i]=input.next();
}
}
public void setaa(String[] a)
{
aa=a;
}
public String[] getaa()
{
return aa;
}
public void print(String[] a)
{
for(int b=0;b<4;b++)
{
System.out.printf("%s",a[b]);
}
}
}
Due to populating the array while creating a class instance, you don't require any setters. The only getter requires.
Divide the logic from the runner.
Always use array.length() while looping or use a simple for loop otherwise you'll be getting an indexOfBoudException error.
Didn't get why you are using printf() while printing results.
My solution:
import java.util.Scanner;
public class App {
public static void main(String[] args) {
App.run();
}
private static void run() {
Stringer stringer = new Stringer();
stringer.print(stringer.getStrings());
}
}
class Stringer {
private String[] strings = new String[3];
Stringer() {
System.out.println("Please enter 3 strings:");
for (int i = 0; i < 4; i++) {
Scanner scanner = new Scanner(System.in);
strings[i] = scanner.next();
}
}
String[] getStrings() {
return strings;
}
void print(String[] strings) {
System.out.println("Strings are:");
for (String string : strings) {
System.out.println(string);
}
}
}

Is it possible in java to get multiple inputs in a single line??

I am trying to get multiple inputs in a single code of line..
for example in c++, we could have it like -
int a,b,c;
cin>>a>>b>>c;
is it possible in java also??
You can use an array for this purpose, like:
public static void main(String[] args) {
int[] values = new int[3];
Scanner in = new Scanner(System.in);
for(int i = 0; i < values.length; i++) {
values[i] = in.nextInt();
}
System.out.println(Arrays.toString(values));
}
UPDATE 2
In java 8 the above solution can have a shorter version:
Scanner in = new Scanner(System.in);
Integer[] inputs = Stream.generate(in::nextInt).limit(3).toArray(Integer[]::new);
UPDATE 1
There is another way, which is closer to cin:
public class ChainScanner {
private Scanner scanner;
public ChainScanner(Scanner scanner) {
this.scanner = scanner;
}
public ChainScanner readIntTo(Consumer<Integer> consumer) {
consumer.accept(scanner.nextInt());
return this;
}
public ChainScanner readStringTo(Consumer<String> consumer) {
consumer.accept(scanner.next());
return this;
}
}
public class Wrapper {
private int a;
private int b;
private String c;
public void setA(int a) {
this.a = a;
} /* ... */
}
public static void main(String[] args) {
ChainScanner cs = new ChainScanner(new Scanner(System.in));
Wrapper wrapper = new Wrapper();
cs.readIntTo(wrapper::setA).readIntTo(wrapper::setB).readStringTo(wrapper::setC);
System.out.println(wrapper);
}

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
}
}

Why can I not make an instance of a local Java class in side of a Java WebMethods Services?

I need to be able to create an instance of the following class in my web Services Method and for some reason there is an error.
Question: Why would I not be able to declare and instance of my class in my Java WEBServices?
**GetTheFileListClass FindArrayListOfFiles = new GetTheFileListClass(fileName);**
Error:
The source was saved, but was not compiled due to the following errors:
C:\SoftwareAG\IntegrationServer\packages\DssAccessBackup\code\source\DssAccessBackup\services\flow.java:48: non-static variable this cannot be referenced from a static context
GetTheFileListClass FindArrayListOfFiles = new GetTheFileListClass(fileName);
1 error
Code:
public final class ReturnListOfValidFileNames_SVC
{
/**
* The primary method for the Java service
*
* #param pipeline
* The IData pipeline
* #throws ServiceException
*/
public static final void ReturnListOfValidFileNames(IData pipeline)
throws ServiceException {
IDataCursor pipelineCursor = pipeline.getCursor();
String fileName = IDataUtil.getString(pipelineCursor,"FileName");
ArrayList<String> listOfFileName = new ArrayList<String>();
//This will get the file list and set it to the local parameter for the Service
**GetTheFileListClass FindArrayListOfFiles = new GetTheFileListClass(fileName);**
listOfFileName = FindArrayListOfFiles.getMyFileList();
IDataUtil.put( pipelineCursor,"ListOfFileNames",listOfFileName.toArray());
pipelineCursor.destroy();
}
// --- <<IS-BEGIN-SHARED-SOURCE-AREA>> ---
public class GetTheFileListClass {
String fileName = new String();
ArrayList<String> MyFileList = new ArrayList<String>();
String InputFile = new String();
GetTheFileListClass(String workFile){
setInputFile(workFile);
}
public void setMyFileList(ArrayList<String> myList, String newFileValueToAdd) {
myList.add(newFileValueToAdd);
}
public ArrayList<String> getMyFileList() {
return MyFileList;
}
public void setInputFile(String wFile) {
fileName = wFile;
}
public String getInputFile(){
return fileName;
}
private String returnFileName(String a) {
String matchEqualSign = "=";
String returnFile = new String();
int index = 0;
index = a.indexOf(matchEqualSign,index);
index++;
while (a.charAt(index) != ' ' && a.charAt(index) != -1) {
returnFile += a.charAt(index);
//System.out.println(returnFile);
index++;
}
return returnFile;
}
private void locatedFileName(String s, String FoundFile, ArrayList<String> myFileListParm) {
final String REGEX = ("(?i)\\./\\s+ADD\\s+NAME\\s*=");
Pattern validStringPattern = Pattern.compile(REGEX);
Matcher validRegMatch = validStringPattern.matcher(s);
boolean wasValidRegMatched = validRegMatch.find();
if (wasValidRegMatched) {
FoundFile = returnFileName(s); //OUTPUT variable should go here
setMyFileList(myFileListParm,FoundFile);
}
}
//This is the methods that needs to be called from the main method
private void testReadTextFile() throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String FileLine = null;
while ((FileLine = reader.readLine()) != null) {
locatedFileName(FileLine,fileName,MyFileList); //test to see if the "./ Add name=" is found in any of the strings
}
}
private void printArrayFileList(ArrayList<String> myList) {
for (String myIndexFileListVariable : myList) {
System.out.println("File Name: " + myIndexFileListVariable);
}
}
}
// --- <<IS-END-SHARED-SOURCE-AREA>> ---
}
your inner class is not static, try
public static class GetTheFileListClass { ....
The rules of scope still apply, even though GetTheFileListClass is (a) a class and is (b) public. Because it is declared inside of ReturnListOfValidFileNames_SVC, that is its enclosing class, so any non-static reference to it must follow the rules of scope.
So you have two options (I'm using main to simulate your static method):
Declare the inner class static:
public final class Outer {
public static void main(String[] args) {
Inner inner = new Inner ();
inner.doIt();
}
public static class Inner {
public void doIt() {
System.out.println("Do it");
}
}
}
OR
Within your static method, create an instance of the enclosing class and use the new operator on it like this
public final class Outer {
public static void main(String[] args) {
Outer outer = new Outer();// Now we have an enclosing instance!
Inner inner = outer.new Inner ();
inner.doIt();
}
public class Inner {
public void doIt() {
System.out.println("Do it");
}
}
}
Have fun!

Categories