Ok so this is my homework assignment, and I am having a heck of a time figuring out how to correctly use overloading to allow for a certain number of terms to print out.
"Create a class that contains a method that accepts an integer from the user to display the next 5 terms in the following pattern: (n-7) * 3.
So, if the user enters 5, the output should be:
-6
-39
-138
-435
-1326
Add an overloaded method so the user can enter how many termss they want to print out in a pattern:
So, the user would enter 5 as the starting number and 3 as the number of terms to print out in the pattern.
The output would be:
-6
-39
-435
Add different method that displays the formula and provides calculation to the formula: (should get starting number from user input) and prints out the next 5 terms.
(5-7) * 3 = -6
(-6-7) * 3= -39
(-39-7) * 3 = -435
Add an overloaded method that displays the formula and the calculation to the formula and takes in how many times it should print: (should get from user input).
For example: User enters 5 as the starting number and print out 4 times.
(5-7) * 3 = -6
(-6-7) * 3= -39
(-39-7) * 3 = -435
(-435-7) * 3 = -1326
Specifics:
You have a separate class that contains all your methods.
You should have 4 methods in this class.
Your main should call these four methods getting user input where appropriate.
"
I'm not asking for anyone to do this for me, I just would appreciate a steer in the right direction.
At the moment trying to collect the number of terms wanted by the user in the main class then pass it to the Numberpattern class and then from their have the program determine which Calc method to use is not working.
Okay i feel dirty for doing your homework for you but i'll get you started
the first method is
public void printPattern(int n){
int prevAnswer = n;
for(int i =0; i < 5; i ++){
int newAnswer = (prevAnswer - 7) * 3;
System.out.println(newAnswer);
prevAnswer = newAnswer;
}
}
The first overload is
public void printPattern(int n, int c){ //this is the overload
public void printPattern(int n){
int prevAnswer = n;
for(int i =0; i < c; i ++){ // i < c to print that many numbers in the sequence
int newAnswer = (prevAnswer - 7) * 3;
System.out.println(newAnswer);
prevAnswer = newAnswer;
}
}
To Overload a method simply provide different parameters and write the extended new functionality
By overloading a method, you are using the same methods with different parameter lists. This allows the program to decide which method is best to be used with only one call of that method name.
It looks like your first method would have a loop of a fixed number and only one parameter (n). Your second method will have the same name, but now allow for two parameters - the (n) and the number of times to loop.
public static void nextTerms (int n) {
Your fixed count loop and print out of n code...
}
public static void nextTerms (int n, int loopCount) {
Your changeable loopCount count loop and print out of n code...
}
To run that nextTerms method, your main Class could either call:
nextTerms(5);
or
nextTerms(5, 3);
The program will then decide which of the two nextTerms methods are appropriate.
For more information, I suggest - http://docs.oracle.com/javase/tutorial/java/javaOO/methods.html
Cheers!
Chris
Related
I have code that has multiple methods and we're suppose to call said methods to help us format an image made from characters. The image is a cake and uses characters like "=", "\", "^" and "/" among others I have yet to get too. Anyways using odd user input between 3 and 9 (3,5,7,9), we're suppose to format it so it prints out the other method and then the one before it. So If one method prints out "[|_______||_______||_______|]" and the other one prints out "[|___||_______||_______|____|]" with it's size varying with user input. If input is 3 it's suppose to print out both methods once as the hint was that it uses half the user input to decide how often to print something. The problem goes when I go beyond 3 to 5 or 7 as I get something like
/^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\
[|_______||_______||_______||_______||_______|]
[|_______||_______||_______||_______||_______|]
[|___||_______||_______||_______||_______|___|]
[|_______||_______||_______||_______||_______|]
[|_______||_______||_______||_______||_______|]
[|___||_______||_______||_______||_______|___|]
\=============================================/
It's suppose to print one then the other, not two at once. Not only that but in total the methods are only suppose to print out 4 times if it's 5 so I'm suppose to get something like this instead. I think it's how I formatted my for loops for that method but I could be wrong, thank you in advance to anyone willing to help.
/^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\
[|_______||_______||_______||_______||_______|]
[|___||_______||_______||_______||_______|___|]
[|_______||_______||_______||_______||_______|]
[|___||_______||_______||_______||_______|___|]
\=============================================/
My "drawFullBrick" method prints out the [|_______||_______||_______||_______||_______|] part while the "drawHalfBrick" prints out the [|___||_______||_______||_______||_______|___|] part
public static void drawBrickStack (int sizeParam) {
System.out.print("/");
for (int count = 0; count < sizeParam * 9; count++)
System.out.print("^");
System.out.print("\\ \n");
for (int count = 0; count < sizeParam/2; count++)
{
for (int nestedCount = 0; nestedCount < sizeParam/2; nestedCount++)
{
drawFullBrickLine(sizeParam);
}
drawHalfBrickLine(sizeParam);
}
I have a 10x10 multiplication table. I need to code in so that when a user inputs a certain number, 50 for example, the numbers >50 are replaced by a character and the rest remain the same.
I know how to do this using strings but I have no clue how to do this in this situation. Any help will be appreciated.
public class task4{
public static void main(String args[]){
int Multiples = 10;
System.out.format(" Table");
for(int z = 1; z<=Multiples;z++ ) {
System.out.format("%5d",z);
}
System.out.println();
System.out.println("-------------------------------------------------------------------------------------------------------");
for(int i = 1 ;i<=Multiples;i++) {
System.out.format("%5d |",i);
for(int j=1;j<=Multiples;j++) {
System.out.format("%5d",i*j);
}
System.out.println();
}
}
}
That seems to be simple enough problem, basically you have table drawing code, your for loops, so we function that off into a nice little method public void drawTable(){} which we call to draw the table initially, but we also provide an overloaded version which takes a number public void drawTable(int maxDispNum){} and this method is the same except if i*j >maxDispNum we print a character instead. then in main we can simply while(true){ read val; drawTable(val);}
alternativley if you want to maintain a permanent record of what's been removed stored the table in an array, 10*10 in your case and use some marker, -1 works here to indicate removed, and simply check for that in your draw method,
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am preparing for an exam next week, and I decided to look for some exam questions online for better preparation.
I came across this question and the answer is c. But I really want to know how or the step by step process to answer to answer a question like this. The part where I got stuck is trying to logically understand how a int m = mystery(n); How can a number equal a method? Whenever I get to a question like this is their anything important I should breakdown first?
private int[] myStuff;
/** Precondition : myStuff contains int values in no particular order.
/*/
public int mystery(int num)
{
for (int k = myStuff.length - 1; k >= 0; k--)
{
if (myStuff[k] < num)
{
return k;
}
}
return -1;
}
Which of the following best describes the contents of myStuff after the
following statement has been executed?
int m = mystery(n);
(a) All values in positions 0 through m are less than n.
(b) All values in positions m+1 through myStuff.length-1 are
less than n.
(c) All values in positions m+1 through myStuff.length-1 are
greater than or equal to n.
(d) The smallest value is at position m.
(e) The largest value that is smaller than n is at position m.
See this page to understand a method syntax
http://www.tutorialspoint.com/java/java_methods.htm
int m = mystery(n); means this method going to return int value and you are assigning that value to a int variable m. So your final result is m. the loop will run from the array's end position to 0. loop will break down when array's current position value is less than your parameter n. on that point it will return the loop's current position. s o now m=current loop position. If all the values of the loop is greater than n it will return -1 because if condition always fails.
Place the sample code into a Java IDE such as Eclipse, Netbeans or IntelliJ and then step through the code in the debugger in one of those environments.
Given that you are starting out I will give you the remainder of the code that you need to make this compile and run
public class MysteriousAlright {
private int[] myStuff;
public int mystery(int num)
{
for (int k = myStuff.length - 1; k >= 0; k--) {
if (myStuff[k] < num) {
return k;
}
}
return -1;
}
public static void main(String[] args) {
MysteriousAlright ma = new MysteriousAlright();
ma.setMyStuff(new int[] {4,5,6,7});
int m = ma.mystery(5);
System.out.println("I called ma.mystery(5) and now m is set to " + m);
m = ma.mystery(3);
System.out.println("I called ma.mystery(3) and now m is set to " + m);
m = ma.mystery(12);
System.out.println("I called ma.mystery(12) and now m is set to " + m);
}
public void setMyStuff(int[] myStuff) {
this.myStuff = myStuff;
}
}
You then need to learn how to use the debugger and/or write simple Unit Tests.
Stepping through the code a line at a time and watching the values of the variables change will help you in this learning context.
Here are two strategies that you can use to breakdown nonsense code like that which you have sadly encountered in this "educational" context.
Black Box examination Strategy
Temporarily ignore the logic in the mystery function, we treat the function as a black box that we cannot see into.
Look at what data gets passed in, what data is returned.
So for the member function called mystery we have
What goes in? : int num
What gets returned : an int, so a whole number.
There are two places where data is returned.
Sometimes it returns k
Sometimes it returns -1
Now we move on.
White Box examination Strategy
As the code is poorly written, a black box examination is insufficient to interpret its purpose.
A white box reading takes examines the member function's internal logic (In this case, pretty much the for loop)
The for loop visits every element in the array called myStuff, starting at the end of the array
k is the number that tracks the position of the visited element of the array. (Note we count down from the end of the array to 0)
If the number stored at the visited element is less than num (which is passed in) then return the position of that element..
If none of elements of the array are less than num then return -1
So mystery reports on the first position of the element in the array (starting from the end of the array) where num is bigger than that element.
do you understand what a method is ?
this is pretty basic, the method mystery receives an int as a parameter and returns an int when you call it.
meaning, the variable m will be assigned the value that returns from the method mystery after you call it with n which is an int of some value.
"The part where I got stuck is trying to logically understand how a int m = mystery(n); How can a number equal a method?"
A method may or may not return a value. One that doesn't return a value has a return type of void. A method can return a primitive value (like in your case int) or an object of any class. The name of the return type can be any of the eight primitive types defined in Java, the name of any class, or an interface.
If a method doesn't return a value, you can't assign the result of that method to a variable.
If a method returns a value, the calling method may or may not bother to store the returned value from a method in a variable.
Hello I am trying to create a method in Java that Accepts an integer from the user. Calculate and display how many occurences of the integer are in the array(i'm Creating a random array) as well as what percentage of the array values is the entered integer.
This is how i create my Array:
public void fillVector ( )
{
int myarray[] = new int [10];
for (int i = 0 ; i < 10 ; i++)
{
myarray [i] = (int) (Math.random () * 10);
}
}
Any sugestions how can i do to accomplish this ?
This seems like a homework to you so I am not gonna give you the full solution but I will break down the steps of what you need to do in order to solve your problem. You have to find out how to code those steps yourself, or at least provide some code and your specific problem because your question is too vague right now.
Ask the user to input the number.
Store that number somewhere.
Check each cell of the array for that number. If you find one appearance
increase the counter and continue until the end of your index.
Print out the appearances of the given number.
Print out the percentage of the cells containing the given value to the total amount of cells.
As I can see from your code (if it's yours) you are capable to pull this off on your own. It shouldn't be too hard.
New to Java, basically started yesterday.
Okay, so here's the thing.
I'm trying to make an 'averager', if you wanna call it that, that accepts a random amount of numbers. I shouldn't have to define it in the program, it has to be arbitrary. I have to make it work on Console.
But I can't use Console.ReadLine() or Scanner or any of that. I have to input the data through the Console itself. So, when I call it, I'd type into the Console:
java AveragerConsole 1 4 82.4
which calls the program and gives the three arguments: 1, 4 and 82.4
I think that the problem I'm having is, I can't seem to tell it this:
If the next field in the array is empty, calculate the average (check Line 14 in code)
My code's below:
public class AveragerConsole
{
public static void main(String args[])
{
boolean stop = false;
int n = 0;
double x;
double total = 0;
while (stop == false)
{
if (args[n] == "") //Line 14
{
double average = total / (n-1);
System.out.println("Average is equal to: "+average);
stop = true;
}
else
{
x = Double.parseDouble(args[n]);
total = total + x;
n = n + 1;
}
}
}
}
The following error appears:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at AveragerConsole.main(AveragerConsole.java:14)
for(String number : args) {
// do something with one argument, your else branch mostly
}
Also, you don't need n, you already have the number of arguments, it's the args length.
This is the simplest way to do it.
For String value comparisons, you must use the equals() method.
if ("".equals(args[n]))
And next, the max valid index in an array is always array.length - 1. If you try to access the array.length index, it'll give you ArrayIndexOutOfBoundsException.
You've got this probably because your if did not evaluate properly, as you used == for String value comparison.
On a side note, I really doubt if this if condition of yours is ever gonna be evaluated, unless you manually enter a blank string after inputting all the numbers.
Change the condition in your while to this and your program seems to be working all fine for n numbers. (#SilviuBurcea's solution seems to be the best since you don't need to keep track of the n yourself)
while (n < args.length)
You gave 3 inputs and array start couting from 0. The array args as per your input is as follows.
args[0] = 1
args[1] = 4
args[2] = 82.4
and
args[3] = // Index out of bound
Better implementation would be like follows
double sum = 0.0;
// No fault tolerant checking implemented
for(String value: args)
sum += Double.parseDouble(value);
double average = sum/args.length;