Java variables not available in different methods within class - newbie - java

I'm new to Java and I looked everywhere but I'm not getting a simple concept.
I declare two variables as int. I want the two variables to be global to all methods.
In my first method, I want to get the value of the first variable from user input.
Then I want that new value available, recognized, and called by the second method. However, every time the first method ends, the value of the variable is set back to 0, and the second method does not find the value the user gave to it in the first method input. What am I doing wrong? Do I need to declare my variables differently? Do I need to declare my methods differently? Thanks for your help!
import acm.program.*;
public class FindRange extends ConsoleProgram {
int num1;
int num2;
public void run() {
println("This program finds the largest and smallest numbers.");
getNum1();
getNum2();
// getNumUntilZero();
}
public void getNum1() {
int num1 = readInt("?:");
if (num1 == 0) { //do not accept 0 for first number
println("Please try again without 0.");
getNum1();
}
}
public void getNum2() {
int num2 = readInt("?:");
if (num2 == 0) { //if 2nd number is 0, print 1st num as high and low nums
println("Biggest number:" + num1);
println("Smallest number:" + num1);
}
}
}

when you do int num1 = readInt("?:"); inside method getNum1(), its a local variable stored in stack . it does not refer to global variable (declared as instance variable )which you want to refer
So do it like this:
public void getNum1() {
num1 = readInt("?:");
if (num1 == 0) { // do not accept 0 for first number
println("Please try again without 0.");
getNum1();
}
}
public void getNum2() {
num2 = readInt("?:");
if (num2 == 0) { // if 2nd number is 0, print 1st num as high and low nums
println("Biggest number:" + num1);
println("Smallest number:" + num1);
}
}

actually you have created new variable inside method. so not actually assigning values to the class variables, but to method variable:
so change
int num2 = readInt("?:");
to
num2 = readInt("?:");
and
int num1 = readInt("?:");
to
num1 = readInt("?:");

You redeclare a local variable called the same thing. This should give an IDE warning along of the lines of "local variable hides a field". So in the scope of the method there is another numX.
You need to reference the instance variable and not declare a new variable:
public void getNumX() {
numX = readInt("?:");
//...
}
You see I have removed the int declaration so that this now assigns the value to numX rather than to a local variable.

Related

how can I take one methods result as another methods' parameter

I need to take this "over" statement under the overallmethod as finalmethods' parameter, how can I do this. I want to learn the final letter but to do that I want to access over statement.
public static void overallmethod(int quiz1,int quiz2,int quiz3,int midterm,int grade){
double quizzes = ( ((quiz1*10) + (quiz2*10) + (quiz3*10)) *25) /300;
double finalg = ( grade * 40) / 100;
double mid = (midterm * 35) / 100;
double over = quizzes + finalg + mid;
System.out.println("Your overall score is: " + over);
}
public static void finalmethod(double over){
if(over <= 100 && over >= 90){
System.out.println("Your final letter is: A");
}
else if(over >= 80) {
System.out.println("Your final letter is: B");
}
else if (over >= 70) {
System.out.println("Your final letter is: C");
}
else if (over >= 60) {
System.out.println("Your final letter is: D");
}
else{
System.out.println("Your final letter is: F");
}
}
You're going to need to return the variable over and change your return type to double.
public static double overallmethod(int quiz1,int quiz2,int quiz3,int midterm,int grade)
{
//Your code
return over;
}
Then simply pass the value returned from the overallmethod to finalmethod.
over is not a statement, it is a local variable now. Just make it class attribute:
public static double over
Make your overall function return the value of over. Then just call the overall function inside the parameter list of finalmethod
The best solution would be to declare over as a private int outside both the methods, i.e. it should have visibility to all the methods in that class (class variable).
Now compute the overall score in the overallMethod and store it to the over variable.
Next, make a public method getOver() which returns the value of over, and call finalMethod in this way : ClassName.finalMethod(objectOfClass.getOver())
By changing the return type of your method to double, and then passing the value in that method to the final method.

Can anyone help me understand these two programs?

Program 1:
public class ValAndRefTypes {
public static void main(String[] args) {
int x=5;
addOneTo(x);
System.out.println(x);
}
static int addOneTo(int num){
num=num++;
return(num);//Outputs 5
}
Program 2:
public class ValAndRefType1 {
public static void main(String[] args) {
int a=2,b=3;
System.out.println("The sum is: " + Add(a,b));
}
static int Add(int num,int num1){
num++;
num1++;
return(num+num1); //Outputs 7
}
Why does the first program not output the incremented value of the variable 'x', but the second program outputs the incremented value of variables 'a' and 'b'?
I also would like to ask whether this has any relation with Value types and Reference types.
TIA for the answer!
Two reasons:
First:
In the first program, the addOneTo function is adding the value and returning the new value (well, attempting to, but we'll get to that below), but that returned value is ignored:
addOneTo(x);
You don't assign the new value to anything. Assign it back to the variable:
x = addOneTo(x);
Whereas in the second program this works because you are using the returned value. You're including it as part of the output:
System.out.println("The sum is: " + Add(a,b));
Second:
This line is very misleading, and is confusing the logic being implemented:
num=num++;
num++ increments num, but evaluates to the previous value of num. So the assignment results in assigning back that previous value. This could work instead:
num = ++num;
Though that's still clouding the logic for no reason. Just increment directly:
num++;
or if you prefer being more explicit:
num = num + 1;
In the second example, that's how you increment:
num++;
num1++;
In your first program, you are printing "x" which has value 5. Only calling a function does not change the value of "x". If you want to print incremented value the program looks like this:
public class ValAndRefTypes {
public static void main(String[] args) {
int x=5;
System.out.println(addOneTo(x));
}
static int addOneTo(int num){
num=num++;
return(num);//It returns 6 not 5
}
Let me make a small change to program 1. You can't mutate a primitive.
public static void main(String[] args) {
int x=5;
int y = addOneTo(x);
System.out.println(y);
}
static int addOneTo(int num){
num=num++;
return(num);
}

How do I use a function involving integers?

We have an assignment in class to create a greatest common divider (gcd) program using functions. I missed out on the lesson where we learned how to properly use them. I finished the part that actually does the division but I don't know how to separate it into a function and have it work. I'd like to have the input in the main class and the process in function.
This is what I have, it does not work when I run it
package gcd.function.java.program;
import java.util.Scanner;
/**
*
* #author sarah_000
*/
public class GCDFunctionJavaProgram {
public static void main(String[] args) {
int num1;
int num2;
int div;
Scanner input = new Scanner(System.in);
System.out.print("Enter your first number: ");
num1 = input.nextInt();
System.out.print("Enter your second number: ");
num2 = input.nextInt();
System.out.printf("The GCD is %d ", div);
}
public static void GCDFunction() {
if(num1 > num2)
div = num2;
else div = num1;
while((num1 % div!= 0)||(num2 % div != 0))
{
div --;
}//end of while loop
}
}
Any tips or help you can give to me will be greatly appreciated, I'm very new
You declare two parameters and modify the return type in your GCDFunction like this:
public static int GCDFunction(int num1, int num2)
You are currently trying to access the variables in the main method but are out of scope.
Also, you never actually call your GCDFunction
Think of it like passing functions in math. The GCDFunction() has to receive the numbers into the function so we do
public static void GCDFunction(int num1, int num2)
That also lets Java know the type it is, type int. And your java variables are scoped inside of the functions so you have to print the output in the function that created the variable in your scenario.
So once you have that function set up to receive the variables and output after processing, you call the function in the main with a
GCDFunction(num1, num2);
Where num1 and num2 are the variables that have your integers stored in.
The end result after a little rearranging looks like this.
import java.util.Scanner;
public class GCDFunctionJavaProgram {
public static void main(String[] args) {
int num1;
int num2;
Scanner input = new Scanner(System.in);
System.out.print("Enter your first number: ");
num1 = input.nextInt();
System.out.print("Enter your second number: ");
num2 = input.nextInt();
GCDFunction(num1, num2);
}
public static void GCDFunction(int num1, int num2) {
int div;
if(num1 > num2){
div = num2;
}
else{ div = num1;}
while((num1 % div!= 0)||(num2 % div != 0))
{
div --;
}//end of while loop
System.out.printf("The GCD is %d ", div);
}
Trying to give you a example of how the code should be to take in variable number of parameters.
public int gcd(Integer... numbers) {
int gcd = 1;
int miNNumber=Collections.min(Arrays.asList(numbers));
boolean isDivisible;
for(int i=2; i<=miNNumber;i++) {
isDivisible=true;
for(Integer eachNumber : numbers) {
if(eachNumber%i!=0) {
isDivisible=false;
break;
}
}
if(isDivisible) {
gcd=i;
}
}
return gcd;
}
You can call it
gcd(10, 200, 400);
or
gcd(10, 200, 400, 4000, 40);

I am getting a Cannot find symbol error that I can't resolve

I am getting this error that to me looks like I am not calling the method correctly. I have reviewed the past answers here but none have specifically addressed my problem as far as I can see. This is for a class project. I realize my math in the method is most likely not correct yet but I need to get the rest working then deal with an incorrect out put. Thanks a lot!
Here is my code:
import java.util.*;
public class PrintOutNumbersInReverse {
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
// Gather Number
System.out.print("Enter a number between 2 and 10 digits long ");
int num = console.nextInt();
System.out.println("your number is: " + num);
// call method
System.out.println("Your number in reverse is: " + reverse);
}
public static int reverse(int num, int rNum) {
rNum = 0;
while (num != 0) {
rNum = rNum + num % 10;
num = num / 10;
}
}
}
And My error Message:
PrintOutNumbersInReverse.java:28: error: cannot find symbol
System.out.println ("Your number in reverse is: " +reverse);
^ symbol: variable reverse location: class PrintOutNumbersInReverse 1 error
Change method implementation to:
public static int reverse (int num)
{
int rNum = 0;
...
return rNum;
}
and place, that is calling this method to:
System.out.println ("Your number in reverse is: " +reverse(num));
Then should be fine
When copy pasting this into eclipse, i noticed 2 things:
1.) your reverse() method doesn't return an int, but it should because the signature of the method says so: public static int reverse(int num, int rNum). Maybe return rNum, or whatever the logic behind it might be?
2.) second, you have not declared any reverse variable in the main method. Maybe you wanted a parameterized call of reverse()?
Also it looks like, you want in the reverse() method rNum to be an output parameter. In java you can't pass primitives by reference, so whatever you do with rNum inside the method, the changes will only be present in the scope of the method. So you might want to calculate something and actually return the results of your calculations.
You need to use reverse as a method, and not a variable. Also, you are passing in a variable that is not used: rNum. You see in reverse(int num, int rNum); right after you start, it sets your rNum to 0. So why pass a number in that will get set to zero?
I did this from my phone, but this should be working code:
import java.util.*;
public class PrintOutNumbersInReverse {
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
// Gather Number
System.out.print("Enter a number between 2 and 10 digits long ");
int num = console.nextInt();
System.out.println("your number is: " + num);
// call method
System.out.println("Your number in reverse is: " + reverse(num)); //<-- notice how this is a method cause it has "()"
}
public static int reverse(int num) { //<-- this has "int num" in the "()". This is a parameter.
int rNum = 0;
while (num != 0) {
rNum = rNum + num % 10;
num = num / 10;
}
}
}

input 2 variables(user input by "Buffered Reader") to be pass to a class?

i am a beginner at java language and i use "text pad". i have a problem with my simple program. my task is to input 2 values and show the "sum","difference","product" and "quotient" altogether. (simple right?) in which , here below is the class that supposed to be doing the job of arithmetic. in which is "correct" as i compiled.
public class mathclass
{
int x;
int y;
int total;
void add ()
{
total = x+y;
}
void sub ()
{
total = x-y;
}
void multi ()
{
total = x*y;
}
void div ()
{
total = x/y;
}
}
And here is the main program that supposed to be the input and output of the program.
my problem here is that i can't pass the 2 variables (num1 and num2) to "mathclass"
i did research on how to pass 2 variables to a another class. but there is nothing same to mine that i have. i did use some like the putting "private or public" on the variables.
my teacher said to use the BufferedReader for input. and i am having a hard time how to get this program right. (sorry if i had wrong english(if i am wrong. ))
import java.io.*;
public class mathmain
{
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public static void main(String[]args)throws IOException
{
mathclass math1 = new mathclass();
System.out.print("Enter 1st Number :");
num1 = Integer.parseInt(br.readLine());
System.out.println(" ");
System.out.print("Enter 2nd Number :");
num2 = Integer.parseInt(br.readLine());
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
math1.add();
{
System.out.print("Sum : ");
System.out.println(math1.total);
}
System.out.println(" ");
math1.sub();
{
System.out.print("Difference : ");
System.out.println(math1.total);
}
System.out.println(" ");
math1.multi();
{
System.out.print("Product : ");
System.out.println(math1.total);
}
System.out.println(" ");
math1.div();
{
System.out.print("Quotient : ");
System.out.println(math1.total);
}
}
}
It's really not clear what you're trying to do here. (Why doesn't add take two arguments for instance?)
Perhaps your after something like this:
// Set up arguments
math1.x = num1;
math1.y = num2;
// Perform the add.
math1.add();
// { <-- brace completely useless.
// Print the result
System.out.print("Sum : ");
System.out.println(math1.total);
// } <-- brace completely useless.
However, I would encourage you to use return values and use parameters:
class MathClass {
public int add(int a, int b) {
return a + b;
}
...
}
and then use the class like
int sum = math1.add(num1, num2);
System.out.println("Sum: " + sum);
You should take some look on how to code in Java because you're going the wrong way.
Either you create a constructor to initialize x & y either you put them in the method add(x,y) which would lead you to make the method static and remove references of x & y from the class. Same goes for the total that should be the return of your function.
Try this,
Use Two Parameter Constructor for mathmain class...
public mathmain(int x, int y){
this.x = x;
this.y = y;
}
Please use Uppercase for the Fist alphabet of the class name (eg: MathMain),
and yes, use Camel Case for writing Class, Variables, Method,etc Names in java.
Since you're beginning, I will not point out the design flaws. Your problem comes from how you are using your read values. You read values into num1 and num2, but you never set them in your mathclass object:
math1.x = num1;
math1.y = num2;
As per what aioobe said, you should look at java design rules to help you create robust, useful classes. I would also encourage you to encapsulate your classes and use parameters and return values whenever possible.
Good luck in learning java, and I hope this helped!

Categories

Resources