This question already has answers here:
What's the best way to implement `next` and `previous` on an enum type?
(7 answers)
Closed 7 years ago.
I have an enum in Java as following:
public enum Cars
{
Sport,
SUV,
Coupe
}
And I need to get the next value of the enum. So, assuming I have a variable called myCurrentCar:
private Cars myCurrentCar = Cars.Sport;
I need to create a function that when called set the value of myCurrentCar to the next value in the enum. If the enum does not have anymore values, I should set the variable to the first value of the enum.
I started my implementation in this way:
public Cars GetNextCar(Cars e)
{
switch(e)
{
case Sport:
return SUV;
case SUV:
return Coupe;
case Coupe:
return Sport;
default:
throw new IndexOutOfRangeException();
}
}
Which is working but it's an high maitenance function because every time I modify the enum list I have to refactor the function.
Is there a way to split the enum into an array of strings, get the next value and transform the string value into the original enum? So in case I am at the end of the array I simply grab the first index
Yeah sure, it goes like this
public Cars getNextCar(Cars e)
{
int index = e.ordinal();
int nextIndex = index + 1;
Cars[] cars = Cars.values();
nextIndex %= cars.length;
return cars[nextIndex];
}
Related
This question already has answers here:
To use a string value as a variable name [duplicate]
(5 answers)
Closed 2 years ago.
I was just simplifying my code and I ran into a small problem which I can't solve.
So I have an activity which has a getter like so:
private String[][] Example001 ={{"String1","String2"},{"Light","Normal","Heavy"}};
public String getExerciseValue(String variableName ,int codeOrValue,int type){
switch (variableName){
case "Example001":
return Example001[codeOrValue][type];
case "Example999"
return Example999[codeOrValue][type];
}
return "default";
}
so instead of having numerous number of cases, I would rather simplify the code by something like this
public String getExerciseValue(String variableName ,int codeOrValue,int type){
return variableName[codeOrValue][type];
}
I ask for an example of working code work this case coz I have no idea how to figure this out. Thanks for any suggestions :)
This is not possible in Java. However, it is also not necessary.
Whenever you have series of numbered variable names, that's actually just a very cumbersome way of implementing an array:
private String[][][] examples = {
{
{ "String1", "String2" },
{ "Light", "Normal", "Heavy" }
}
};
public String getExerciseValue(int exampleNumber, int codeOrValue, int type) {
return examples[exampleNumber - 1][codeOrValue][type];
}
Suggest you to use HashMap, and put each array as a value with your preferred name in it. Something like it:
Map<String, String[][]> examples = new HashMap<>();
examples.put("Example001", Example001);
You can then easily retrieve your element with its names and indexes as you needed.
examples.get("Example001")[codeOrValue][type]
This question already has an answer here:
Java: Find the index of a String in a list
(1 answer)
Closed 3 years ago.
I have an ArrayList of type Player and I am trying to search for a specific string and I'm having a lot of trouble.
Currently I'm using a boolean to see if the player contains the string. Then I use a for loop to search the list.
But it keeps outputting the final line of the file; I'm pretty sure im not searching properly.
String playerName = sc.next();
boolean isFound = players.contains(playerName);
int index = 0;
for (int i = 0; i < players.size(); i++) {
if (isFound) {
break;
}
index = i;
}
System.out.println(players.get(index));
System.out.println(isFound);
My Player class is defined as follows
(not sure if this helps)
public class Player extends Person {
public String pos;
public int g;
public int ab;
public int r; // various statistics for the player
public Player(String name, String team, String pos) {
this.name = name;
this.team = team;
this.pos = pos;
}
And i also have a league class containing the lists
public class League extends loadData {
public static ArrayList<Player> players = new ArrayList<Player>();
public static ArrayList<Pitcher> pitchers = new ArrayList<Pitcher>();
}
If anyone can help me out that would be much appreciated!
If you just need the index of an element in the list, use List#indexOf(). There is no need to check if the list contains the element first because if it does not, the method returns -1.
Example:
List<String> players = new ArrayList<String>
players.addAll(Arrays.asList("Jim, "Bob, "Mary");
int indexOfBob = players.indexOf("Bob");
If you plan on iterating through the list and performing an operation on all the elements until you reach a specific one, you don't need to use two index integers. Example:
int i;
for(i = 0; i < players.size(); i++) {
// Perform an operation on the current player.
if(players.get(i).equals("Bob")) break;
}
what's happening with your code
isFound is set only before loop. That's totally ok for checking if the string is contained within the list.
If the list doesn't contain the string, then the loop will never break and iterating through all elements. So in this case your index-counter i will point to the last element which then gets printed after the loop.
clarify type of list elements VS type of searched
If your list stores objects of Player you couldn't simply compare them to searched object String. Maybe you can — on each element of the list — compare for player.toString().contains(playerName) or you can check for player.getName().equalsIgnoreCase(playerName).
The type of you list's elements and it's declaration matter and need to be known (to us) in order to solve this.
solving search and print finding
assuming the list contains elements of type string, i.e. ArrayList<String> players
To check if an element (here string playerName) is contained you can use either (Array)List's indexOf or contains method.
Note: the string could be 0, 1, or multiple times contained in the list. The approaches above only find first or no occurrence.
For printing you can either print the search-term playerName directly if found. Or you can use the returned first found index of method-call index to get the matching element and print that.
Note: The text printed should be the same in both options, although instance-ids/hashCodes could vary.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
Im trying to use the override comparator method of priorityqueue and i want to achieve the following:
i have the current list:
RG3
PR1
PR2
RG4
RG1
RG2
the RG refers to a regular person and the PR refers to a person with priority, the numbers represent the turns.
what i want is to get a First in first out order except when is a priority person wich will go to the top of the queue in his turn. so in the list i want the following result
PR1
PR2
RG1
RG2
RG3
RG4
heres what ive done until now:
Queue<Ficha> cola = new PriorityQueue<>(6, idComparator);
while (!list.isEmpty()) //this list is the unsorted list.
{
aux = list.remove(0);
cola.add(aux); // adds it to the priority queue
}
while(!cola.isEmpty())
{
aux = cola.poll();
System.out.println(aux.getCod_priority()+aux.getTurn()); // this shows me the order of the queue
}
}
public static Comparator<Ficha> idComparator = new Comparator<Ficha>()
{
#Override
public int compare(Ficha f1, Ficha f2) {
return (int) ((f1.getTurn()+prioridad(f1.getCod_priority())) - (f2.getTurn()+prioridad(f2.getCod_priority())));
}
};
private static long prioridad(String cod_priority) // this method i use it to give the cod_priority a int value to compare
{
if(cod_tipo_ficha=="PR")
{
return 10000;
}
else
{
return 1;
}
}
and when i run it i get the following order:
PR1
RG1
RG2
PR2
RG3
RG4
i know my problem is in the comparator method but i dont know how to achieve the queue that i want.
i know theres a lot of question related of how to compare but the only answers i see is when you compare strings. and this one i need to compare the priority string and the int.
Just change cod_tipo_ficha=="PR" to
if("PR".equals(cod_tipo_ficha)) {
...
}
Should work
I have a list of objects where list name is employments and it has 'n' number of objects called employments.Each employment object has variable called serialnumber. Now i need to increment serialnumber for each object by 11.
Here is code
for(Employment employment:employments.getEmployemnts()){
if(employment="GENERAL_MANAGER"){
employement.setSerialNumberForGenManager()
}else{
employment.setSerialNumberForOthers()
}
Inside the employment class:
public static employemntIndex=11;
public employemnt setSerialNumberForGenManager(){
this.serialNumber = 0;
}
public employemnt setSerialNumberForOthers(){
this.serialNumber = employemntIndex+serialNumber;
}
Now,i'm not able to increment values by 11. The result for every object is always 11 only.It is not getting incremented.
This may be because of your String comparison. String comparisons should use the Object#equals(Object) method (as opposed to ==);
if (yourString.equals("COMPARISON STRING")) //do stuff
This is because String is an instance (which happens to contain text), and the the == operator in this case only tests the references, not whether the instances themselves contain the same text.
Also, = is an assignment operator, == should be used for most comparisons (other than 'special cases', such as comparing Strings).
The next problem is that you are not carrying the values over (as you say). To fix this;
public static employemntIndex = 11;
//Increase the employment index for each GENERAL_MANAGER
public employemnt setSerialNumberForOthers(){
this.serialNumber = employmentIndex;
employmentIndex += 11;
}
Try like this
public static Integer employemntIndex = 0;
public employemnt setSerialNumberForOthers(){
this.serialNumber = employemntIndex;
employemntIndex += 11;
}
Two possible errors:
You are using a so called "enhanced for loop".
You can't edit the elements of a collection that way as that loop is read-only.
To edit elements you have to use a for loop with an explicit iteration index or an iterator.
You seem to be comparing a reference (memory address with a String that is unlikely to correspond to a memory address.
employment="GENERAL_MANAGER"
You probably forgot to call a getter method like
employment.getRole().equals("GENERAL_MANAGER")
So it would be (if size() method is not supported you should use array.length)
for(int i = 0; i < employments.getEmployemnts().size(); i++) {
if(employments[i].yourGetter().equals("GENERAL_MANAGER")){
employements[i].setSerialNumberForGenManager()
}else{
employments[i].setSerialNumberForOthers()
}
Or if your collection implements the List interface
Iterator iter = employments.getEmployments().iterator();
while (iter.hasNext()){
Employment employment = iter.next();
if(employment.yourGetter().equals("GENERAL_MANAGER")){
employement.setSerialNumberForGenManager()
}else{
employment.setSerialNumberForOthers()
}
}
Hope that helped
Edit:
as KookieMonster has noticed you are using the assignment operator within the IF condition you should use the equals method
What should be my return at the end of my for loop? I'm trying to display the added results of all three parties numDemocrat, numRepulican and numIndepent by
calculating and then printing the number of democrats (party is "D"),
republicans (party is "R"), and independents (party is anything else).
I'm currently looping over the MemberOfCongress ArrayList returned by parseMembersOfCongress and counting up how many of each party type there are.
Also in my loop I need to check which party the current member belongs to and increment the proper variable. After the loop completes I then print the totals.
public void printPartyBreakdownInSenate()
{
CongressDataFetcher.fetchSenateData(congressNum);
}
{
ArrayList<MemberOfCongress> parseMembersOfCongress; String jsonString;
}
{
System.out.println("Number of Members of the Senate of the " + "&congressNum=" + "?chamber=");
}
public String[]
{
int numDemocrats = 0;
int numRepblican = 0;
int numIndepent = 0;
ArrayList<MemberOfCongress> members;
for (MemberOfCongress memberParty : members) {
if (memberParty.getParty() == "D" ) {
numDemocrats++;
}
else if (memberParty.getParty() == "R" ){
numRepblican++;
}
else if (memberParty.getParty() == "null"){
numIndepent++;
}
}
return ???;
}
Firstly i'm 99% positive you cannot return multiple values, unless your return either an array, an array list or a map.
But what you could do as a work around is one of the following.
1). Return a String array of party members.
2). Return a 2D array mapping name to age or something similar.
3). Return a hashmap of the data with a custom class of information mapped to a name.
4). Use getters to get different pieces of the data at time or all at once.
Java (like the majority of programmming languages) allows only a single return value from a method. There are lots of good reasons for this.
If you need to return multiple values then you will need a separate class for which your method can return a reference to an instance.
For example, in your case:
public enum Party {
REPUBLICAN, DEMOCRAT, OTHER;
}
public Map<Party, Integer> senatorsByParty(List<MemberOfCongress> senators) {
return senators.stream()
.collect(Collectors.groupingBy(MemberOfCongress::getParty, Collectors.counting()));
}
Apologies if you are not aware of the Java 8 syntax here. The stream functions are really just saying 'take all the senators, group them by party and then count them'. The key point is that you are returning a map from parties to integers representing the count of senators.