I need to have the teams sortable by order of points, from most to least, i have that i have to write a new method and can make changes to the class header.
I was thinking of using this as my method, but it would put the teams in order of least to most :S so i dont know what way to fix it, also i dont know what changes i would need to make to the class header if any!
public void orderPoints()
{
List<String> points = new ArrayList<String>();
Collections.sort(points);
}
I know i can use Collections.max and min but unsure how i would filter the rest of the points in
Code for rest of the class
public class League
{ /* instance
variables */
private Team name;
private int points;
/**
* Constructor for objects of class League.
*/ public League(Team aname)
{
super();
name = aName;
points = 0; }
/**
* Returns the receiver's name Team
*/ public Team getName() {
return this.name; }
/**
* Returns the receiver's points
*/ public int getPoints() {
return points; }
/**
* Sets the receiver's points
*/ public void setPoints(int aPoints) {
this.points = aPoints; }
I'm not sure I understand what you're asking, but if you want to reverse the sorting of your List you can use Collections.sort(points, Collections.reverseOrder());
Related
This is my source code. I want to traverse a Vector using the Enumeration interface. If I simply traverse the Vector, I get hash codes of objects and if I implement interface Enumeration on the class Student I'm asked to override the nextElement() method. Can anyone tell me a way of overridding this method so that I get elements of class (i.e. name, r_num and cgpa) and not the hashcodes of objects?
import java.util.*;
public class Student implements Enumeration {
private String name;
private int r_num;
private float cgpa;
Student() {
}
Student(String name,int r_num,float cgpa)
{
this.name=name;
this.r_num=r_num;
this.cgpa=cgpa;
}
/**
* #return the name
*/
public String getName() {
return name;
}
/**
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* #return the r_num
*/
public int getR_num() {
return r_num;
}
/**
* #param r_num the r_num to set
*/
public void setR_num(int r_num) {
this.r_num = r_num;
}
/**
* #return the cgpa
*/
public float getCgpa() {
return cgpa;
}
/**
* #param cgpa the cgpa to set
*/
public void setCgpa(float cgpa) {
this.cgpa = cgpa;
}
public static void main(String[] args){
Vector<Student> studentList = new Vector<>();
Enumeration en;
System.out.println("Enter Students' Name, Roll Number and CGPA");
Scanner in= new Scanner(System.in);
char ch;
do
{
int x=0;
String s= in.next();
int r= in.nextInt();
float c= in.nextFloat();
studentList.add(new Student(s,r,c));
System.out.println("Enter another student's record?(y/n)");
ch= in.next().charAt(0);
}
while(ch=='y'|| ch=='Y');
System.out.println("List of Students: ");
en = studentList.elements();
while(en.hasMoreElements()){
System.out.println(en.nextElement());
}
}
#Override
public boolean hasMoreElements() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public Object nextElement() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
I want to traverse a Vector using the Enumeration interface.
No, you don't. You want to traverse a List, quite possibly an ArrayList, using the Iterable and Iterator interfaces. Vector and Enumeration are very old fashioned and almost certainly not what you want.
If I simply traverse the Vector, I get hash codes of objects.
No, you don't. You get the actual objects. The problem is, your class doesn't override the toString() method, so when you print them out with System.out.println you get the default toString() format of java.lang.Object, which looks like Student#DEADBEEF.
Add a toString() method to Student, such as:
#Override
public String toString() {
return name + " " + r_num + " " cgpa;
}
If you really want to implement Enumeration, take a look at the source code that comes with the JDK to see how classes like Vector and ArrayList implement it. But it doesn't make sense to have Student implement it, since a Student isn't a collection of anything that you can enumerate.
It looks like your problem is that you didn't override toString(), and so the call to print out the next element is using the default toString(), which prints out a relatively unhelpful message (i.e. the "hashcode" you're referring to, or the class name, an at sign, and the location of the object in memory).
Furthermore, you shouldn't be implementing Enumeration if your Student class does not represent something which can be iterated over.
I am trying to write an if condition to check a value exists in a list containing many objects,
Here is my code:
List<TeacherInfo> teacherInfo=ServiceManager.getHelperService(TeacherManagementHelper.class, request, response).getTeacherInfoId();
if(teacherInfo.contains(inputParam))
{
out2.println("<font color=red>");
out2.println("Id Not Available");
out2.println("</font>");
}
else
{
out2.println("<font color=green>");
out2.println("Id Available");
out2.println("</font>");
}
after executing 1st sentence getTeacherInfoId() method successfully returns a list of objects, in those objects I want to check any object has a value same as inputParam. Is my above code right ? if wrong please help me .
contains(Object o) is internally based on equals between objects of your list and your input, as stated by the doc.
Since you said that inputParam is an integer, then the current state of your code can't work because you compare an integer to TeacherInfo objects, so they won't ever be equal. I believe you want to compare inputParam to one particular field of TeacherInfo objects.
If you're using Java 8, you can use the stream API instead of contains():
List<TeacherInfo> teacherInfo=ServiceManager.getHelperService(TeacherManagementHelper.class, request, response).getTeacherInfoId();
if (teacherInfo.stream().anyMatch(ti -> ti.getId() == inputParam)) {
// contains the id
} else {
// does not contain the id
}
For previous java versions, an alternative to contains() would be to iterate over your list and compare manually your integer to the TeacherInfo's field:
private static boolean containsTeacherId(List<TeacherInfo> teacherInfos, int id) {
for (TeacherInfo ti : teacherInfos) {
if (ti.getId() == inputParam) { // I used getId(), replace that by the accessor you actually need
return true;
}
}
return false;
}
Then:
List<TeacherInfo> teacherInfo=ServiceManager.getHelperService(TeacherManagementHelper.class, request, response).getTeacherInfoId();
if (containsTeacherId(teacherInfo, inputParam)) {
// contains the id
} else {
// does not contain the id
}
Note: If you don't need other information than the ID itself, I'd rather suggest to return the list of IDs from a method called getTeacherIds(), especially if this information comes from a DB.
No it won't work at all. you should iterate the 'teacherInfo' list and you need to override the compare()and hashvalue() of object class.
You would need to iterate over the list teacherInfo and compare each element of that list with inputParam.
Below is a small demo code that might help you.
I have created a testerInfo analogous to your teacherInfo and param analogous to your inputParam.
I hope it helps.
Tester.java
/**
*
*/
package com.demo;
/**
* #author Parul
*
*/
public class Tester {
private int id;
private String name;
/**
* #return the id
*/
public int getId() {
return id;
}
/**
* #param id the id to set
*/
public void setId(int id) {
this.id = id;
}
/**
* #return the name
*/
public String getName() {
return name;
}
/**
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
}
public Tester(int id, String name) {
this.id = id;
this.name = name;
}
public Tester() {
}
}
Demo.java
/**
*
*/
package com.demo;
import java.util.ArrayList;
import java.util.List;
/**
* #author Parul
*
*/
public class Demo {
public static void main(String [] args){
List<Tester> testerInfo=new ArrayList<Tester>();
testerInfo.add(new Tester(1,"Java"));
testerInfo.add(new Tester(2,"C++"));
testerInfo.add(new Tester(3,"Python"));
testerInfo.add(new Tester(4,"C"));
Tester tester=null;
int param=2;
for(int i=0;i<testerInfo.size();i++){
tester=testerInfo.get(i);
if(tester.getId()==param){
System.out.println("param found: "+tester.getName());
break;
}
}
}
}
OUTPUT
param found: C++
This is my first Java project.
So I'm working on my own simulation project, and some of my core stuff has gone awry. I have two classes I'm focusing on right now - settlement and townRey, which extends settlement.
The error is thrown when I try
System.out.println(townRey.returnStrength());
Here are my two relevant classes:
settlement:
public class settlement
{
//
//
// VARIABLES
//
//
/**
* The town's unique name.
*/
public String name;
/**
* The settlement's location in latitude (N-S)
*/
public int latitude;
/**
* The settlement's location in longitude (E-W)
*/
public int longitude;
/**
* What faction a town or village is aligned to. This determines production and consumption, mostly.
*/
public String faction;
/**
* What a specific village or town produces.
*/
public String[] production;
/**
* What a specific town consumes (villages don't consume)
*/
public String[] consumption;
/**
* How dangerous a specific town is with bandits
* A 1-10 scale, with 10 being the most dangerous.
* Any town with a danger over 8 can be raided and destroyed temporarily by bandits.
* Being raided successfully depends on the Strength of a town.
*/
public int danger;
/**
* How much a town takes in taxes.
*/
public float tax;
/**
* How easily a town is raided by bandits.
* If a bandit raid has a lower strength than the town, then the town wins.
*/
public int strength;
//
//
// METHODS
//
//
public int returnLatitude()
{
return latitude;
}
public int returnLongitude()
{
return longitude;
}
public String returnFaction()
{
return faction;
}
public String[] returnProduction()
{
return production;
}
public String[] returnConsumption()
{
return consumption;
}
public int returnDanger()
{
return danger;
}
public float returnTax()
{
return tax;
}
public int returnStrength()
{
return strength;
}
}
and townRey:
public class townRey extends settlement
{{
name = "Rey";
latitude = 5;
longitude = 5;
String faction = "Nord";
String[] production;
String[] consumption;
danger = 1;
tax = 0.05F;
strength = 6;
}}
EDIT:: Thanks for all the help! I fixed all issues now. Below is 'Settlement' and 'Start'.
public class Settlement
{
//
//
// VARIABLES
//
//
/**
* The town's unique name.
*/
public String name;
/**
* The settlement's location in latitude (N-S)
*/
public int latitude;
/**
* The settlement's location in longitude (E-W)
*/
public int longitude;
/**
* What faction a town or village is aligned to. This determines production and consumption, mostly.
*/
public String faction;
/**
* What a specific village or town produces.
*/
public String[] production;
/**
* What a specific town consumes (villages don't consume)
*/
public String[] consumption;
/**
* How dangerous a specific town is with bandits
* A 1-10 scale, with 10 being the most dangerous.
* Any town with a danger over 8 can be raided and destroyed temporarily by bandits.
* Being raided successfully depends on the Strength of a town.
*/
public int danger;
/**
* How much a town takes in taxes.
*/
public float tax;
/**
* How easily a town is raided by bandits.
* If a bandit raid has a lower strength than the town, then the town wins.
*/
public int strength;
//
//
// METHODS
//
//
public int returnLatitude()
{
return latitude;
}
public int returnLongitude()
{
return longitude;
}
public String returnFaction()
{
return faction;
}
public String[] returnProduction()
{
return production;
}
public String[] returnConsumption()
{
return consumption;
}
public int returnDanger()
{
return danger;
}
public float returnTax()
{
return tax;
}
public int returnStrength()
{
return strength;
}
}
and Start, where I create 'townRey' then access a bit of data in two different ways.
public class Start
{
public static void main(String[] args)
{
//Creates 'Rey'
Settlement townRey = new Settlement();
townRey.name = "Rey";
townRey.latitude = 5;
townRey.longitude = 5;
townRey.faction = "Nord";
townRey.danger = 1;
townRey.tax = 0.05F;
townRey.strength = 6;
//This calls the returnLongitude method from Settlement, and is the 'proper' way to do it.
System.out.println(townRey.returnLongitude());
//This also works.
System.out.println(townRey.longitude);
//Thanks for the help!
}
}
townRey shouldn't be extending settlement. You should be declaring it as an instance of settlement in some method, as follows:
townRey = new settlement();
townRey.name = "Rey";
...
townRey.strength = 6;
Or, better still, making a new constructor for settlement that takes the different fields as inputs.
Also, a style note: Generally, in Java, classes should begin with a capital letter, so Settlement rather than settlement might make a better name.
You should define a townRey object then use this object to call returnStrength
townRey mytownRey = new townRey();
System.out.println(townRey.returnStrength());
I expect you want townRey to be an instance of settlement, not a subclass. Unless you want to have multiple copies of townRey. Replace the line public class townRey extends settlement with settlement townRey = new settlement(), and add a semicolon after }}. Leave everything else the same.
public class mainclss()
{
public static void main(String arg[])
{
townRey= new settlement();
//you can do sth you like
}
}
create a new class to check.DO NOT start Java with Class!It is a little difficult.
Create a separate class with main() method. Inside this method, you should create an object of townRey, in order to access the method returnStrength(). You can't access it using the class name 'townRay' if you are doing so. So Add this class with the code below:
public class MainClass {
public static void main(String[] args) {
townRey tr = new townRey();
System.out.println( tr.returnStrength () );
}
}
This worked fine with me. So you can safely use it.
NOTE: You should learn by practice to start each word in your class name with a capital letter such as Settlement and TownRey. Good Luck!
I am having problems storing and printing a list array which uses threads. I want to store the list of threads in a list array and print them to a text area where they can be sorted by a user. The code below is my array class and transaction class.
import java.util.ArrayList;
/**
* #author B00533474
*/
public class Array {
ArrayList<Transaction> transactionList = new ArrayList<Transaction>();
// Variables
private final Transaction nextTransaction;
public static int inInt2 = TranAcc.inInt2;
public static int inInt3 = TranAcc.inInt3;
public static String inInt1 = TranAcc.inInt1;
//public static void main(String[] args){
public Array(){
nextTransaction = new Transaction(inInt1, inInt2, inInt3, 2000);
transactionList.add(nextTransaction);
transactionList.get(3);
}
/*public static void main(String[] args){
Array ar = new Array();
ar.add(nextTransaction);
}
*
*/
}
The variables inInt1 etc are from another class called TranAcc which is the main GUI of my project.
package bankassig;
/**
*
* #author B00533474
*/
public class Transaction {
String type;
int amount;
int wkNum;
int balance;
public Transaction(String ty, int am, int wk, int bal)
{
type = ty;
amount = am;
wkNum = wk;
balance = bal;
}
}
My problem is actually implementing/using the list area, I was going to add an action listener to a button on a gui which would call the list area and print the transactions in a text are but I was unsure of the code to write for this ( I know about the action listener just not calling the list array).
Any help would be much appreciated and if I need to provide anymore code I would be happy to do so.
How do I implement the list array and use it to print out the values of the variables which I used?
Overwrite the inherited (from java.lang.Object) toString() method in your Transaction class. In your toString() method, you can put together a String with your variable data in any format that makes sense to a user, and return it. You can then iterate through all the Transactions in your Array class's list, call the toString() method, and put it in your GUI. Something like:
for (Transaction trans : yourArrayObj)
{
yourTextArea.append(trans.toString());
}
After developing in PHP for a long time I have decided to step into Java. Comfortable in OOP methodology and all that, I'm trying to start off at that point within java, but I'm getting hung up on passing out my arraylist object into a for statement to be printed back out using the Item class methods.
HelloInvetory.java
package helloInventory;
import java.util.Arrays;
public class HelloInventory {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Object InvetoryItems;
Inventory inv = new Inventory();
inv.createItemObj(101, "camera", "Used camera that I bought off of a homeless guy.", 500);
InvetoryItems = inv.getAllInventoryItems();
for(Object item : InvetoryItems){
System.out.println(item.getItemName());
}
System.out.println("Done");
}
}
Inventory.java
package helloInventory;
import java.util.*;
/**
* Tracks and maintains all items within the inventory
* #author levi
*
*/
public class Inventory {
List<Object> InventoryItems = new ArrayList<Object>();
/*
* create object from Items class
* and insert into Object[] array.
*/
public void createItemObj(int sku, String name, String descriptor, float price) {
Items item = new Items();
item.setSku(sku);
item.setItemName(name);
item.setItemDescription(descriptor);
item.setItemPrice(price);
this.setInventoryItems(item);
}
public Object getAllInventoryItems() {
//return InventoryItems;
return this.InventoryItems.toArray();
}
public void setInventoryItems(Object inventoryItems) {
//InventoryItems.add(inventoryItems);
this.InventoryItems.add(inventoryItems);
}
}
Items.java
package helloInventory;
/**
* Class object to hold each item details
* #author levi
*
*/
public class Items {
int sku;
String itemName;
String itemDescription;
float itemPrice;
public int getSku() {
return sku;
}
public void setSku(int sku) {
this.sku = sku;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public String getItemDescription() {
return itemDescription;
}
public void setItemDescription(String itemDescription) {
this.itemDescription = itemDescription;
}
public float getItemPrice() {
return itemPrice;
}
public void setItemPrice(float itemPrice) {
this.itemPrice = itemPrice;
}
}
Where I am stuck is within the HelloInventory.java
for(Object item : InvetoryItems){
System.out.println(item.getItemName());
}
IDE (Eclipse) gives me the error "Can only iterate over an array or an instance of java.lang.Iterable". Is there something extra I need, or I'm I going around this totally the wrong way in Java? Correct example would be helpful.
Best,
Levi
You have a very strange architecture here my friend. You shouldn't be using generic Objects everywhere, but the actual types. First thing:
public Object getAllInventoryItems() {
//return InventoryItems;
return this.InventoryItems.toArray();
}
Why not just return the List itself?
public List<Item> getAllInventoryItems() {
return this.InventoryItems;
}
Also change this:
List<Item> InventoryItems = new ArrayList<Item>();
and this:
public void setInventoryItems(Item inventoryItems) {
this.InventoryItems.add(inventoryItems);
}
Now iterating the List is smooth sailing:
public static void main(String[] args) {
// TODO Auto-generated method stub
List<Item> InvetoryItems;
Inventory inv = new Inventory();
inv.createItemObj(101, "camera", "Used camera that I bought off of a homeless guy.", 500);
InvetoryItems = inv.getAllInventoryItems();
for(Item item : InvetoryItems){
System.out.println(item.getItemName());
}
System.out.println("Done");
}
Btw, I changed Items to Item out of habit. A class name should indicate a single entity so by convention it's singular.
Now don't take this the wrong way, but you may have got off on the wrong foot with Java, so I highly recommend this reading: http://www.mindview.net/Books/TIJ/ This worked for me when I was starting with Java, maybe others can suggest some good sources as well.
Ok, two things. One is that Tudor is absolutely right, it's best to use the classes you're expecting directly, not Objects, and stylistically his points are accurate too.
Two is that if you really have to use a list of object, you'll need to cast back from object to whatever type it is that you're expecting to receive.
List<Object> list = inv.getAllInventoryItems();
for (Object item : list){
System.out.println((Items) item).getItemName();
}
However, I wouldn't recommend doing this as it effectively takes what should be a compile-time error and makes it a RunTime error (if the class cannot be cast).