I was practicing on a bank account program , and I faced this small problem.
I made it as a method the make it easier to understand.
The main method
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
double b=0;
while(b!=-1){
b=in.nextInt();
ddd(b);
}
}
The addition method
public static void Addition(double b){
double g=0;
g+=b;
System.out.println( "GGGGGGGG"+ g );
}
The problem is that I get the same input I enter each time .
I know that the problem from the
double g=0;
Because each time I call the method addition g will be initialized to Zero because of this statement double g=0;, but I should to initial it, or I will get compilation error.
What should I do to fix this problem.
You can make the double g a member of the class by declaring it outside of methods. So here's an example class
class TestClass {
static double g = 0;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
double b = 0;
while (b != -1) {
b = scan.nextDouble() //you need to change nextInt() to nextDouble()
add(b);
}
System.out.println(g);
}
public static void add(double b) {
g += b; //g refers to the variable about the main method
}
}
This may not be exactly how your class works, but using the variable g outside of a method makes sure the class retains its value even when the method has ended. Hope this helps!
Initialize it just before the while statement.
Related
currently doing an assignemnt but i'm new to programming so was wondering how you add a value to a variable in a different class which already has an existing class
class OtherClass {
int a;
}
public class Main Class{
public static void main(String[] args) {
int b = 7;
OtherClass temp = new OtherClass();
OtherClass.a = 5
OtherClass.put(b) //this is where I'm not sure how to add b to a
}
Actual Code
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.print("Enter amount of money you have: ");
Scanner input = new Scanner(System.in);
Wallet bettersWallet = new Wallet();
bettersWallet.moneyAvailable = input.nextDouble(); //then had a function which played out a bet and added/took away winnings from the bet
int winnings = 5;
bettersWallet.moneyAvailable +=winnings; //Will setMoneyAvailable function work in this scenario aswell?
}
class Wallet {
double moneyAvailable;
double openingCash;
public void setMoneyAvailable()
{
moneyAvailable += ChuckALuckDiceGame.winnings;
}
int b = 7;
OtherClass temp = new OtherClass();
temp.a = 5;
temp.a += b; //Same as temp.a = temp.a + b;
System.out.println(temp.a);
What we are doing here,
We are creating an object of class OtherClass, the name of the object is temp.
Then we are assigning the value 5 in the attribute a of object temp
Then we are adding the value of primitive variable b into the variable temp.a.
The sum of the above equation is being assigned to the value of temp.a
Then I am printing the sum at the end through System.out.println(temp.a);
First of all I am new to JAVA, so I still dont understand everything and how it works. But I was working on something and was wondering if it could be done like this.
import java.util.Scanner;
public class Main {
public static int calc(){
Scanner sc = new Scanner(System.in);
String number1 = sc.nextLine();
int y = Integer.parseInt(number1);
System.out.println("+");
String number2 = sc.nextLine();
int z = Integer.parseInt(number2);
int Result = y + z;
sc.close();
return Result;
}
public static void printText(){
System.out.println(Result);
}
public static void main(String args[]) {
calc();
printText();
}
}
In the first method I was calculating the "Result" and in the second I just wanted it to make it so that it takes the "Result" and prints it.. but How I understand is that what happens in a method stays in the method. But I was wondering if it is possible to let method "printText" access the int from "calc".
I know I could place the code into the main and print it from there, but still it buggs me if it could be done like that :)
You can't access a local variable from a different method, no. (Once the method has completed, the local variable doesn't exist any more.) However, you can use the return value from your calc method, and pass that to the printText method:
public static void printText(int result) {
System.out.println(result);
}
public static void main(String args[]) {
int result = calc();
printText(result);
}
In order to do something like that1, you would need to give Result visibility. Since your methods are static it would also need to be static. Also, don't call close on a Scanner wrapping System.in (that's a global, and you can't re-open it). Something like,
private static int Result;
public static int calc(){
Scanner sc = new Scanner(System.in);
String number1 = sc.nextLine();
int y = Integer.parseInt(number1);
System.out.println("+");
String number2 = sc.nextLine();
int z = Integer.parseInt(number2);
Result = y + z;
return Result;
}
1As opposed to using the returned value, or passing it into your second method.
I'm new to Java and wanted some clarification, I understand that I'm declaring an int variable of x inside the method's parameters but why is it that 'result' can not be resolved to a variable.
public class Methods{
public static void main(String[] args) {
//f(x) = x * x
square(5);
System.out.println(result);
}
//This method
static int square(int x) {
int result = x * x;
}
You can, but note that local variable are only defined in their respected functions. So even though result is defined in square(), it's not defined in main(). So what you want to do is return a value for your square function and store that in a variable inside main() like so:
public static void main(String[] args) {
int myResult = square(5);
System.out.println(myResult);
}
//This method
static int square(int x) {
int result = x * x; // Note we could just say: return x * x;
return result;
}
Example Here
Since you are beginner, I will explain it bit thoroughly
Rule 1:Local variables are declared in methods, constructors, or blocks.
Rule 2:Local variables are created when the method, constructor or block is entered and the variable will be destroyed once it exits the method, constructor or block.
Rule 3:There is no default value for local variables so local variables should be declared and an initial value should be assigned before the first use.
public class Methods{
public static void main(String[] args) {
//f(x) = x * x
square(5);
System.out.println(result); //result! who are you?
//Main will not recognize him because of rule 3.
}
static int square(int x) {
int result = x * x; //you did it as said in rule 1
}//variable result is destroyed because of rule 2.
Please go thorough comments in code.
Well solution for your code is:
public class Methods{
public static void main(String[] args) {
//f(x) = x * x
int result=square(5);
System.out.println(result); //result! who are you?
//Main will not recognize him because of rule 3.
}
static int square(int x) {
int result1 = x * x; //you did it as said in rule 1
return result1;
}
This question already has answers here:
What is the reason behind "non-static method cannot be referenced from a static context"? [duplicate]
(13 answers)
Closed 9 years ago.
import java.util.Scanner;
import java.lang.Math;
public class Assignment1{
//instance variables
double a;
double b;
double c;
// method
public double hypot(double x, double y){
x = x*x;
y = y*y;
double z = x+y;
z = Math.sqrt(z);
return z;
}
// constructor
public Assignment1(double a , double b, double c){
this.a = a;
this.b = b;
this.c = c;
}
public static void main(String [] args){ // execution starts from here
Assignment1 obj = new Assignment1(a,b,c);
Scanner in = new Scanner(System.in);
System.out.println("Enter the values to compute the pythagoras theorem");
obj.a = in.nextDouble();
obj.b = in.nextDouble();
obj.c = hypot(a,b);
System.out.println("The hypot is"+ c);
}
}
What is the problem with this code... I m creating the objects... then it should worl fine !! Aint it???
In your main method (which is static) you are trying to access a b and c fields which are non-static without any reference to Assignment1 instance.
You need to understand that non-static members of class belongs to instance of class and they can be access only via such instance.
In non-static methods like
void someMethod(){
field = 42;
}
you can use field without reference to instance only because compiler will add this. to variable for you which will represent current instance. In static methods there is no this because static methods/fields belong to entire class, not to instances.
To solve your problem consider either first creating "unset" instance of Assignment1 class (lets say you set its values to 0) like
Assignment1 obj = new Assignment1(0, 0, 0);
then you can set its field to data from user like
obj.a = in.nextDouble();
obj.b = in.nextDouble();
and lastly you can calculate c value using
obj.c = obj.hypot(obj.a, obj.b);
BTW direct manipulation of object field is consider bad design. Instead you should create getters and setters (methods like getA() setA(int newA)) which will return or manipulate their values.
a, b and c are instance members. You main method is a class member.
You're trying to mix the two, which won't work.
Also, since you don't really need a custom constructor for your Assignment1 class, you can delete it.
Instead, try something like this:
public static void main(String [] args){ // execution starts from here
Assignment1 obj = new Assignment1();
Scanner in = new Scanner(System.in);
System.out.println("Enter the values to compute the pythagoras theorem");
obj.a = in.nextDouble();
obj.b = in.nextDouble();
obj.c = hypot(a,b);
System.out.println("The hypot is"+ c);
}
Of course its wrong,
you create a instance of Assignment1 with these Codes first:
Assignment1 obj = new Assignment1(a,b,c);
where are a and b and c??
maybe you should use null first:
Assignment1 obj = new Assignment1(null,null,null);
then use the Scanner.in to initialize a ,b and c
You should make a new class for Assignment. Having the main method here is a bit confusing. That said, the problem is that the first line of your main method:
Assignment1 obj = new Assignment1(a,b,c);
Accesses variables a, b, and c, which are non-static variables. This means they do not exist in the context of the static main function.
An alternative way to write this would be:
// Place this in a file called Assignment.java
import java.util.Scanner;
import java.lang.Math;
public class Assignment {
double a;
double b;
double c;
public double hypot(double x, double y) {
x = x*x;
y = y*y;
double z = x+y;
z = Math.sqrt(z);
return z;
}
public Assignment(double a , double b, double c) {
this.a = a;
this.b = b;
this.c = c;
}
} // end class Assignment
// Place this in a file called Main.java
public class Main {
public static void main(String [] args){ // execution starts from here
// Give some values to a, b, and c!
double a = 1;
double b = 1;
double c = 1;
Assignment obj = new Assignment(a,b,c);
Scanner in = new Scanner(System.in);
System.out.println("Enter the values to compute the pythagoras theorem");
obj.a = in.nextDouble();
obj.b = in.nextDouble();
obj.c = hypot(a,b);
System.out.println("The hypot is"+ c);
} // end method main
} // end class Main
As a general rule of thumb, try leave your main class empty of everything except the main method. It's even clearer if you call the class that contains the main method public class Main. Hope this helps!
package test;
import java.util.Scanner;
public class Char {
public static void main(String[] args) {
char c = 0;
Scanner scan = new Scanner(System.in);
printeaza(c, scan);
}
public static char printeaza(char c, Scanner sc) {
c = sc.next().charAt(0);
if (sc.hasNext()) {
System.out.println(printeaza(c, sc));
return c;
} else {
return c;
}
}
}
What i'm trying to do is type letters from the keyboard and then have them diplayed in reverse. I know it can be made very easy with a for loop and char arrays but i'm curious about making it recursively and using only one char variable. I almost made it but it seems it prints all but the first letter.
So if I type: "a s d f" instead of "f d s a" i get only "f d s". I think I know why, it's because the Println statement it's only inside the if statement but I kind of run of ideeas about how to make the function "catch" the first letter as well. I hope you can have a look, thanks!
Your first call to printeaza(c, scan) (made from public static void main) needs to be wrapped with a System.out.println(..) as well.
Like this:
package test;
import java.util.Scanner;
public class Char {
public static void main(String[] args) {
char c = 0;
Scanner scan = new Scanner(System.in);
System.out.println(printeaza(c, sc)); // <-- changed line
}
public static char printeaza(char c, Scanner sc) {
c = sc.next().charAt(0);
if (sc.hasNext()) {
System.out.println(printeaza(c, sc));
return c;
} else {
return c;
}
}
}
Incorporating Cruncher's advise, I'd write it like this:
package test;
import java.util.Scanner;
public class Char {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println(printeaza(sc));
}
public static char printeaza(Scanner sc) {
char c = sc.next().charAt(0);
if (sc.hasNext()) {
System.out.println(printeaza(sc));
}
return c;
}
}
The problem is that a call to printeaza doesn't print its own character, only that of it's recursive call.
In other words, printeaza(c, scan); in main needs to be changed to System.out.println(printeaza(c, scan);
Also, I would just like to point out that using recursive calls for user input like this is not a very good idea to be honest. :/