I have a question which requires me to create an enum class with two fields, name (String), and then create a hashmap to generate the output with foreach loops method here.
Expected output:
1 = APPLE, price = 20
2 = STRAWBERRY, price = 70
I try to create two hashmaps to get the output and for loops to get the value but the output is not what I want. May I know how to print the price with the relevant fruits only?
My output:
1 = APPLE
2 = STRAWBERRY
,price=20
,price=70
Enum code here:
enum Fruit {
APPLE("APPLE", 20), STRAWBERRY("STRAWBERRY", 70);
private final int price;
private final String name;
private Fruit(String name, int price) {
this.name = name;
this.price = price;
}
}
main class here
public static void main(String[] args) {
HashMap<Integer, Fruit> foodTable = new HashMap<>();
HashMap<Fruit, Integer> priceTable = new HashMap<>();
foodTable.put(1, Fruit.APPLE);
priceTable.put(Fruit.APPLE, Fruit.APPLE.price);
foodTable.put(2, Fruit.STRAWBERRY);
priceTable.put(Fruit.STRAWBERRY, Fruit.STRAWBERRY.price);
for (Map.Entry<Integer, Fruit> set : foodTable.entrySet()) {
System.out.println(set.getKey() + " = " + set.getValue());
}
for (Map.Entry<Fruit, Integer> set1 : priceTable.entrySet()) {
System.out.println("," +
"price" + "=" + set1.getValue());
}
}
You don't need maps at all, as an enum provides a method to return its values.
Given the enum
enum Fruit {
APPLE("APPLE", 20), STRAWBERRY("STRAWBERRY", 70);
private final int price;
private final String name;
private Fruit(String name, int price) {
this.name = name;
this.price = price;
}
public String getName() { return name; }
public int getPrice() { return price; }
}
You can simply write:
int pos = 0;
for (Fruit fruit : Fruit.values()) {
pos++;
System.out.printf("%d = %s, price = %d%n",
pos, fruit.getName(), fruit.getPrice());
}
Edit: as an enum value also knows its ordinal position you can simplify this to
for (Fruit fruit : Fruit.values()) {
System.out.printf("%d = %s, price = %d%n",
fruit.ordinal()+1, fruit.getName(), fruit.getPrice());
}
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
Let's assume I have got a List of Flight Objects
public class Flight {
private int passengers;
private int price
...
//getters and Setters
}
List<Flight> flightList = new ArrayList<Flight>();
Now i need to accumulate price per passenger and the Price, because I have to be able to proceed both informations later on. so I would create two methods:
public int calculatePrice(List<Flight> flightList) {
int price = 0;
for (Flight flight : flightList) {
price = price + flight.getPrice();
}
return price;
}
public int calculatePricePerPassengers(List<Flight> flightList) {
int pricePerPassenger = 0;
for (Flight flight : flightList) {
pricePerPassenger = (pricePerPassenger) + (flight.getPrice() / flight.getPassgers());
}
return pricePerPassenger;
}
I have got like 4-5 methods of the same type. I am not sure whether there is too much redundancy, because I call the for loop 4-5 Times and I could easily do all the operations in one for loop, but that would have the effect of multiple return values. So is this the appropriate way ?
(just a dummy example)
You can use map for that or also you can warp all the fields you want to return in a class. Here I am giving the example using Map.
public static Map<String, Integer> calculatePrice(List<Flight> flightList) {
Map<String, Integer> priceMap = new HashMap<>();
int price = 0;
int pricePerPassenger = 0;
for (Flight flight : flightList) {
price = price + flight.getPrice();
pricePerPassenger = (pricePerPassenger) + (flight.getPrice() / flight.getPassgers());
}
priceMap.put("price", price);
priceMap.put("pricePerPassenger", pricePerPassenger);
return priceMap;
}
EDIT:
Example using a wrapper class (DTO).
public static FligtPriceDTO calculatePrice(List<Flight> flightList) {
FligtPriceDTO dto = new FligtPriceDTO();
int price = 0;
int pricePerPassenger = 0;
for (Flight flight : flightList) {
price = price + flight.getPrice();
pricePerPassenger = (pricePerPassenger) + (flight.getPrice() / flight.getPassgers());
}
dto.setPrice(price);
dto.setPricePerPassenger(pricePerPassenger);
return dto;
}
}
class FligtPriceDTO {
private int price;
private int pricePerPassenger;
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public int getPricePerPassenger() {
return pricePerPassenger;
}
public void setPricePerPassenger(int pricePerPassenger) {
this.pricePerPassenger = pricePerPassenger;
}
}
You could wrap those two values into a new array:
public int[] calculatePrices(List<Flight> flightList) {
int totalPrice = 0;
int pricePerCustomer = 0;
for (Flight flight : flightList) {
totalPrice += flight.getPrice();
pricePerCustomer += (flight.getPrice() / flight.getPassgers());
}
return new int[] { totalPrice, pricePerCustomer };
}
It all comes down to what are the functionalities that you want to provide to the user. So if the user expects to be able to calculate both prices individually then I do not see any other way around what you have. But if you can present both prices at once, then you can eliminate one of the methods and loop only once trough your Flight list and return a composition of both prices. ex:
public static Pair[] calculatePrices(List<Flight> flightList)
{
int pricePerFlight= 0;
int pricePerPassenger = 0;
for(Flight flight : flightList)
{
pricePerFlight = pricePerFlight + flight.getPrice();
pricePerPassenger = pricePerPassenger +(flight.getPrice()/flight.getPassgers());
}
return new Pair[] {new Pair<>("pricePerFlight", pricePerFlight), new Pair<>("pricePerPassenger", pricePerPassenger )};
}
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)
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);
}
}
I have this Java object which is used to store item:
public class PaymentDetailsItem
{
private String name;
private String amount;
private int quantity;
private String currencyID;
public PaymentDetailsItem(String name, String amount, int quantity, String currencyID){
this.name = name;
this.amount = amount;
this.quantity = quantity;
this.currencyID = currencyID;
}
............
}
I use a List to store several Objects. How can I sum up the total amount from every object store into the List?
You could make use of Java 8 Stream API and implement something like this:
public static void main(String[] args) {
PaymentDetailsItem payment = new PaymentDetailsItem("test", "100.00", 10, "1");
PaymentDetailsItem payment2 = new PaymentDetailsItem("test number 2", "250.00", 10, "2");
List<PaymentDetailsItem> payments = new ArrayList<>();
payments.add(payment);
payments.add(payment2);
List<String> amounts = payments.stream().map(PaymentDetailsItem::getAmount).collect(Collectors.toList());
System.out.println("Here we have the extracted List of amounts: " + amounts);
String totalAmount = amounts.stream()
.reduce((amount1, amount2) -> String.valueOf(Float.valueOf(amount1) + Float.valueOf(amount2))).get();
System.out.println("Total amount obtained by using .reduce() upon the List of amounts: " + totalAmount);
System.out.println("Or you can do everything at once: " + payments.stream().map(PaymentDetailsItem::getAmount)
.reduce((amount1, amount2) -> String.valueOf(Float.valueOf(amount1) + Float.valueOf(amount2))).get());
}
Remember to implement the getter for the amount attribute.