So I'm creating a method in that is supposed to print the numbers between two specified numbers. I had it setup before in the main method but i can figure out how to make a method and call it into the main method. What my program does right now is it only prints what "int between" is equal to. I don't want anyone to just type the code out for me, i'm just looking for tips on what i should change. Last time i asked a question someone proceeded to just answer with code and it did not help me to learn anything.
So my question is what is causing the program to only display what between is equal to? I know that I need a value for the if loop to return something, but it needs to return the numbers between num1 & num2. My Professor Also said that the method needs to be "public static void Printer(int num1, int num2)" is that even possible? I kept getting an error so I switched to "int Printer".
package nortonaw_Assignment8;
public class Nortonaw_Assignment8 {
public static void main(String[] args) {
int between;
between = Printer(5, 20);
System.out.println(between);
}
public static int Printer (int num1, int num2){
int between = 0;
for (;num1<=num2; num1++);
return between;
}
}
1) There's a difference between printing out a value and returning a value.
When you"print" a value in a function, you are just writing out the value to screen or some other medium , but when you use the return statement, you are passing what you are returning to the caller of your function as well as control.
** I hope that makes sense to you?
2)"public static void Printer(int num1, int num2)" is possible.
currently your method is designed to return only one single number, so either you return a collection of numbers are you print the numbers inside Printer, in this case you can use the method signature suggested by your professor.
So I would write it like this:
public static void main(String[] args) {
Printer(5, 20);
}
public static void Printer (int num1, int num2) {
for (int i=num1;i<=num2; i++) {
System.out.println(i);
}
}
EDIT:
Note that I introduced a additional counter variable i because I think num1 and num2 should not be changed as they define the boundary of your range.
package printingTasks;
public class Printer {
public static void main(String[] args) {
printInBetween(25, 30); //Would print 26 -> 29
}
/*
* You don't need to return something if you just want to print it out to the console.
* So you can use void as return type
*/
public static void printInBetween(final int leftBoundary, final int rightBoundary){
/**
* Calculate the first number which should be printed.
* This number would be the leftBoundery plus one
* This number will be the starting point of your loop
*/
final int firstNumber = leftBoundary + 1;
// final int firstNumber = leftBoundary; //if you want to include the left boundary
for (
int currentNumber = firstNumber; //Set the counter of the the loop (currentNumber) to the first valid number
currentNumber < rightBoundary; //Run the loop while the loop counter is less than the rightBoundary
// currentNumber <= rightBoundary; //If you want to include the right boundary
currentNumber++ //Increment the loop counter with each iteration
){
/**
* In each iteration you will print the current value of the counter to the console
* Because your counter (currentNumber) will be incremented from the first valid number
* to the last number before the right boundary you will get all numbers between the two
* boundaries.
*/
System.out.println(currentNumber);
}
}
}
Your teacher wants you to print from the Printer method not directly in the main method. All the main method should be doing is calling the Printer method.
Here is the full snippit:
package nortonaw_Assignment8;
public class Nortonaw_Assignment8 {
public static void main(String[] args) {
Printer(5, 20);
}
public static void Printer (int num1, int num2) {
for (int i = num1+1;i<=num2-1; i++) {
System.out.println(i);
}
}
}
Related
I'm trying to write a recursive method in Java to find the base 2 log for multiples of 2.
I've successfully computed the log using this recursive method.
import java.util.*;
class temp
{
static int log(int number)
{
if(number==1)
return 0;
return log(number/2)+1;
}
public static void main(String s[])
{
Scanner input=new Scanner(System.in);
System.out.println("Enter Multiple of 2:");
System.out.println("Log is:"+log(input.nextInt())); //calling log with return value of nextInt()
}
}
Where I've run aground is trying to implement the same program using a different method , a method where i start multiplying from 2 in recursive calls until it becomes equal to the given number. Here's what i've tried:
class logarithmrecursion
{
static int step=1;
static int log(int number)
{
final int temp=number;
if(number>=temp && step!=1)
return 0;
step++;
return log(number*2)+1;
}
}
During the first call, number is equal to temp so i use a step variable to prevent the execution of the termination condition.If i don't use "number" variable in the recursive call, i don't have a way to accumulate the previous product but number variable is already equal to temp and will trigger the termination condition in the next recursive call , thus always giving output 1.
What can i do to make this program work?
The first, reducing, version has a fixed termination value of 1.
But the second version's termination depends on the number, so you have to pass that into the recursive call. So, your main function calls a private recursive version:
static int log(int number) {
return log(number, 1);
}
private static int log(int number, int current) {
return current < number ? log(number, current * 2) + 1 : 0;
}
Note: Your algorithm rounds the value up. To give the (more expected) rounded down result, which agrees with (int)(Math.log(i) / Math.log(2)), use this variation:
private static int log(int number, int current) {
return current <= number / 2 ? log(number, current * 2) + 1 : 0;
}
This kind of pattern - using a wrapper function - is common where initial state of the recursion needs to setup once, but we don't want to burden the caller with having to know about what is an implementation choice.
Your first method may also be coded as one line:
static int log(int number) {
return number == 1 ? 0 log(number/2) + 1;
}
try this:
import java.util.Scanner;
public class LogTest
{
static int calLog(final int number)
{
if(number < 2) {
return 0;
}
return log(number, 2, 1);
}
static int log(final int number, final int accumulated, final int step)
{
if(accumulated >= number) {
return step;
}
return log(number, accumulated * 2, step+1);
}
public static void main(String s[])
{
Scanner input=new Scanner(System.in);
System.out.println("Enter Multiple of 2:");
System.out.println("Log is:"+calLog(input.nextInt())); //calling log with return value of nextInt()
}
}
hello in the code below I am sorting (sort method) a small array to find the largest number. I then print the answer in the (display method).
But to extend my knowledge I want to mass the max value back to them main in a return statement and then print from there....simply to learn how to return a value.
package christmas;
public class maxvalue
{
public static void main(String[] args)
{
int[] data={10,90,30};
sort(data);
System.out.println("\nmax number is :");
display(data);
System.out.println(data);
}
static int display(int num[])
{
System.out.print(num[0] + " ");
return num[0];
}
static void sort(int num[])
{
int i, j, temp;
for(i=0; i<num.length-i;i++)
{
for(j=0; j<num.length-i-1;j++)
{
if(num[j]<num[j+1])
{
temp = num[j];
num[j] = num[j+1];
num[j+1] = temp;
}
}
}
}
}
the output is:
max number is :
90 [I#4617c264
90 is the max value as printed by the display value. But after this I have a return of the max value and then I try and print the return. But instead of an integer it looks like a memory location is being printed.
Any ideas please - I am student but this is not homework - simply trying to catch up. I appreciate that there are more elegant ways to calculate the max value in an array but what I am trying to learn is the passing of arguments to and from a method.
The reason is that you are trying in your last System.out to print data, which is an array, and that's the reason why you see a memory address.Try printing display(data) and you will see as the output the desired number.
try System.out.println(data[0]);
data is your array therefore printing data without an index will only print its memory location
Instead of printing the returned value, you are printing the data array memory location:
System.out.println(data);
You should change that line with:
System.out.println(display(data));
With that line we have:
Your display method is called and it prints the max value
Your display method returns the max value
println takes that returned value and prints it
private static int sort(int[] array){
int a, b, max = 0;
for (int i = 1;//If i was 0, it would have thrown an ArrayIndexOutOfBoundsException.
i < array.length; i++){
a = array[i-1];//The first element in the array.
b = array[i];//The second one, and so on.
if (a > b) max = a;//Check the bigger number.
else max = b;
}
return max;
}
private static void display(int nr){
System.out.print(nr);//Or what you want to do with the number.
}
public static void main(String[] args){
int[] data={10,90,30};
display(sort(data));
//Or do it like this.
int max = sort(data);
display(max);
}
So I have this basic factorial calculator in java but I am having trouble modifying it to fit the exercise. It says: Modify the factorial
method to print its local variable and recursive-call parameter. For each recursive call,display the outputs on a separate line and add a level of indentation. I think Im having trouble understanding where the print statements should go. So does local variable = number and recursion call parameter = number-1. Here is my code so far.
public class Factorial {
private static String s1="";
public static long factorial(long number,long save) {
if (number <= 1) { //test for base case
System.out.printf("%s%d! = %d*%d!= ",s1,save,save,save-1);
s1 = s1 +" ";
return 1;
}
else{ //recursion step
return number * factorial(number - 1,save);
}
}
//output factorial for values 0-21
public static void main(String[] args) {
//calculate factorials 0-21
for (int counter = 0; counter <= 21; counter++){
long x = factorial(counter,counter);
System.out.printf("%d%n",x);
}
}
}
I think Im having trouble understanding where the print statements should go.
Yes, indeed. As you can see, the exercise states
Modify the factorial method to print its local variable and recursive-call parameter.
So, modify factorial instead of main. This way, each time factorial is invoked, you get a new line printed out, just as the exercise asks.
I'm in a beginning programming class, and a lot of this had made sense to me up until this point, where we've started working with methods and I'm not entirely sure I understand the "static," "void," and "return" statements.
For this assignment in particular, I thought I had it all figured out, but it says it "can not find symbol histogram" on the line in the main method, although I'm clearly returning it from another method. Anyone able to help me out?
Assignment: "You see that you may need histograms often in writing your programs so you decide for this program to use your program 310a2 Histograms. You may add to this program or use it as a class. You will also write a class (or method) that will generate random number in various ranges. You may want to have the asterisks represent different values (1, 100, or 1000 units). You may also wish to use a character other than the asterisk such as the $ to represent the units of your graph. Run the program sufficient number of times to illustrate the programs various abilities.
Statements Required: output, loop control, decision making, class (optional), methods.
Sample Output:
Sales for October
Day Daily Sales Graph
2 37081 *************************************
3 28355 ****************************
4 39158 ***************************************
5 24904 ************************
6 28879 ****************************
7 13348 *************
"
Here's what I have:
import java.util.Random;
public class prog310t
{
public static int randInt(int randomNum) //determines the random value for the day
{
Random rand = new Random();
randomNum = rand.nextInt((40000 - 1000) + 1) + 10000;
return randomNum;
}
public String histogram (int randomNum) //creates the histogram string
{
String histogram = "";
int roundedRandom = (randomNum/1000);
int ceiling = roundedRandom;
for (int k = 1; k < ceiling; k++)
{
histogram = histogram + "*";
}
return histogram;
}
public void main(String[] Args)
{
System.out.println("Sales for October\n");
System.out.println("Day Daily Sales Graph");
for (int k = 2; k < 31; k++)
{
if (k == 8 || k == 15 || k == 22 || k == 29)
{
k++;
}
System.out.print(k + " ");
int randomNum = 0;
randInt(randomNum);
System.out.print(randomNum + " ");
histogram (randomNum);
System.out.print(histogram + "\n");
}
}
}
Edit: Thanks to you guys, now I've figured out what static means. Now I have a new problem; the program runs, but histogram is returning as empty. Can someone help me understand why? New Code:
import java.util.Random;
public class prog310t
{
public static int randInt(int randomNum) //determines the random value for the day
{
Random rand = new Random();
randomNum = rand.nextInt((40000 - 1000) + 1) + 10000;
return randomNum;
}
public static String histogram (int marketValue) //creates the histogram string
{
String histogram = "";
int roundedRandom = (marketValue/1000);
int ceiling = roundedRandom;
for (int k = 1; k < ceiling; k++)
{
histogram = histogram + "*";
}
return histogram;
}
public static void main(String[] Args)
{
System.out.println("Sales for October\n");
System.out.println("Day Daily Sales Graph");
for (int k = 2; k < 31; k++)
{
if (k == 8 || k == 15 || k == 22 || k == 29)
{
k++;
}
System.out.print(k + " ");
int randomNum = 0;
int marketValue = randInt(randomNum);
System.out.print(marketValue + " ");
String newHistogram = histogram (randomNum);
System.out.print(newHistogram + "\n");
}
}
}
You're correct that your issues are rooted in not understanding static. There are many resources on this, but suffice to say here that something static belongs to a Class whereas something that isn't static belogns to a specific instance. That means that
public class A{
public static int b;
public int x;
public int doStuff(){
return x;
}
public static void main(String[] args){
System.out.println(b); //Valid. Who's b? A (the class we are in)'s b.
System.out.println(x); //Error. Who's x? no instance provided, so we don't know.
doStuff(); //Error. Who are we calling doStuff() on? Which instance?
A a = new A();
System.out.println(a.x); //Valid. Who's x? a (an instance of A)'s x.
}
}
So related to that your method histogram isn't static, so you need an instance to call it. You shouldn't need an instance though; just make the method static:
Change public String histogram(int randomNum) to public static String histogram(int randomNum).
With that done, the line histogram(randomNum); becomes valid. However, you'll still get an error on System.out.print(histogram + "\n");, because histogram as defined here is a function, not a variable. This is related to the return statement. When something says return x (for any value of x), it is saying to terminate the current method call and yield the value x to whoever called the method.
For example, consider the expression 2 + 3. If you were to say int x = 2 + 3, you would expect x to have value 5 afterwards. Now consider a method:
public static int plus(int a, int b){
return a + b;
}
And the statement: int x = plus(2, 3);. Same here, we would expect x to have value 5 afterwards. The computation is done, and whoever is waiting on that value (of type int) receives and uses the value however a single value of that type would be used in place of it. For example:
int x = plus(plus(1,2),plus(3,plus(4,1)); -> x has value 11.
Back to your example: you need to assign a variable to the String value returned from histogram(randomNum);, as such:
Change histogram(randomNum) to String s = histogram(randomNum).
This will make it all compile, but you'll hit one final roadblock: The thing won't run! This is because a runnable main method needs to be static. So change your main method to have the signature:
public static void main(String[] args){...}
Then hit the green button!
For starters your main method should be static:
public static void main(String[] Args)
Instance methods can not be called without an instance of the class they belong to where static methods can be called without an instance. So if you want to call your other methods inside the main method they must also be static unless you create an object of type prog310t then use the object to call the methods example:
public static void main(String[] Args)
{
prog310t test = new prog310t();
test.histogram(1);
}
But in your case you probably want to do:
public static String histogram (int randomNum)
public static void main(String[] Args)
{
histogram(1);
}
Also you are not catching the return of histogram() method in your main method you should do like this:
System.out.print(histogram(randomNum) + "\n");
Or
String test = histogram(randomNum);
System.out.print(test + "\n");
Static methods are part of a class and can be called without an instance but instance methods can only be called from an instance example:
public class Test
{
public static void main(String[] args)
{
getNothingStatic();// this is ok
getNothing(); // THIS IS NOT OK IT WON'T WORK NEEDS AN INSTANCE
Test test = new Test();
test.getNothing(); // this is ok
getString(); // this is ok but you are not capturing the return value
String myString = getString(); // now the return string is stored in myString for later use
}
public void getNothing()
{
}
public static void getNothingStatic()
{
}
public static String getString()
{
return "hello";
}
}
Void means the method is not returning anything it is just doing some processing. You can return primitive or Object types in place of void but in your method you must specify a return if you don't use void.
Before calling histogrom (randomNum) you need to either make histogram static or declare the object that has histogram as a method
e.g
prog310t myClass = new prog310t();
myClass.histogram()
It's pretty simple program:
Create a method for the calculate class that will take in two numbers and add them together (use class variables for this!). For an extra challenge, create more than one class method for this: one class method to take in the numbers and another to do the calculation.
Create a method to display the results of the calculation by displaying the contents of a class variable that holds the calculation results.
Create a main method that will declare an object of the calculate class and use all of the methods of that class.
This is what i've come up with but it won't let me pass any values to the calculator class because I don't have constructors yet I do have constructor method in getNum. Please help
public class MainCalc {
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
calculator calcOne = new calculator();
System.out.println("calcOne equals: " + calcOne.calculate());
}
class calculator
{
private int num1;
private int num2;
public int answer;
public void getNum(int i, int j)
{
num1 = i;
num2 = j;
}
public int calculate()
{
answer = num1 + num2;
return answer;
}
}
}
You want
public void getNum(int i, int j)
{
to be
public calculator(int i, int j)
{
A constructor has no return type and is otherwise essentially a function with the same name as the class, to keep it simple. Please look at oracle docs for more information.
And construct the calculator with 2 values like so.
new calculator(1,2);
Change
class calculator
to
static class calculator
because you are referencing it within the static context of your main method.
Try something like this:
public class MainCalc {
public static void main(String[] args) {
// TODO Auto-generated method stub
Calculator calcOne = new Calculator();
System.out.println("calcOne equals: " + calcOne.addTwoNumbers(10, 25));
}
static class Calculator {
private int num1;
private int num2;
private int answer;
public int addTwoNumbers(int i, int j) {
num1 = i;
num2 = j;
calculate(num1, num2);
return answer;
}
private void calculate(int i, int j) {
answer = i + j;
}
}
}
The addTwoNumbers method takes in two integers as paremeters, sets the class variables num1 & num2 equal to them. Then calls the calculate method which takes those two variables as inputs, performs the calculation & sets the answer variable equal to it. Then the addTwoNumbers method returns answer. This should meet your requirement that a separate method perform the calculation.