Refactor a reference variable in part of code in Eclipse - java

How would I go about renaming a variable in only part of the code?
For example:
System.out.println("Rectangle 1: " + "\n" + "Width: " + r1.width + "\n" + "Height: " +
r1.height + "\n" + "Color: " + r1.color + "\n" + "Area and Perimeter: " +
r1.getArea(r1.width, r1.height) + ", " + r1.getPerimeter(r1.width, r1.height));
So if I want to type out the same for a second rectangle using r2 as the refVar, is there a way I can quickly do this? I tried copy and pasting then using Alt + Shift + R, but, it ends up changing all of the r1 refvars.

I suggest you to use Find/Replace dialog for this problem it suites for your need. Select a set of statements then press Ctrl + F. A Find/Replace dialog will popup, note that in Scope group Selected lines option is selected.
You can use Replace All or Replace/Find. But be careful that it also replaces the string in comments if found.
Refer picture below.

Take a look at don't repeat yourself (DRY) principle which was designed to prevent situations like yours. Instead of renaming variables create separate method which will accept any Rectangle and print its details.
public static void printRectangleDetails(Rectangle r){
System.out.println("Rectangle 1: " + "\n" + "Width: " + r.width + "\n" + "Height: " +
r.height + "\n" + "Color: " + r.color + "\n" + "Area and Perimeter: " +
r.getArea(r.width, r.height) + ", " + r.getPerimeter(r.width, r.height));
}
Now you can use it with your r1 and r2 rectangles when needed
printRectangleDetails(r1);
...
printRectangleDetails(r2);
If for some reason where you can't create separate method and use DRY principle you can do something like this:
lets say we have
String foo = "foo";
System.out.println(foo+" hello wordls"+ foo);
String bar = "bar";
System.out.println(foo+" hello wordls"+ foo);
and you want to replace foo in second print statement to bar. Using Alt + Shift + R (or from menu: Refactor -> Rename..) on second printing statement would rename all foo references . To prevent it redeclare your foo reference (compiler will give you error, but don't worry, we will later remove it, it is helpful only while renaming process) just before statements from which you want to change foo to bar like
String foo = "foo";
System.out.println(foo+" hello wordls"+ foo);
String bar = "bar";
String foo = "whatever";
// ^^^
System.out.println(foo+" hello wordls"+ foo);
Now use Alt + Shift + R on this new duplicate foo and eclipse will look for foo from this new reference, and ignore earlier foos, so you should be able to see something like
(as you can see first two foo are not selected for renaming)
so you can change it to bar like
String foo = "foo";
System.out.println(foo+" hello wordls"+ foo);
String bar = "bar";
String bar = "whatever";
System.out.println(bar+" hello wordls"+ bar);
and after that just removed this additional String bar = "whatever"; since you don't need it any more.
BUT BE CAREFUL. This way you will rename all foo variables after duplicate foo, not only those in System.out.println(foo+" hello wordls"+ foo); which you wanted to rename. To make sure you are not changing anything you don't want to, place code you want to change at the end of your method (where you are sure there is no foo which shouldn't be changed after it). After you are done move your changed code to place you want.

Related

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:", ""));

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.

Java Android, listing multiple stored values in settext

I have a blank text field which I'm trying to use settext on after a button click, so I can change the blank text field to the text in the stored variables.
The variables are two ints which I've converted to string and I'm trying to do the following:
blankText.setText("" + var1);
currently works but when I try to add the other variable in the same field I'm not sure how to go about it?
For example I tried to do: blankText.setText("" + var1, var2) which throws an error. I want them listed side by side in the same text field. is this possible?
To combine Strings, use +:
blankText.setText(var1 + var2);
blankText.setText(var1 + " " + var2);
blankText.setText("" + var1 + " " + var2);
if you want to space your variables
If you are trying to add or append the text in already written textview then use
blankText.append(""+var2);
if you want to write two variables in textview at the same time then use the concatination symbol
blankText.setText(" " + var1 + " " + var2); // also will remove the previous written text

Eclipse: change description of variable in debug mode

Can I change description of variable?
I want to see my own string at this place. I want generate this string by myself.
For example
"RTKAccount number=111 and FGSFDS"
insead of
"RTKAccount (id=830039244504)".
I tried to change toString() method in my class, but it did not work.
public String toString() {
return "RTKAccount id=" + this.id + " number=" + this.number;
}
What you're searching for are the detail formatters.
Right-click on the variable in the Variable view and select "New Detail Formatter...". In the wizard type this into the big text area:
"RTKAccount id=" + id + " number=" + number
And there you have it ;-)
You can change the value of a variable by right clicking it -> Change value

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