Send enums values with a message - java

public enum Number {
one(), two(), three(), four();
}
I want to send a message with the numbers separated by a comma:
The numbers are one, two, three and four

The simplest solution would be to use the method name() in your enum
System.out.println(Number.one.name() + ", "
+ Number.two.name() + ", "
+ Number.three.name() + ", "
+ Number.four.name());
Or, if you want to populate your enum in a List first, because your numbers are many, you could populate them using EnumSet.allOf like this:
List<Number> numberList =
new ArrayList<Number>(EnumSet.allOf(Number.class));
And then simply use it like this:
for (int i = 0; i < numberList.size(); i++){
System.out.print(numberList.get(i).name() + (i == numberList.size() - 1 ? "" : ","));
}
(A little syntatical sugar to distinguish between the last number and the rests are added)

I suggest you read the java documentation here:
https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html

Related

Why printing "" + variables output each variable individually without spacing?

One of my assignments has this code:
System.out.println("" + x + y + count);
that outputs the value of x, y and count individually without any spaces. I would like to know more about it online. However, I can't seem to find the right keywords to search it up online. Can someone please explain to me the logic behind this or perhaps point to me a name or keyword for such a situation?
I have always known the " " as a tool to print out a string so I'm confused by this.
Thanks in advance.
If we apply standard Java precedence rules, the statement:
System.out.println("" + x + y + count);
is equivalent to
System.out.println((("" + x) + y) + count);
Then we look at the meaning of +
If the static types of both a and b are numeric types (either primitive numeric or their boxed types) then a + b is numeric addition.
Otherwise, a + b is string concatenation. The two arguments are converted to strings and the strings are concatenated.
Based on this we can say that all of the + operators in the example will be treated as string concatenations.
If you want spaces between x, y and count you need to add some string literals; e.g.
System.out.println("" + x + " " + y + " " + count);
or, more simply:
System.out.println(x + " " + y + " " + count);
If you wanted x, y and count to be added (assuming that they are numeric), then you could write this:
System.out.println("" + (x + y + count));
or, more simply:
System.out.println(x + y + count);
The latter is using a different overload of println.
I have always known the "" as a tool to print out a string so I'm confused by this.
Ummm ... it is actually an empty string literal. The usage "" + x is simply an idiom for converting x to a String. The empty string literal has other uses too. The main one is to represent a String with zero characters.
Or you can use String format like this:
System.out.printf("%d%d%d", x, y, count);
The "" is an empty String. In Java when you concatenate a String with other primitives that can be cast to String the result is a String. That means that the code
System.out.println("" + something);
is a different way to write
System.out.println(String.valueOf(something));
However in your scenario the "" + x + y + count means that the elements are converted to String and then concatenated - this means that if x==1, y==2, count==3 the result would be 123. If you wanted to just cast the result to String you would have to indicate that the computation should happen before casting to String for example by using brackets
System.out.println("" + (x+y+count));
The output of this would be 6.

Performing addition when creating a string

I'm creating a number of objects with details read in from an array. They will have a standard format for one of their instance variables which I'd like to be, in part, an ascending number. Specifically, I'm creating a load of Location objects which I'd like to have a description of "Flat 1", "Flat 2", etc.
I'm wondering though if there is an easy way to perform addition when assigning a value to a String. Stripped down to the relevant part, my code is:
int size = locations.size();
Location l;
for (int i=0; i<size; i++){
l = new Location ("Flat " + i + 1); //LINE A
addLocation(l);
}
//several bits of code have been removed and swapped around here, I realise
//that that snippet doesn't really perform anything useful
However, Java interprets both the "+" symbols in LINE A as concatenation meaning I get "Flat 01", "Flat 11", "Flat 21", etc.
Obviously I could change around the way the loop works, but I was curious as to whether performing calculations in a myString = value + 2 type statement was possible?
String concatenation is left-associative, so all you have to do is wrap the value you want in parentheses to ensure that it's calculated first:
l = new Location ("Flat " + i + 1);
is effectively:
l = new Location (("Flat " + i) + 1);
So i is appended to the string "Flat " first; and then 1 is appended to that.
Should be:
l = new Location ("Flat " + (i + 1));
Use parentheses:
l = new Location ("Flat " + (i + 1)); //LINE A

Java: Issue when replacing Strings on loop

I'm building a small app which auto translates boolean queries in Java.
This is the code to find if the query string contains a certain word and if so, it replaces it with the translated value.
int howmanytimes = originalValues.size();
for (int y = 0; y < howmanytimes; y++) {
String originalWord = originalValues.get(y);
System.out.println("original Word = " + originalWord);
if (toReplace.contains(" " + originalWord.toLowerCase() + " ")
|| toCheck.contains('"' + originalWord.toLowerCase() + '"')) {
toReplace = toReplace.replace(originalWord, translatedValues.get(y).toLowerCase());
System.out.println("replaced " + originalWord + " with " + translatedValues.get(y).toLowerCase());
}
System.out.println("to Replace inside loop " + toReplace);
}
The problem is when a query has, for example, '(mykeyword OR "blue mykeyword")' and the translated values are different, for example, mykeyword translates to elpalavra and "blue mykeyword" translates to "elpalavra azul". What happens in this case is that the result string will be '(elpalavra OR "blue elpalavra")' when it should be '(elpalavra OR "elpalavra azul")' . I understand that in the first loop it replaces all keywords and in the second it no longer contains the original value it should for translation.
How can I fix this?
Thank you
you can sort originalValues by size desc. And after that loop through them.
This way you first replace "blue mykeyword" and only after you replace "mykeyword"
The "toCheck" variable is not explained what is for, and in any case the way it is used looks weird (to me at least).
Keeping that aside, one way to answer your request could be this (based only on the requirements you specified):
sort your originalValues, so that the ones with more words are first. The ones that have same number of words, should be ordered from more length to less.

Love letter- using arrays to print message

I've been asked to create a program that stores series of suitable nouns, adjectives and verbs in arrays. These must be set up at the start of program run. Rather than ask the user, each time it generates letter it just chooses words at random from the appropriate array. The arrays are passed to methods that represent the templates.
I'm new to java, and this is what I have managed to get done below, however shows errors saying void cannot be converted to string for each print message part. I would be glad if someone can help me approach this simple question which i'm struggling on, I don't know if I am doing it correctly.
Any help would be much appreciated.
public static void arrays()
{
String []noun = {"face", "eyes", "tender", "lips", "ears", "roses"};
Random random = new Random();
int rand1 = random.nextInt(noun.length);
String []verb = {"enchant", "dazzle", "cuddle" , "lure", "desire", "dream" };
Random random2 = new Random();
int rand2 = random2.nextInt(verb.length);
String []adjective = { "Alluring", "Angelic", "Adoring", "Appealing", "Attractive", "beautiful"};
Random random3 = new Random();
int rand3 = random3.nextInt(adjective.length);
printmessage (noun[rand1], verb[rand2], adjective[rand3]);
}
// END arrays
public static void printmessage(String noun, String verb, String adjective)
{
System.out.println("I would love to " + verb + " " + adjective + " " + noun + "\n");
System.out.println("Your are my " + noun + " " + adjective + " " + verb + "\n");
System.out.println("you always look great in that " + noun + " ,as you always do, since your so " + adjective + "\n");
System.out.println("I get butterflies when I see you in" + noun + " , you make me " + verb + " , in your " + adjective + " world" + "\n");
}
} // END class loveletter
You've got some issues here, so let's walk through them.
First, the conceptual issue. You shouldn't need to return anything from your printmessage method, as all you're doing is showing a message dialog.
Next, you don't do anything with those four result variables, and they would only last within the scope of that method. That's to say, not very long. I don't think you need them.
Next, the technical issues:
One return is all it takes for the code execution to halt. If it were valid code, you would only get back result1. Since we discussed earlier that you don't need to return anything from this method, remove the superfluous returns.
JOptionPane#showMessageDialog returns void; that is to say, it returns nothing. You can't assign a value of its return type to a variable, so the variables do you absolutely no good. Remove the assignment and declarations.
Don't forget to change the return type of your method to void instead of String.
Clean up the call in arrays() so that it only calls printmessage at the end, and doesn't do anything else after that.
I leave the logical errors (I did notice some funky string concatenation and grammatical errors in there) as an exercise to the reader.

Correct ways to manipulate / get information from array of objects

I have defined an array of objects for a class Plane. Like this:
Plane[] terminalOne = new Plane[] {
new Plane(1, "Madrid", "Ryanair", "Airbus A300", "05.00"),
new Plane(3, "Riga", "AirBaltic", "Boeing 737", "05.30")
//ETC..
};
I'm trying to figure out how to manipulate / get information from this array, for example, display objects. I tried System.out.println(terminalOne); which returns [Lairport.Plane;#322ba3e4 (where airport is my package) I don't understand what this means, but I assume it returned first object? I tried to make it more readable and in my file where I define Plane class and object constructor I added this function:
public void displayPlane() // display plane
{
System.out.println();
System.out.print("{" + flightID + "," + destination + "," + airline + "," + aircraft + "," + time + "}");
System.out.println();
}
To display information about object in form of {.., .., .., .., ..} and tried applying it in my main file as terminalOne.displayPlane(); However got a compiler error saying "Can not find symbol, symbol: method displayPlane(), location: variable terminalOne of type Plane[]"
I worked with LinkedLists where I defined these methods in a separate file, alongside methods for search, delete etc.. Can I do something like this for arrays, if so what is the correct way?
terminalOne is an array, not an individual plane. You could use:
for (Plane plane : terminalOne) {
plane.displayPlane();
}
... but I would personally consider overriding toString() in Plane instead:
#Override public String toString() {
return "{" + flightID + "," + destination + "," + airline + "," +
aircraft + "," + time + "}";
}
Then:
for (Plane plane : terminalOne) {
System.out.println(plane);
}
as Jon suggested you could replace your displayPlane() method with toString() implementation.
Then you could call
System.out.println("terminalOne = " + Arrays.toString(terminalOne));
to see all elemens of your array printed.
to output results from "concatenation" you can then do: :
List<Plane> concatList = new ArrayList<Plane>();
Collections.addAll(concatList, terminalOne);
Collections.addAll(concatList, terminalTwo);
// add many more terminals and then print
System.out.println(concatList);
using only standard java library

Categories