I'm not very experienced in making static methods...I wanted some practice and I'm having some problems. I'm trying to make a program where you input a number and it prints out all the squares less than b. For example, if you put in 100, it returns 0, 1, 4, 9, 16, 25, 36, 49, 64, 81.
I'm getting errors, though.
Illegal modifier for parameter getSquares; only final is permitted. This is on the line public static double getSquares(double b)
-The method getSquares(int) is undefined for the type Squares when I try to do Squares.getSquares(100);...I'm guessing this is because of my first problem. Please help me, I know static methods are important but I don't know how to make them.
package Testers;
import java.util.Scanner;
public class Squares
{
public static void main(String[] args)
{
Squares.getSquares(100);
public static double getSquares(double b)
{
double sqrtNum=Math.sqrt(b);
int i=0;
while(i<sqrtNum)
{
sqrtNum=Math.pow(i,2);
System.out.print(sqrtNum+" ");
i++;
}
}
}
}
You can't declare a method inside a method - format your code and it is clearer to see. Example:
package Testers;
import java.util.Scanner;
public class Squares {
public static void main(String[] args) {
Squares.getSquares(100);
}
public static double getSquares(double b) {
double sqrtNum = Math.sqrt(b);
int i = 0;
while(i < sqrtNum) {
sqrtNum = Math.pow(i, 2);
System.out.print(sqrtNum + " ");
i++;
}
}
}
Also, there is no returned value in getSquares() - it looks like you intended to make it void.
Finally, this while loop:
int i = 0;
while(i < sqrtNum) {
// code
i++;
}
can be simplified to this for loop:
for (int i = 0; i < sqrtNum; i++) {
// code
}
Your static method should not be in main() if you want it to be a method of the Squares class. it should be in Squares and not in main, like:
public class Squares
{
public static void main(..) {...}
public static double getSquares(...) {...}
}
You're declaring your method in another method, which doesn't work. Put it outside and it should be good.
package Testers;
import java.util.Scanner;
public class Squares
{
public static void main(String[] args)
{
Squares.getSquares(100);
}
public static double getSquares(double b)
{
double sqrtNum=Math.sqrt(b);
int i=0;
while(i<sqrtNum)
{
sqrtNum=Math.pow(i,2);
System.out.print(sqrtNum+" ");
i++;
}
}
}
In your getSquares method you need a return statement.
Related
I need to split this code in a way where I would be calling it from the main and doing the sorting in another method in a different file.
This is what I have in the main:
public class Test {
public static void main(String[] args) {
//array of 10 numbers
double numbers[] = new double[]{1.9, 2.5, 3.7, 2, 1.5, 6, 3 , 4 , 5, 2};
//assign first element of an array to largest and smallest
double smallest = numbers[0];
double largetst = numbers[0];
for(int i=1; i< numbers.length; i++)
{
if(numbers[i] < smallest)
smallest = numbers[i];
}
System.out.println("The minimum number is: " + smallest);
}
}
This is the other method:
import java.util.Arrays;
public class Chapter8 {
public static void chap8method(){}
public static double[][] sortRows(double[][] m) {
Chapter8.chap8method();
double[][] result = Chapter8.sortRows(m);
}
}
Create a class with the main method.
Main.java
public class Main {
public static void main(String[] args) {
//if your sort method is static in another class
Sort.sortRows(
//if your method is non static than create an object of that class
Sort obj = new Sort();
obj.sortRows
}
}
Your another class:
Sort.java
public class Sort{
public static double sortRows(double[][] m) {
//your sorting logic here
}
}
homework question is-----Write code that tests the variable x to determine whether it is greater than 0. If x is greater than 0, the code should test the variable y to determine whether it is less than 20. If y is less than 20, the code should assign 1 to the variable z. If y is not less than 20, the code should assign 0 to the variable z.
What i have at the moment is
import javax.swing.JOptionPane;
public class jjjd {
public static void main(String[] args) {
int x=0;
String input;
input=JOptionPane.showInputDialog("Enter a number for x");
x=Integer.parseInt(input);
if (x>0)
if (y<20)
{ (z==1);
}
else
{
z==0;
}
}
}
}
-------------------------------------------- EDIT
import javax.swing.JOptionPane;
public class jjjd {
public static void main(String[] args) {
int x=0;
String input;
input=JOptionPane.showInputDialog("Enter a number for x");
x=Integer.parseInt(input);
if (x>0) {
if (y<20)
{(z=1);}
}
else
{
z=0;
}
}
}
thats my new code!
the error im getting is the (z=0) under the else is "not a statement"
You have misused your braces ({}). You need to make sure that you close all braces after opening them or the java compiler will return an error.
Also make sure to use '=' for assignment and '==' for checking variables.
Hope this helps!
import javax.swing.JOptionPane;
public class jjjd {
public static void main(String[] args) {
int x=0;
int y=0;
int z=0;
String input;
input=JOptionPane.showInputDialog("Enter a number for x");
x=Integer.parseInt(input);
if (x>0) {
if (y<20) {
z=1;
}
} else {
z=0;
}
}
}
EDIT - OP you haven't created the variable 'z' or even 'y'. Make sure to use 'int z=0;' and 'int y=0;' at the top of your code with the 'int x=0;' I have updated my code to show this
To assign a value to a variable you use = not ==
Not to sure why the integers lowRange and highRange are not going between these classes.
package guessnumber;
public class GuessNumber
{
static public int computerGenedNumber;
static public int lowRange;
static public int highRange;
static public int playerGuess;
public static void main(String[] args)
{
Input.range(lowRange, highRange);
Rand.number(lowRange, highRange, computerGenedNumber);
Input.guess();
Give.result();
}
}
Next Class:
package guessnumber;
import javax.swing.JOptionPane;
class Input
{
public static void range(int lowRange, int highRange)
{
String rawUserInput;
rawUserInput = JOptionPane.showInputDialog("Please enter the range you wish to guess. (EX: 1-10)", "1-10");
for(int i = 0; i < rawUserInput.length(); i++)
{
if(rawUserInput.charAt(i) == '-')
{
lowRange = Integer.parseInt(rawUserInput.substring(0, i));
highRange = Integer.parseInt(rawUserInput.substring(i + 1, rawUserInput.length()));
}
}
}
static void guess()
{
}
}
And the last relevant one:
package guessnumber;
class Rand
{
static public void number(int lowRange, int highRange, int computerGenedNumber)
{
computerGenedNumber = (int)(Math.random() * (highRange - lowRange) + lowRange);
}
}
The rest of the classes are currently blank so I don't think I need to put them here too.
Here is a simplified piece of code which reproduce your problem, and make sure you understand why it is causing problem and the solution:
class Foo {
public static void square(int a, int result) {
result = a*a;
}
}
class Bar {
public static void main(String[] args) {
int a=2;
int result = 0;
Foo.square(a, result);
System.out.println("result " + result);
}
}
This should be fundamental understanding of Java. Checkout what is the meaning of "pass-by-value"
In brief, the parameter passed in the method is a copy of the argument. Therefore when you are changing the parameter in your method, you are just changing another piece of data, and your change is not reflected to caller.
One way to fix is to change the method and return your result, which looks like:
class Foo {
public static int square(int a) {
return a*a;
}
}
class Bar {
public static void main(String[] args) {
int a=2;
int result = 0;
result = Foo.square(a);
System.out.println("result " + result);
}
}
Another common solution is to pass in a "holder object" as the result. Although the object reference is passed by value, that copy of object reference is still pointing to the same object as caller. I won't go too deep into this as it is less common and you should be able to get the proper way doing so once you have better understanding on how value (including object reference) is passed around.
Parameters are passed "by value" in Java. What that means is that when you call
input.range(lowRange, highRange);
it gives the current values of those variables to input.range, but it doesn't give input.range a way to modify them. In the range method:
public static void range(int lowRange, int highRange)
the parameters lowRange and highRange (which have no connection with the variables in GuessNumber, even though the names are the same) are copies of what you pass in. When you assign lowRange = ... in the method, it changes the copy but has no effect at all on the lowRange and highRange in GuessNumber.
You need to write a range method that returns two values. This needs a little bit of work, but I'd write a Range class that has low and high members, and then change your method to
public static Range range()
That method would have to create a new Range object. I think it's OK for low and high to be public members of Range:
class Range {
public int low;
public int high;
public Range(int low, int high) {
this.low = low;
this.high = high;
}
}
Normally, public data in a class is a bad thing, but for a class whose only purpose is to let a method return multiple values, it's OK in my opinion.
I have a quick question out of curiosity...if I declare an integer in one method, for example: i = 1, is it possible for me to take that i and use its value in my main class (or another method)? The following code may be helpful in understanding what I'm asking...of course, the code might not be correct depending on what the answer is.
public class main {
public main() {
int n = 1;
System.out.print(n + i);
}
public number(){
i = 1;
}
}
No you cannot! Not unless you make it an instance variable!
Or actually send it to the function as an argument!
First, let's start simple. All methods that are not constructors require a return type. In other words,
public void number(){
i = 1;
}
would be more proper.
Second: the main method traditionally has a signature of public static void main(String[] args).
Now, on to your question at hand. Let's consider a few cases. I will be breaking a few common coding conventions to get my point across.
Case 1
public void number(){
i = 1;
}
As your code stands now, you will have a compile-time error because i is not ever declared. You could solve this by declaring this somewhere in the class. To access this variable, you will need an object of type Main, which would make your class look like this:
public class Main {
int i;
public static void main(String[] args) {
Main myMain = new Main();
myMain.number();
System.out.print(myMain.i);
}
public void number(){
i = 1;
}
}
Case 2
Let's say you don't want to make i a class variable. You just want it to be a value returned by the function. Your code would then look like this:
public class Main {
public static void main(String[] args) {
Main myMain = new Main();
System.out.print(myMain.number());
}
public int number(){ //the int here means we are returning an int
i = 1;
return i;
}
}
Case 3
Both of the previous cases will print out 1 as their output. But let's try something different.
public class Main {
int i = 0;
public static void main(String[] args) {
Main myMain = new Main();
myMain.number();
System.out.print(myMain.i);
}
public void number(){
int i = 1;
}
}
What do you think the output would be in this case? It's not 1! In this case, our output is 0. Why?
The statement int i = 1; in number(), it creates a new variable, also referred to as i, in the scope of number(). As soon as number() finishes, that variable is wiped out. The original i, declared right under public class Main has not changed. Thus, when we print out myMain.i, its value is 0.
Case 4
One more case, just for fun:
public class Main {
int i = 0;
public static void main(String[] args) {
Main myMain = new Main();
System.out.print(myMain.number());
System.out.print(myMain.i);
}
public int number(){
int i = 1;
return i;
}
}
What will the output of this be? It's 10. Why you ask? Because the i returned by number() is the i in the scope of number() and has a value of 1. myMain's i, however, remains unchanged as in Case 3.
You may use a class-scope field to store you variable in a class object or you can return it from one method or pass it as a parameter to the other. Mind that you will need to call your methods in the right order, which is not the best design possible.
public class main {
int n;
int i;
public main() {
n = 1;
System.out.print(n + i);
}
public number(){
i = 1;
}
}
Yes, create a classmember:
public class Main
{
private int i;
public main() {
int n = 1;
System.out.print(n + i);
number();
System.out.print(n + i);
}
public number(){
i = 1;
}
}
void method(){
int i = 0; //has only method scope and cannot be used outside it
}
void method1(){
i = 1; //cannot do this
}
This is because the scope of i is limited to the method it is declared in.
The question asks for the user to enter. lets forget about that and make it already initialized with some values so I can understand the first part.
Write a static method
public static int findMax(int[] r)
which receives as a parameter an array of numbers of type int and returns the maximum value.
Write a main method to test your program with array size 10 and elements entered by user.
Can't get what you exactly want to do? But if want that one class has static method and other class in main access that then you can try like this..
public class Demo {
public static void main(String[] args) {
int i = FindMaxClass.findMax(new int[10]); // pass int array
System.out.print(i);
}
}
class FindMaxClass{
public static int findMax(int[] r){
//logic to find max.
return 0; // return the max value found.
}
}
If static method should be in same class then others answers are good/correct.
public static int findMax(int[] values) {
int max = Integer.MIN_VALUE;
for (int val : values) {
if (val > max) {
max = val;
}
}
return max;
}
public static void main(String[] args) {
System.out.println("Max value: " + findMax(new int[]{1,2,3,1,2,3}));
}
I'm not going to write the code to solve your exact problem, but I'll tell you how to create and call a static method. See the example below:
public class Test {
// This is a static method
static void myMethod(int myArg) {
System.out.println("Inside Test.myMethod " + myArg);
}
// This is how to call it from main()
public static void main(String[] args) {
myMethod(3);
}
}
If you need more information to static methods take a look at:
http://openbook.galileocomputing.de/javainsel/javainsel_05_003.htm#mjd51d5220468ee4a1f2a07b6796bb393b
But you already know how to iterate over arrays?
Or maybe you are able to be more specific what you do not understand and what you have tried yet?