Simplify Two Large Methods Into One Similar Method?
Jan 4, 2015
Right now I have 12 methods, each roughly 40 lines long, and I am contemplating whether I should simplify some of the pairs (12 methods, but every other method is very similar to each other, so 6 pairs) into one method.
The main pro of simplifying them is that my class will be much smaller, right now its about 555 lines of code. However a con is that it might not be as straight forward, at first glance at least.
Here is what I am talking about. Two original methods that are very similar:
void rotateRightClockwise(int rotations){//rotates FRONTS's RIGHT! CONFIRMED
String a, b, c;//temp values
for(int i = 1; i <= rotations; i++){//confirmed
a = cube.cube[1][2].square[2];//3
b = cube.cube[1][2].square[5];//6
c = cube.cube[1][2].square[8];//9
[Code] ....
The only difference between these two methods, other than the last chunk for each method, is the I have to change the 2nd square bracket, [], values from lines 9-23 for cube[][]. That's it. So I am thinking of combining them into something like this...
private void rotateRight(int rotations, int x, int y){
String a, b, c;//temp values
for(int i = 1; i <= rotations; i++){//confirmed
a = cube.cube[1][2].square[2];//3
b = cube.cube[1][2].square[5];//6
c = cube.cube[1][2].square[8];//9
[Code] .....
And then after calling this similar method, I would finish off the last chunk from each methods, since they are too different (ie lines 26-38).
The reason why I ask this is because I am trying to build up my portfolio and I want to know if the employer would look at this and say "that was a good move by compacting your code" or "this is not that straight forward".
View Replies
ADVERTISEMENT
Oct 6, 2014
Write a method called largerAbsVal that takes two integers as parameters and returns the larger of the two absolute values. A call of largerAbsVal(11, 2) would return 11, and a call of largerAbsVal(4, -5) would return 5.
I have tried this code using methods in the Math Class but I am getting an error in Practice-it that says
Line 4
Your method's return type is void, which means that it does not return a value. But your code is trying to return a value. This is not allowed.
cannot return a value from method whose result type is void
return Math.max(Math.abs(Num1), Math.abs(Num2));
Here is my code. What I am doing wrong?
public static void largerAbsVal (int Num1, int Num2)
{
return Math.max(Math.abs(Num1), Math.abs(Num2));
}
View Replies
View Related
May 24, 2014
I m trying to simplify an if condition as much as possible and i m curious if it can be made more short then i managed to .The problem is simple , a integer number with 3 digits is generated and the user is asked to input another 3 digits integer number ... One of the conditions that need to be verified is if all the digits in each number match but not exactly ( aka 123 and 132 ) .Using only an if statement to verify this what is the most short condition that can be checked to identify when the digits in a 3 digits number match the digits of another 3 digits integer number (not interested if they match exactly) .
The simplest condition i managed to find is :
else if (guessDigit1 + guessDigit2 + guessDigit3
== lotteryDigit1 + lotteryDigit2 + lotteryDigit3
&& (guessDigit1 == lotteryDigit1 || guessDigit1
== lotteryDigit2 || guessDigit1 == lotteryDigit3)
&& (guessDigit2 == lotteryDigit1 || guessDigit2
== lotteryDigit2 || guessDigit2 == lotteryDigit3)) {
System.out.println("Match all digits: you win $3,000");}
Is there a better(shorter ) condition that can be used ?
View Replies
View Related
Apr 6, 2014
I am trying to figure out how I can most easily make it easier to make new types of units in my game. I have buildings and ships, and would like to know how I could make it easy to add new units. I have been recently told about interfaces, and have worked with inheritance a little bit.
What I would like to able to do is have it so that all of the variables and methods common to all ships could be stored in a superclass or interface, and same with the buildings. I would also like to be able to assign behaviours to the buildings and ships, maybe as interfaces, which could contain all of the methods and variables required for the functions of that ship or building.
For example, creating a new type of building that can shoot, build ships, and can regenerate nearby ships. So it would possible inherit all of the variables and methods common to all buildings, such as health, image, x, y, getX(), getY() etc. But it would then also gain the variables and methods essential for its functionality, such as shootRange, shoot(), regenRate, etc.
How could this best be achieved?
View Replies
View Related
Feb 16, 2014
I've looked around a bit myself online (admittedly for only a few minutes) and have yet to come across a straight-forward object for date selection. Does Java offer something like that?what should be a simple task?
View Replies
View Related
Apr 25, 2014
1.Write a program to produce a similar output for n characters, where n is a odd number. The below output is for n=7.
Java Code:
A B C D E F G F E D C B A
A B C D E F F E D C B A
A B C D E E D C B A
A B C D D C B A
A B C C B A
A B B A
A A
mh_sh_highlight_all('java');
View Replies
View Related
Jul 26, 2014
I have the following code:
public class CollisionManager<T> {
private boolean collision = false;
private T mainEntity;
public <T extends Entities> void handleCollision(T mainEntity, T secondEntity){
this.mainEntity = mainEntity; // This is illegal.
}
}
Why "this.mainEntity = mainEntity" is incorrect and also show me the correct way to achieve this?
The error I am getting is "Type mismatch: cannot convert T to T"
View Replies
View Related
Feb 17, 2014
so basically what i'm trying to do is add TWO methods under the calculateMPG method which both need the result of calculateMPG. i.e. if calculateMPG < 15 your car is a gas hog, else your car is an economy car. i tried storing calculateMPG's result into a variable, and writing the two new methods that way, but being either inside OR outside of the calculateMPG method, the program can't seem to find it to reference for the two new methods. here is what i'm working with:
class Car
{
// instance variables
double startMiles; // Stating odometer reading
double endMiles; // Ending odometer reading
double gallons; // Gallons of gas used between the readings
[code]...
again, i tried creating a reference variable for the result of calculateMPG but everywhere i put it when MilesPerGallon ran, it could not find that variable. i have a feeling this is something simple that i'm overlooking, but i'm hitting a wall and would love any input!
View Replies
View Related
Sep 30, 2014
This current one is to calculate a planes holding pattern. I have to write a method to prompt user to enter speed in knots, then it converts it to km/hr. Another method to calc. pattern width using the speed, another method to calc. pattern length, than a main method which would call and print out the speed in knots, speed in km, pattern width and length.My current problem is on the second method. It works in that I can enter the values and it gives me the correct answers, however it's asking me to enter the speed twice, instead of just once. Anything I try just results in errors and won't compile.
import java.util.Scanner ;
//main method
public class TitleRemoved {
public static void main(String[] args) {
double airSpeedKm = airSpeedOts () ;
System.out.println("That speed is " + airSpeedKm + " km/hr.") ;
[code].....
I want my code to not only work, but be organized and easily readable as well, so I want to avoid bad habits.
View Replies
View Related
Aug 6, 2014
I have a question about a method I have. In my game, I had a move method to move my player left and right, and originally this method was huge, as it also took care checking collisions and a few other things. I broke it up a bit and put the collisions in their own methods and call them from again another method... Here is an extract which I hope illustrates my point:
private static final double MOVE_SPEED = 0.2;
private static final double MAX_MOVE_SPEED = 3.5;
private static final double STOP_SPEED = 0.18;
private double xPos;
private double yPos;
[Code] .....
Something I thought might be a good idea is to check the direction collision when im doing the calculations for that direction:
if(moveLeft) {
dx -= MOVE_SPEED;
(dx < -MAX_MOVE_SPEED) {
dx = -MAX_MOVE_SPEED;
}
checkLeft();
}
But then I would also need to check it when I'm slowing down the left movement:
if(dx < 0.0) {
dx += STOP_SPEED;
if(dx > 0.0) {
dx = 0.0;
}
checkLeft();
}
Then I thought instead i can check it after both of these steps:
if(moveLeft || dx < 0.0) {
checkLeft();
}
I guess my question is quite general: How much is acceptable to break up a method? How many chains of method calls is acceptable? Is it ok to call the same method from different nearby places?
View Replies
View Related
Jan 15, 2015
a. Create an application named ArithmeticMethods whose main() method holds two integer variables. Assign values to the variables. In turn, pass each value to methods named displayNumberPlus10(), displayNumberPlus100(), and displayNumberPlus1000(). Create each method to perform the task its name implies.
b. Modify the ArithmeticMethods class to accept the values of the two integers from a user at the keyboard.
View Replies
View Related
Aug 25, 2014
I am having an array of strings and i want to find out whether these strings contained in the array contain a similar character or not.For example i am having following strings in the array of string:
aadafbd
dsfgdfbvc
sdfgyub
fhjgbjhjd
my program should provide following result: 3 because i have 3 characters which are similar in all the strings of the array(f,b,d).
View Replies
View Related
Mar 16, 2012
Is there a way to create a flipbook using swings similar to flash flipbook.
View Replies
View Related
Mar 13, 2015
The intentions of this program is to prompt a user to enter a file name, and then reads the file. The program will prompt the user to enter a word that needs to be corrected. So lets say I have a text file containing "My name is OP and I Like goind to the Park!" I want to change "goind" to "going",
Now, my second method "isSimilar" executes a similar word with more than one same letter and same length, but I dont know how to execute that whole thing in my third method "correctThisLine" . How I can call that isSimilar method and read in that text file and change that word into that?
import java.util.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class WahidMuhammadA3Q2{
String fileName = "AutoCorrectMe.txt";
public static void main (String [] args){
[Code] ....
View Replies
View Related
Feb 7, 2015
I am trying to pass an object of type Product p to my editProduct method, however trying to call p.getName(); doesn't work and throws a NullPointerException. The same kind of thing works for my displayRecord method (in a different class) and I can call .getName() on Product p, also passed as an argument to that method. Below is my editProduct class. The NullPointerExcepion is being thrown at line 61 (i.e., nameField.setText(p.getName());).
I don't know if I explained right, so here's a line thing of how the classes relate:
Search >>>(field.getText())>>> displayRecord(Product p) >>>editProduct(p)>>> EditProduct
And as a side note: adding the line p = new Product(); fixes it and successfully runs the class (including the Save and Quit parts) but obviously I want it to specifically refer to the Product I pass to the method.
Java Code:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.util.ArrayList;
import javax.swing.BorderFactory;
[Code] ....
I'm asking a question because I don't understand how Product p could possibly be null, because the argument is passed through my DisplayRecord class, which also takes a Product p argument and works. In that class, I have declared Product prod = p; and prod is what I am passing to editProduct.
View Replies
View Related
Oct 31, 2014
I found an exercise online to create a small program . I have this code that I have done so far:
import java.util.Scanner;
public class Test {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
long a = sc.nextLong(); long b = sc.nextLong();
long count = 0; // counter
[code]....
The program should read the numbers a and b and list how many numbers between a and b are divisible by either 2, 3 or 5. If the user types the number 5 and then 8.... it would look at all the numbers in between - 5,6,7,8 and check if any of them are divasable by either 2,3 or 5. And since the numbers 5,6,8 are it would return the number 3 to the user..Now the problem is that this program only works for small numbers, but when I try to input numbers such as 123456789012345678 and 876543210987654321... it doesn't run at all.
So there needs to be a quicker way on how the program checks the numbers divisibility instead of checking each one. Here is where I am lost. How to fix the program that it will read bigger numbers such as a=123456789012345678 b=87654321098765432..There must be a quicker way ...something that can modify the code so it finishes in the matter of seconds not hours. Something that will fasten the process of checking if the numbers are dividable.
View Replies
View Related
Nov 6, 2014
I want to migrate some large application code base's from jdk1.4 to jdk1.6.
1. Is there any tool/s available that can be used for this migration (Because manually it is very difficult for a application with almost 15,000 java files and 15 * 10^6 KLOC within a limited time frame).
2. Steps that should be followed in such cases.
3, If any tool is not available for such activity what are the salient points that are needed to be considered while migrating.
View Replies
View Related
Aug 16, 2014
I have a simple display method in a java project as given below:
public void displayInfo() {
for(Student student : studentdB){
System.out.println(student.toString() + "
");
}
I would want to use one of Swing components to display the students instead of displaying them on the stdout. How I could go about calling this method in some Swing components that can display all the students in the studentdb?
View Replies
View Related
Mar 14, 2015
I need to encrypt/decrypt file contents using RSA . But the default nature of RSA I could not upload files larger than 177 bytes for key length 1024 bytes . How it can avoid , I look it for a 100 times yet...
I attach my encryption files here ...
See attached files for more details ...
View Replies
View Related
Sep 3, 2014
What I'm tasked to do, is to make a simple Java class that forms a "V" based on whatever height the user would desire, made out of stars "*", and spaces " ".
For example, if a user desires a "V" with a height of 3, it would look print out something like;
* *
* *
*
Where a "V" with a height of 5 would look something like:
* *
* *
* *
* *
*
(That one didn't look too good, but you get the point, it's suppose to be 5 "high" and shaped like a "V"). The problem I have, is that I don't see what loops within loops within loops I would need to build something like this.
All the easy stuff like asking the user what height they want and such, I can handle, but I don't see how this thing is suppose to be coded, to print out a decent-looking and right-sized "V" in the console.
public static void main(String[] args) {
int height = 3;
for (int i = 0; i < height; i++) {
for (int j = 0; j < 2/(height+1)+1; j++) {
if(j == i) {
[Code] ....
Looked like something of a good start, and it drew me half (!) of the "V" in the size I wanted. Am I on to it here, or am I on the moon in terms of progress? I need the entire "V", not just a nice "".
View Replies
View Related
Dec 9, 2014
I am calculating an exponent without using BigInteger. However, I find that using long is not enough to handle my code. Is there a way to handle large numbers without using BigInteger?
public static void main (String[] args){
int base = 3;
int exponent;
long total = 1L;
boolean n;
Scanner input = new Scanner(System.in);
[code].....
View Replies
View Related
Oct 10, 2013
I have an application which has 10 million rows and 1000 columns in Oracle. Each value has a different set of calculations that are stored in User Defined PLSQL functions.
Data is displayed in form of data grid. When a user updates any value, the calculation is performed using plsql function and value is stored in database. Is there an easy way through which calculation is performed on the fly and i get maximum performance ?
View Replies
View Related
Dec 4, 2014
I'm programming an android app where I want to send large sets of data from an MySQL Table to the app and write this data to an SQLite database.So I know i have send an HttpRequest and I can send data with json, but how can I handle large datasets like tables?I think its no good idea to just concatinate a string together in php and then send it?
View Replies
View Related
Mar 2, 2015
In my programming class we need to create a large test array of Longs to iteratively sum/reverse the array and recursively sum/reverse the array.creating the array and where to go from there.
View Replies
View Related
Oct 8, 2014
We have a website used for downloading large files as large as 6gb and sometimes larger. We have all files in FTP server. The websit is JSP/Servlet /Tomcat combination. Below is code sample. I need a solution to increase the download speed. I understand it is bound to network bandwidth but are the steps that we need to take while we have such large files.I read about multipart downloads,gunzip streaming.
//first connect to FTP server and login and keep connection
Calendar cal=Calendar.getInstance();
startTime=cal.getTime();
fis=ftp.downloadFile(ftpclient,separator+resourceID);
response.setContentType("application/*");
response.setHeader("Content-Disposition", "attachment; filename="" + downloadFileName + "";");
byte[] bytes = new byte[1024];
[code]....
View Replies
View Related
Apr 1, 2015
I've written a small program that does factorial by recursion.
I think it works properly for small input like 10, but it stops working properly
if the input becomes large, like 100.
If I try any large input, I get a zero.
Why I am getting 0s.
import java.util.Scanner;
public class myFactorialRecursion {
public static void main(String[] args) {
[Code].....
View Replies
View Related