Love letter- using arrays to print message - java

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.

Related

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.

Deleting String template until '\n' In a large String - Java

I'm having problem with String's in Java. I have a large String with a lot of \n and \\n. I want to delete entire rows that start with a certain template "Chorus:" and the rest of the row until \n.
I try to go over the String and searching the template "Chorus:". When i reach that, I concatenate the rest of the line until i reach to \n. Then i use myString.reaplaceAll(subString," ") and i get the same String as i started with.
My Code:
String string = " Police voice:\n"
+ "Attention all units attention all units\n"
+ "We have an All Points Bulletin out on a man with green hair\n"
+ "I repeat we have an APB on a man with green hair\n"
+ "He's armed with a knife I repeat he's armed with a knife\n"
+ "Proceed with caution watch your back fella's\n"
+ "He could be coming at your girlfriend next\n\n"
+ "Verse 1:\n"
+ "There's a joker on the loose from the psychiatric ward\n"
+ "His face is up on the bulletin board with a reward\n"
+ "He'll stab you with a sword don't be fooled by his charm\n"
+ "He's probably armed with intent to do bodily harm\n"
+ "Ring the alarm, look for a man with green hair\n"
+ "Check at your girl's house, he was last seen there\n"
+ "He's has a mean stare but usually crack's jokes\n"
+ "Good luck on your mission and guard your backs folks\n\n"
+ "Chorus:\n"
+ "I make you think you're a best friend then\n"
+ "Why I oughtta\n"
+ "Hit a bitch snake from the back, I make you think you're a best friend then\n"
+ "Why I oughtta\n"
+ "Stay away from him he ain't no good!\n\n"
+ "Verse 2:\n"
+ "We got the walkie-talkies to keep us all informed\n"
+ "Suited up head to toe in detective uniforms\n"
+ "Our unit storms in, we split the ghetto in sectors\n"
+ "Locking down every block and put up metal detectors\n"
+ "Protectors and be sure that you stand close\n"
+ "Watch each others backs and guard your command post\n"
+ "And most of all be advised that he's wise\n"
+ "He could be disguised as one of your very own guys\n\n"
+ "Chorus:\n"
+ "I make you think you're a best friend then\n"
+ "Why I oughtta\n"
+ "Hit a bitch snake from the back, I make you think you're a best friend then\n"
+ "Why I oughtta\n"
+ "Stay away from him he ain't no good!\n"
+ "Verse 3:\n"
+ "I'm on a solo mission to find him personally\n"
+ "To settle the score and beat then him mercifully\n"
+ "For what he first did to me\n"
+ "It's sure to be the last\n"
+ "Following footprints with a magnifying glass\n"
+ "To drag his lying ass back to his padded cell\n"
+ "I'm mad as hell, on the trail of the tattle tail\n"
+ "I heard a yell the voice sounded familiar\n"
+ "Give me your girlfriend or I'm gonna kill ya\n\n"
+ "Chorus:\n"
+ "I make you think you're a best friend then\n"
+ "Why I oughtta\n"
+ "Hit a bitch snake from the back, I make you think you're a best friend then\n"
+ "Why I oughtta\n"
+ "Stay away from him he ain't no good!\n\n"
+ "Verse 4:\n"
+ "I followed the voice that led down a flight of steps\n"
+ "Sneezing at dust, and swinging at the spider-webs\n"
+ "Inside the depths of his basement\n"
+ "I taste lint in my mouth, then the lights in the place… went!\n"
+ "I saw my life flash in front of my eyes\n"
+ "I felt a butcher knife slash at one of my thighs\n"
+ "None of my guys knew where I'm at I was doomed\n"
+ "Then I remembered the flashlight in my costume\n\n"
+ "Chorus: Eminem\n"
+ "I make you think you're a best friend then\n"
+ "Why I oughtta\n"
+ "Hit a bitch snake from the back, I make you think you're a best friend then\n"
+ "Why I oughtta\n"
+ "Stay away from him he ain't no good!\n\n"
+ "Verse 5:\n"
+ "Dealing with backstabber's there was one thing I learned\n"
+ "They're only powerful when you got your back turned\n"
+ "I yearned for the day that we finally met againf\n"
+ "So I can give him a taste of his own medicine\n"
+ "He shed his skin, then he promised to come clean\n"
+ "I took his butcher knife and jabbed it into his spleen\n"
+ "Cut him at the seam then dragged the fella home\n"
+ "Beating him over the head with the telephone\n\n"
+ "Police voice:\n"
+ "Attention all cars, attention all cars\n"
+ "Unit 313 has apprehended the suspect\n"
+ "He's going back to the crazy home, I repeat\n"
+ "He's going back to the crazy home, how about that?\n\n"
+ "Chorus:\n"
+ "I make you think you're a best friend then\n"
+ "Why I oughtta\n"
+ "Hit a bitch snake from the back, I make you think you're a best friend then\n"
+ "Why I oughtta\n"
+ "Stay away from him he ain't no good!\n"
+ "I make you think you're a best friend then\n"
+ "Why I oughtta\n"
+ "Hit a bitch snake from the back, I make you think you're a best friend then\n"
+ "Why I oughtta\n"
+ "Stay away from him he ain't no good!\n"
+ "I make you think you're a best friend then\n"
+ "Why I oughtta\n"
+ "Hit a bitch snake from the back, I make you think you're a best friend then\n"
+ "Why I oughtta\n"
+ "Stay away from him he ain't no good!";
String subString = ""; // Searching for Chorus: (7 characters) sub sub string in string
for (int i = 0;i < string.length();i++)
{
if (string.charAt(i) == 'C')
{
subString = string.substring(i,i + 7);
subString += " "; // "Chorus: "
//System.out.println(subString);
if (subString.equals("Chorus:")) // Delete the row
{
i += 7;
while (string.charAt(++i)!= '\n')
{
//System.out.println(string.charAt(i));
subString += string.charAt(i);
}
string = new String(string.replaceAll(subString, ""));
}
}
}
printString(string);
}
/**
*
* #param string to be printed on the console.
*/
public static void printString(String string)
What am i doing wrong? Any help will be very appreciated.
EDIT:
For clarification:
converting "abcChorus:def\n"+"gh\n"+"Chorus;ijk\n"+"lmnop" to "gh\n"+"lmnop"
You should get into the base libraries of a language and see what they can do, instead of pushing chars yourself...
String[] lines = string.split("\n"); // split into array at newlines
String result = Stream.of(lines)
.filter(s -> !s.startsWith("Chorus:")) // filter however you like
.collect(Collectors.joining("\n")); // re-join as string with newlines
System.out.println(result);
You can try this:
String new = old.trim()
It removes the leading and trailing spaces from string.
You can store the trimmed string somewhere.After that once you make the modification concatenate it as the way you want it.
You could make a use of regex and recursion too. Just call the removeStuff method on your String.
You can also change and tweak the regex inside the compile method argument.
static Pattern pattern = Pattern.compile("Chorus([^\n]*)");
static Matcher matcher = pattern.matcher(string);
public static String removeStuff(String myString, Matcher matcher) {
if (matcher.find() == false) {
return myString;
}
return removeStuff(string.replace(matcher.group(), ""), matcher);
}
My complicated solution.
I searched for "Chorus: " String in the String and concatenated the rest of the line (until \n) and replace those sub strings in the whole String. Then replacing all the "Chorus:" sub strings from the whole String.
Like that i tackle both "Chorus:" lines and "Chorus: blablablalba" lines.
Solution:
String subString = ""; // Searching for "Chorus: " (7 characters) sub string in string
for (int i = 0;i < string.length();i++)
{
if (string.charAt(i) == 'C')
{
subString = string.substring(i,i + 8);
//subString += " "; // "Chorus:"
//System.out.println(subString);
if (subString.equals("Chorus: ")) // Delete the row
{
i += 8;
while (string.charAt(i)!= '\n')
{
//System.out.println(string.charAt(i));
subString += string.charAt(i);
i++;
}
//System.out.println(subString);
string = new String(string.replaceAll(subString, ""));
}
}
}
string = new String(string.replaceAll("Chorus:", ""));

Send enums values with a message

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

How to display a list of ints and display total cost

This is my current code:
public static void Costs(float[] args) {
Scanner Costs = new Scanner(System.in);
String Item1Cost;
System.out.print("Enter the cost of Item 1 £");
Item1Cost = Costs.next();
String Item2Cost;
System.out.print("Enter the cost of Item 2 £");
Item2Cost = Costs.next();
String TotalCost;
TotalCost = Item1Cost + ", " + Item2Cost;
System.out.println("The cost of each of your items in order is: " + TotalCost);
}
I am trying to change it so that it obtains an int form the user and displays all the prices, and also totals them.
When trying my self I used this, and I could get the 'costs' stored them in a string and display them but I can not make a total with this code. I was wondering if someone could give me a hand. I'm sure the answer is pretty simple, but I'm fairly new to java and I just cant think of a solution.
So what you're doing at the moment is String concatenation. This is where you simply stick two String objects on the end of one another, and create a new String from that. This happens because, in Java the + operator is overloaded. This means that it expresses different functionality depending on the type of the operands.
Example of overloaded operator
String str = "Hello ";
String str2 = "World.";
String sentence = str + str2; // Sentence equals "Hello World."
int num1 = 5;
int num2 = 7;
int total = num1 + num2; // Same operator, but total equals 12, not 57.
What you need to do in your example is cast the operands to the correct types, so that Java knows how to work on them. That is, it overloads + to the correct functionality.
Example
int item1Cost = costs.nextInt(); //Notice the java naming conventions.
int item2Cost = costs.nextInt();
System.out.println("Total cost: " + (item1Cost + item2Cost));
Or you can pull the value in as a String and perform some validation. This is a safer option because it means you can control program flow easier.
String item1CostStr = costs.nextLine();
int item1Cost = 0;
if(item1CostStr.matches("[0-9]+")) {
item1Cost = Integer.parseInt(item1CostStr);
}
to convert an string to an int and operate with it, you should use this method:
Integer.parseInt(string);
That method returns an int.
Hope it helps!
If you want the input as an integer, use scan.nextInt() instead. Then it should work just fine.
This is a weird line of code though:
TotalCost = Item1Cost + ", " + Item2Cost;
What is it supposed to do? This won't compile if you're using integers.
Sidenote: use the java naming conventions. Variable names should start with a lowercase letter.

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