I have these monsters in the LinkedList and it iterates through it. In addition to that I want my output to look like this:
Screaming-Monster "Bob" with fightingpower 1
Fighting-Monster "Tom" with fightingpower 6
Fighting-Monster "Dave" with fightingpower 7
Scream-Fight-Monster "Steve" with fightingpower 3
How do I archieve this?
public class AdventureGame {
public static void main(String[] args) {
LinkedList <String> monsterList = new LinkedList <String>();
monsterList.add("Screaming-Monster \"Bob\"");
monsterList.add("Fighting-Monster \"Tom\"");
monsterList.add("Fighting-Monster \"Dave\"");
monsterList.add("Scream-Fight-Monster \"Steve\"");
for(int i=0; i<monsterList.size(); i++){
System.out.println(monsterList.get(i));
}
}}
You need to associate the 'fighting power' value with the monster, but you don't do this in your program. Values that relate to each other should be stored together. How about a class to represent a monster:
class Monster {
private String name;
private int fightingPower;
public Monster(String name, int fightingPower) {
this.name = name;
this.fightingPower = fightingPower;
}
public String getName() {
return name;
}
public int getFightingPower() {
return fightingPower;
}
}
Then you could make a list of Monsters like this:
LinkedList<Monster> monsterList = new LinkedList <Monster>();
monsterList.add(new Monster("Screaming-Monster \"Bob\"", 1));
monsterList.add(new Monster("Fighting-Monster \"Tom\"", 6));
monsterList.add(new Monster("Fighting-Monster \"Dave\"", 7));
monsterList.add(new Monster("Scream-Fight-Monster \"Steve\"", 3));
and you could print them out like this:
for(int i = 0; i < monsterList.size(); i++){
Monster monster = monsterList.get(i);
System.out.println(monster.getName() + " with fightingpower " + monster.getFightingPower());
}
Try creating a monster class that looks like this:
private String type;
private String name;
private int fightingpower;
monster(String type, String name, int fightingpower) {
this.type = type;
this.name = name;
this.fightingpower = fightingpower;
}
public String getStats() {
String stats = this.type + " \"" + this.name + "\" with fightingpower " + this.fightingpower;
return stats;
}
then in your class with your LinkedList do:
LinkedList <monster> monsterList = new LinkedList <>();
monsterList.add(new monster("Screaming-Monster", "Bob", 1))
//Repeat for every monster you want to have
for (int i = 0; i < monsterList.size(); i++) {
System.out.println(monsterList.get(i).getStats());
}
Further to #matt's fine answer, and as the title of your question is "LinkedList iterating", I'd like to point out that you should use a for-each loop to iterate over a linked list:
for (Monster monster : monsterList) {
System.out.println(monster.getName() + " with fightingpower "
+ monster.getFightingPower());
}
Using a for-each loop is O(n), while using an index and get() is O(1/2 n * n)
Related
I'm trying to find who are all having the greatest number and give the gift to persons who are having the greatest number.Consider if there are 4 persons.Get the input no as n1,n2,n3,n4.Then check which person have the greatest no and give gift to them.I just tried to find the greatest among 4 numbers.
int great=0;
if (n1 >= n2 && n1 >= n3 && n1>=n4)
great=n1;
else if (n2 >= n1 && n2 >= n3 && n2>=n4)
great=n2;
else if(n3>=n1 && n3>=n4)
great=n3;
else
great=n4;
if suppose 3 persons have same highest no then give the gift for 3 persons.Print the output as "Good you got a gift" along with the name of the persons who has greatest no with them.
first find the max value:
int[] all = new int[] { n1, n2, n3, n4 };
int max = -1;
for (int i=0; i<all.length; i++) {
if (max < all[i) {
max = all[i];
}
}
then see who has the max value and print their index, name or whatever
for (int i=0; i<all.length; i++) {
if (max == all[i) {
System.out.println ("Good you got a gift " + i);
}
}
Integer[] a = {105, 30, 40, 110};
Arrays.sort(a, Collections.reverseOrder());
int great = a[0];
System.out.println("Good you got a gift: "+ great);
try this out
Maybe this can work for you. I think you should go for a class Person which have name and number because at the end you want to show the name of the people with the highest number.
/**
* Class representing each person
*/
public class Person{
private final String name;
private final Integer number;
Person(String name, Integer number)
{
this.name = name;
this.number = number;
}
public String getName() {
return name;
}
public Integer getNumber() {
return number;
}
#Override
public String toString() {
return name;
}
}
This is another class. Please create another file for it.
public class Main{
/**
* This is the main method
*/
public static void main(String[] args) {
List<Person>all = new ArrayList<>();
all.add(new Person("P1", 5));
all.add(new Person("P2", 2));
all.add(new Person("P3", 3));
all.add(new Person("P4", 5));
Integer max = findMaxNumber(all);
List<Person> winners = findWinners(all, max);
System.out.print("Good you got a gift: " + winners);
}
private static Integer findMaxNumber(List<Person> all) {
Integer max = 0;
for(Person onePerson : all)
{
Integer onePersonNumber = onePerson.getNumber();
if(onePersonNumber > max)
{
max = onePersonNumber;
}
}
return max;
}
private static List<Person> findWinners(List<Person> all, Integer max) {
List<Person>winners = new ArrayList<>();
for(Person onePerson : all)
{
if(onePerson.getNumber().equals(max))
{
winners.add(onePerson);
}
}
return winners;
}
}//end of Main Class
-------------------------------------------------------------------
This is a second solution. It is much like the first one just using lambda expressions.
/**
* Class representing each person
*/
public class Person{
private final String name;
private final Integer number;
Person(String name, Integer number)
{
this.name = name;
this.number = number;
}
public String getName() {
return name;
}
public Integer getNumber() {
return number;
}
#Override
public String toString() {
return name;
}
}
This is another class. Please create another file for it.
public class Main{
/**
* This is the main method
*/
public static void main(String[] args) {
List<Person>all = new ArrayList<>();
all.add(new Person("P1", 5));
all.add(new Person("P2", 2));
all.add(new Person("P3", 5));
all.add(new Person("P4", 5));
Integer max = findMaxNumber(all);
List<Person> winners = findWinners(all, max);
System.out.print("Good you got a gift: " + winners);
}
private static Integer findMaxNumber(List<Person> all)
{
/**
* Map from Person to Integer (Person's number) and find the max number.
*/
OptionalInt maxNum = all.stream()
.mapToInt(p -> p.getNumber())
.max();
return maxNum.getAsInt();
}
private static List<Person> findWinners(List<Person> all, Integer max) {
/**
* Filter the people that have the max number and collect them in the list
*/
List<Person> winners = all.stream()
.filter(p -> p.getNumber().equals(max))
.collect(Collectors.toList());
return winners;
}
}//end of Main Class
I am trying to simulate a library of Albums. But I would also be able to organise the contents of the library alphabetically by the author's name. Any help in how to organise the contents of the array of objects alphabetically?
I have created a Class called Album, which I use to create my objects
public class Album {
private String author;
private String name;
private String year;
public Album(String a, String n, String y) { // constructor
author = a;
name = n;
year = y;
}
public String toString()
{
return author +","+ name + "," + year;
}
}
The class Collection is used to store the objects into an array
public class AlbumCollection {
public Album collection[]= new Album[10];
private int numAlbums = 0;
public void add (Album a){
if (numAlbums >= collection.length){
Album newcollection[]= new Album [collection.length * 2];
for (int n = 0; n < numAlbums; n ++){
newcollection[n] = collection[n];
}
newcollection = collection;
}
collection[numAlbums] = a;
numAlbums = numAlbums + 1;
}
public String toString()
{
String details = "";
for ( int p = 0; p < collection.length ; p ++)
{
details = details + collection[p] + "\n" ;
}
details += "\n";
return details;
}
}
This is the class that I am using to create the Album Objects
public class TestCollection {
public static void main(String[] args) {
AlbumCollection c = new AlbumCollection();
c.add( new Album("DaftPunk","Discovery","2001"));
c.add( new Album ("Pink Floid","The Dark Side Of The Moon","1973"));
c.add( new Album( "The Clash", "London Calling", "1979"));
System.out.print(c);
}
}
I had to change the compareTo method to sort by the author.
public class Album {
private String author;
private String name;
private String year;
public Album(String a, String n, String y) { // constructor
author = a;
name = n;
year = y;
}
public String toString()
{
return author +","+ name + "," + year;
}
public int compareTo(Album a) {
// usually toString should not be used,
// instead one of the attributes or more in a comparator chain
return author.compareTo(a.author);
}
}
And i added method sort to sorting elements of array:
public class Collection {
public Album collection[]= new Album[10];
private int numAlbums = 0;
public void Add (Album a){
if (numAlbums >= collection.length){
Album newcollection[]= new Album [collection.length * 2];
for (int n = 0; n < numAlbums; n ++){
newcollection[n] = collection[n];
}
newcollection = collection;
}
collection[numAlbums] = a;
numAlbums = numAlbums + 1;
}
public String toString()
{
String details = "";
for ( int p = 0; p < numAlbums ; p ++)
{
details = details + collection[p] + "\n" ;
}
details += "\n";
return details;
}
public void sort(){
for(int i=0;i<numAlbums;i++){
for(int j=i;j<numAlbums-1;j++){
if(collection[j].compareTo(collection[j+1])>0){
Album tmp =collection[j];
collection[j]=collection[j+1];
collection[j+1]=tmp;
}
}
}
}
}
You can not use the length of an array, if you store the number of authors, because you will print null values
public static void main(String[] args) {
Collection c = new Collection();
c.Add( new Album("DaftPunk","Discovery","2001"));
c.Add( new Album ("Pink Floid","The Dark Side Of The Moon","1973"));
c.Add( new Album( "The Clash", "London Calling", "1979"));
c.sort();
System.out.print(c);
}
I am creating a program that handles a car dealership. The user has the opportunity to add a car in the store by creating a random 3 digit number.
Now the question is how I can search/delete cars depending on the 3 digit code?
I'm thinking that I need every code that the cars have to save it on an array so I can search and delete afterwards.
I have created a class and certain methods on it, I have also created 5 objects and I'm trying to see if it works on these 5.
Here is the method of the random number:
I use the metritis variable because I can't achieve to place correctly the values on the array so I have to give parameter of 1,2,3,4,5 so I can place them correctly to the array.
package antiprosopeia;
import java.util.Random;
public class Antiprosopeia {
private String company,colour;
private int model,horsePower,speed,price,specialCode,metritis;
private int[] codes = new int[]{0,0,0,0,0};
public Antiprosopeia(String company, String colour, int model, int horsePower, int speed, int price) {
this.company = company;
this.colour = colour;
this.model = model;
this.horsePower = horsePower;
this.speed = speed;
this.price = price;
}
public Antiprosopeia() {
company = ""; colour = ""; model = 0; horsePower = 0; speed = 0; price = 0;
}
public void setRandomNumber(int metritis) {
Random rand = new Random();
int randNum2 = rand.nextInt(900) + 100;
specialCode = randNum2;
codes[metritis] = specialCode;
}
public void printarray() {
for(int i=0; i<codes.length; i++) {
System.out.println(" " + codes[i]);}
}
public void Info() {
System.out.println("Company : " + company + "\nColour : " + colour + "\nModel : " + model + "\nHorse Power : " + horsePower +
"\nSpeed : " + speed + "\nPrice : " + price );
}
public static void main(String[] args) {
Antiprosopeia car1 = new Antiprosopeia("Toyota","red",333,100,2223,8000);
car1.setRandomNumber(0);
Antiprosopeia car2 = new Antiprosopeia("Mercedes","yellow",233,100,2990,9000);
car2.setRandomNumber(1);
Antiprosopeia car3 = new Antiprosopeia("Volkswagen","green",153,100,2780,6000);
car3.setRandomNumber(2);
Antiprosopeia car4 = new Antiprosopeia("Mitsubisi","white",678,140,2600,7000);
car4.setRandomNumber(3);
Antiprosopeia car5 = new Antiprosopeia("Porsche","black",390,1000,2000,30000);
car5.setRandomNumber(4);
}
}
[EDIT] Now when i call the printarray() method it seems that at my array only one value is hold and all the others are zer0s as i defined the array at start of my program
If I were doing this, I would use a HashMap. This way you know that you have a unique 3 digit number, and if you wanted to, you could also store more data. You could do something like:
HashMap<Integer, Car> cars = new HashMap<Integer, Car>();
This example would allow you to add a car object to the map. You don't have to that, but it's an option. If you didn't want to do that, you could do:
HashMap<Integer, String> cars = new HashMap<Integer, String>();
and then do:
cars.put(123, "Description of car");
Using a HashMap would give you more options when storing the data. This would also prevent you from creating an array with 1000 elements, all of which are 0 until you have a value for them. You could easily print out all your numbers by doing:
for(int number : cars.entrySet()){
System.out.println("My car number: " + number);
}
Searching for keys would extremely easy, as you could do:
String description = cars.getKey(123);
If description was null, you would know that there is no key for it.
Your issue is that each Antiprosopeia object has its own codes array. They are not shared.
If you really want each object to have a Random ID, then assign that within the constructor.
public class Antiprosopeia {
private String company,colour;
private int model,horsePower,speed,price,specialCode,metritis;
private int randID;
public Antiprosopeia(String company, String colour, int model, int horsePower, int speed, int price){
this.company = company;
this.colour = colour;
this.model = model;
this.horsePower = horsePower;
this.speed = speed;
this.price = price;
this.randID = new Random().nextInt(900) + 100;
}
public Antiprosopeia(){
this("", "", 0, 0, 0, 0);
}
public int getID() { return this.randID; }
#Override
public String toString() {
return String.format(
"Company : %s\n" +
"Colour : %s\n" +
"Model : %s\n" +
"Horse Power : %d\n" +
"Speed : %d\n" +
"Price : %d\n",
company, colour, model, horsePower, speed, price
);
}
If you want to print all those objects,
public static void main(String[] args) {
List<Antiprosopeia> cars = new ArrayList<Antiprosopeia>();
cars.add(new Antiprosopeia("Toyota","red",333,100,2223,8000));
cars.add(new Antiprosopeia("Mercedes","yellow",233,100,2990,9000));
for (int i = 0; i < cars.size(); i++) {
Antiprosopeia c = cars.get(i);
System.out.println(c.getID());
System.out.println(c);
}
}
package chapter10;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Customer {
private String name;
private String streetAddress;
private String phoneNumber;
private int total;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStreetAddress(){
return streetAddress;
}
public void setStreetAddress(String streetAddress) {
this.streetAddress = streetAddress;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public int getTotal(){
return total;
}
public void setTotal(int total){
this.total = total;
}
public static void assign(){
int a = (int) (Math.random() + 10);
int r = (int) (Math.random() + 10);
int f = (int) (Math.random() + 10);
System.out.println(a + r + f + "x" + "x" + "x");
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
ArrayList <Customer > customerList = new ArrayList <Customer>();
char ans;
do
{
Customer customer = new Customer();
System.out.print("Customer name ");
customer.setName(in.next());
int i = 0;
++i;
System.out.print("Street Address ");
customer.setStreetAddress(in.next());
System.out.print("Phone Number ");
customer.setPhoneNumber(in.next());
customerList.add(customer);
System.out.println("Enter total sales ");
customer.setTotal(in.nextInt());
System.out.println("Would you like to enter in a new customer ( y/n)? ");
String answer = in.next();
ans = answer.charAt(0);
((String) customerList).concat("")
} while(ans == 'y');
for(Customer c: customerList){
System.out.print(c.getName() + "\n" + "Phone number is " +c .getPhoneNumber() +"\n" + "Total sales is "+ c.getTotal() + "\n" + "Address is"+ c.getStreetAddress());
}
for(int i=0; i<customerList.size(); i++){
//System.out.print(customerList.get(i).getName());
}
}
}
I need to assign a number to each value in the arraylist but i am getting an error that says that I have to convert to string (arraylist). How do I add it?
If what I gather from the comments is correct then I believe this is what you want:
Your current assign() is incorrect if you want random values 1-10, it should look like this instead:
public String assign(){
Random rand = new Random();
int a = rand.nextInt(10) + 1;
int r = rand.nextInt(10) + 1;
int f = rand.nextInt(10) + 1;
return a+r+f+"xxx";
}
Customer will look like this:
public class Customer {
private String name;
private String customerNumber;
private String streetAddress;
private String phoneNumber;
private int total;
...
...
...
public String getCustomerNumber() { return this.customerNumber; }
public void setCustomerNumber(String cNumber) { this.customerNumber = cNumber; }
And assigning the numbers should look like this:
for(Customer c : customerList) {
c.setCustomerNumber(assign());
}
Also avoid this line of code, it's a really bad idea:
((String) customerList).concat("")
You should probably rename the customerNumber to customerID.
Hiiii
As i understand you are trying to to add number to each value to arrayList ,And same time you are creating arrayList of customer object, So first understand about arrayList of object,
Customer c1 = new Customer();
Customer c2 = new Customer();
ArrayList<Customer> al = new ArrayList();
al.add(c1);
al.add(c2);
Here this ArrayList object save only address of customer object so how can you change the address of Customer object ; You can not add number in Customer type ArrayList Object,
There is another way typecast your ArrayList to Object type and then no need to typecast again , you can add any type of object in ArrayList
like this,
Customer c1 = new Customer();
Customer c2 = new Customer();
ArrayList<Object> al = new ArrayList();
al.add(c1);
al.add(c2);
In your code there's the following line:
((String) customerList).concat("")
Trying to cast a List to a String is doomed to failure - I'm not sure why do you think it should work.
If you want a String representation of the list, you should implement a toString() method in class Customer and then you can do something like:
System.out.println(Arrays.toString(customerList.toArray()));
Instead of using ArrayList, you can use Map. In which you can have the number as key and value as Customer.
http://examples.javacodegeeks.com/java-basics/java-map-example/ Contains the example of using Map
Answer in Storing a new object as the value of a hashmap? contains info about how to use Object as value in HashMap
i have a string array consisting of a name and a score. I want to sort that array by score. Problem is, considering it's a string array, the scores are strings which results in 13,16,2,5,6 and not 2,5,6,13,16. I am using this code:
int spaceIndex;
String[][] scoreboard;
String[] playername;
String[] score;
int sbsize;
array1.add("Thomas" + ":" + 5);
array1.add("Blueb" + ":" + 6);
array1.add("James" + ":" + 16);
array1.add("Hleb" + ":" + 13);
array1.add("Sabbat" + ":" + 2);
sbsize = array1.size();
scoreboard = new String[sbsize][2];
playername = new String[sbsize];
score = new String[sbsize];
pos2 = new int[sbsize];
for (int i=0; i<array1.size(); i++)
{
spaceIndex = array1.get(i).indexOf(':');
scoreboard[i][0] = array1.get(i).substring(0, spaceIndex);
scoreboard[i][1] = array1.get(i).substring(spaceIndex+1, array1.get(i).length());
}
Arrays.sort(scoreboard, new Comparator<String[]>() {
#Override
public int compare(String[] entry1, String[] entry2) {
String time1 = entry1[1];
String time2 = entry2[1];
return time1.compareTo(time2);
}
});
What is the solution?
Cast them to int. As I recall, something like...
Arrays.sort(scoreboard, new Comparator<String[]>() {
#Override
public int compare(String[] entry1, String[] entry2) {
Integer time1 = Integer.valueOf(entry1[1]);
Integer time2 = Integer.valueOf(entry2[1]);
return time1.compareTo(time2);
}
});
Also you can make simple value object class for easier manipulations. Like...
class Player
{
public String name;
public int score;
}
And after that you can make
Player[] scoreboard = ...
Arrays.sort(scoreboard, new Comparator<Player>() {
#Override
public int compare(Player player1, Player player2) {
if(player1.score > player2.score) return 1;
else if(player1.score < player2.score) return -1;
else return 0;
}
});
Edit:
I recommend you to understand the basic OOP principles, this will help you a lot in the beginning.
Edit 2: Java 8 (with functional interface and a lambda):
Arrays.sort(scoreboard, (player1, player2) -> {
Integer time1 = Integer.valueOf(player1[1]);
Integer time2 = Integer.valueOf(player2[1]);
return time1.compareTo(time2);
});
This is the easy way of Sorting String Array:
Arrays.sort(mystringarray);
Use
java.util.Arrays.sort(yourArray, new Comparator<String>() {
#Override
public int compare(String object1, String object2) {
return Integer.valueOf(object1).compareTo(Integer.valueOf(object2));
}
});
Comparator will compare your strings as integers.
ArrayList<String> names= new ArrayList<String>();
names.add("sathish");
names.add("Ravi");
names.add("Praksh");
names.add("pavithara");
names.add("Duraga");
names.add("uma");
names.add("Upendar");
System.out.println("Before sorting");
System.out.println("Names : "+names);
Collections.sort(names, new Comparator<String>() {
#Override
public int compare(String lhs, String rhs) {
return lhs.compareToIgnoreCase(rhs);//Ascending order.
//return (lhs.compareToIgnoreCase(rhs)*(-1));//Descending order.
}
});
System.out.println("After sorting");
System.out.println("Names : "+names);
output:
Before sorting
Names : [sathish, Ravi, Praksh, pavithara, Duraga, uma, Upendar]
After sorting
Names : [Duraga, pavithara, Praksh, Ravi, sathish, uma, Upendar]
If possible use better data structure for your problem, use HashMap, with name to score mapping and , sort the hashmap with values.
If you want to go with arraylist as described by you, before sorting, convert them into integer and sort, then back to string.
You would probably be better off storing the names + results in objects, then storing those in an ArrayList. You can then sort very easily using a custom comparator, see the link for a simple example: http://www.javabeat.net/tips/20-sorting-custom-types-in-java.html
Score should be a class like
public class HighScore Comparable<HighScore>
{
private String name;
private int score;
public Score( String name, int score )
{
this.name = name;
this.score = score;
}//cons
//getters
public String getName() {
return name;
}//met
public int getScore() {
return score;
}//met
#Override
public int compareTo( HighScrore b )
{
int diffScore = score - b.score;
if( diffScore != 0)
return diffScore;
else
return name.compareTo( b.name );
}//met
public boolean equals( Object o )
{
if( !(o instanceof HighScore))
return false;
HighScore b = (HighScore) o;
return score == b.score && name.equals( b.name );
}//met
}//class
Then you can build score objects,
String[] stringParts[];
List<HighScore> listHighScore = new ArrayList<HighScore>();
for (int i=0; i<array1.size(); i++)
{
stringParts = array1.get(i).split(':');
listHighScore.add( new HighScore( stringParts[ 0 ], Integer.parseInt( stringParts[ 1 ])) );
}//for
put them in a List and sort them through
Collections.sort( list );
Regards,
Stéphane
You can use ArrayList instead of Array.
Please check this link