Getting value to display for Java CurrentAccount class - java

package bankAccount;
public class CurrentAccount {
int account[];
int lastMove;
int startingBalance = 1000;
CurrentAccount() {
lastMove = 0;
account = new int[10];
}
public void deposit(int value) {
account[lastMove] = value;
lastMove++;
}
public void draw(int value) {
account[lastMove] = value;
lastMove++;
}
public int settlement() {
int result = 0;
for (int i=0; i<account.length; i++) {
result = result + account[i] + startingBalance;
System.out.println("Result = " + result);
}
return result;
}
public static void main(String args[]) {
CurrentAccount c = new CurrentAccount();
c.deposit(10);
}
}
At the moment, when I run the class, the expected System.out.println does not appear, and if I simply move public static void main(String[] args) to the top, this generates multiple red points. What is the best way for me to refactor my code so it works in the expected way?

you can have another class called Main in the file Main.java in which you can write your
public static void main(String args[])
and call
c.settlement();
in you main() to print.
Also one more advice,
in your constructor you have
account = new int[10];
which can hold only 10 ints.
in your deposit() and draw() you are not checking the account size. When the value of lastMove is more than 10 , the whole code blows up.
Hence I suggest you to use ArrayList

You never called the settlement method...
public static void main(String args[]) {
CurrentAccount c = new CurrentAccount();
c.deposit(10);
c.settlement();
}
I have the feeling that you come from some non-OOP language, like C or PHP. So some explanation:
The main method is static: that means it "exists" even when there is no object instance created, it can be thought of as if it belonged to the class instance.
on the contrary, for the other methods to "work", an instance is required.
This way the main method can be (and is actually) used as the entry point of the application
It is executed, and when it exists, (if no other threads are left running) the application terminates.
so nothing else is run that is outside of this method just by itself...
so if you don't call c.settlement(); - it won't happen...
Other notes:
Running main doesn't create an instance of the enclosing class
with new CurrentAccount(), you create an object instance, which has states it stores, and can be manipulated
be careful with arrays, they have to be taken care of, which tends to be inconvenient at times...

Why do you expect the printed output to appear? You don't actually call the settlement method, so that command is not executed.

You did not call settlement.. so nothing appears
if you add c.settlement... it is fine..

You have not called deposit() and settlement() in the main method untill you call, You cannot get expected output.

Related

Increment the number by 1 whenever i call the funtion in java

I am trying to print the number increment by 1 whenever i call the function, but i am not able to get the solution, below is my code
The blow is the function
public class Functions<var> {
int i=0;
public int value()
{
i++;
return i;
}
}
I am calling the above function here
import Java.Functions;
public class Increment {
public static void main(String[] args)
{
Functions EF = new Functions();
System.out.println(EF.value());
}
}
Whenever i run the program , i am getting only the output as 1 , but i want the output to be incremented by 1 . Could you please help. Thanks in Advance.
I believe your answer is with the scope of your variables and your understanding of them. You only call the method once in your given examples, so 1 is arguably the correct answer anyway. Below is a working example which will persist during runtime one variable and increment it every time a function is called. Your methods don't seem to follow the common Java patterns, so I'd recommend looking up some small example Hello, World snippets.
public class Example{
int persistedValue = 0; // Defined outside the scope of the method
public int increment(){
persistedValue++; // Increment the value by 1
return persistedValue; // Return the value of which you currently hold
// return persistedValue++;
}
}
This is due to the scope of "persistedValue". It exists within the class "Example" and so long as you hold that instance of "Example", it will hold a true value to your incremented value.
Test bases as follows:
public class TestBases {
static Example e; // Define the custom made class "Example"
public static void main(String[] args) {
e = new Example(); // Initialize "Example" with an instance of said class
System.out.println(e.increment()); // 1
System.out.println(e.increment()); // 2
System.out.println(e.increment()); // 3
}
}
If your desire is out of runtime persistence (the value persisting between application runs) then it would be best to investigate some method of file system saving (especially if this is for your Java practice!)
Your main problem is to increment the number value 1.
But you are calling your function only once. Even though you call the function many times you will get the value 1 only because it is not static variable so it will every time initialize to 0.
So please check below answer using static context.
Functions.java
public class Functions{
static int i=0;
public int value()
{
i++;
return i;
}
}
Increment.java
public class Increment{
public static void main(String []args){
Functions EF = new Functions();
System.out.println(EF.value());
System.out.println(EF.value());
System.out.println(EF.value());
}
}
Output:
1
2
3
If you design multi-threaded application, it will be better to use AtomicInteger.
The AtomicInteger class provides you an int variable which can be read and written atomically.
AtomicInteger atomicInteger = new AtomicInteger();
atomicInteger.incrementAndGet();

Java program without main method

For my class I need to write code that adds up the numbers 1-100 which will produce the number 5050. He told us not to use a main method and use a for loop. Is a main method 'public static void main (String[] args)' or something else. I am just still very confused on what exactly the main method is. Here is the code I have so far that works
public class SumAndAverageForLoop{
public static void main (String[] args) {
int sum = 0;
for (int i = 1; i <= 100; i++) sum += i;
System.out.println("The sum is " + sum);
}
}
From what I read more and after talking to some other kids in the class they said I need to make another class with a main method that calls this class but how do you call one class from another?
How to call one class from another that has a main method?
Yes the public static void main(String[] args) signature is the main method.
It sounds like you're writing library style code. So just create a method with a meaningful name for what your code does. Like AddOnetoOneHundred or similar.
You can create a method like this:
public static int CountUp() {
// code that was in your main method before
}
Double check your assignment, your teaching might have specified a class and method name and already has a program that will test your code.
A main method is fundamental to any given program as the Java compiler searches for the method as a starting point of execution. However, you are trying to make a utility class so:
class SumAndAverageForLoop {
// no main method
public static int sum() {
int sum = 0;
for (int i = 1; i <= 100; i++) sum += i;
System.out.println("The sum is " + sum);
}
}
class MainClassProgram {
// main in another class
public static void main() {
SumAndAverageForLoop.sum();
}
}
Try to create a method to do the calculation. The idea is create code that is unit testable.
public class SumAndAverageForLoop{
public static void main (String[] args) {
int returned = SumUp(1, 100);
System.Out.Println("sum is " + returned);
}
public int SumUp(int startInt, int endInt) {
int sum = 0;
if (endInt > startInt) {
for (int i = startInt; i <= endInt; i++) sum += i;
}
return sum;
}
}
Short Answer:
Yes, that (public static void main (String[] args)) is the main method.
Long Answer:
The main method is the entry point for an application. Without it, you may have code, but that code must somehow link to a main method or it cannot be ran. Counter-intuitively, the main method doesn't actually have to be a method. In C, you can create an integer array called main and execute it. It will translate the integers into hexadecimal and execute a corresponding Assembly command for each one, iteratively.
If you do what the professor says, you will not be able to test the program as an executable. He probably has a program made to run your code and test it for him, which is why he doesn't want a main method.
I'm not sure by what your teacher means by, "not using a main method". But you can declare a method outside of you main method and call it from there;
public class SumAndAverageForLoop{
public static void main (String[] args) {
makeSum();
}
public static void makeSum() {
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum += i;
}
System.out.println(sum);
}
}
Also, since one of your comments asked "How to create a method?".
I suggest you read up on some books for beginners. I'd recommend the book Head First Java.

How to pass information through a method and returning a value

I'm new to Java, and need help. I have been asked to write a program that rolls dice and determines the chance of the player to get two "1s" on the top face of the dice. I have different functions such as role(), getTopFace() etc. I want to be get what the number on the dice is using these functions, but don't know how to call them in my main function. Here's my code:
import javax.swing.JOptionPane;
import java.util.Random;
public class SnakeEyes {
private final int sides;
private int topFace;
public static void main(String[]args)
{
String numberSides;
int n;
numberSides=JOptionPane.showInputDialog("Please enter the number of sides on the dice:");
n = Integer.parseInt ( numberSides);
int[]die=new int[n];
for (int index=0; index<n;index++)
{
die[index]=index+1;
}
//Here is where I want to get information from my functions and calculate the ods of getting two 1's.
}
public void Die(int n)
{
if(n>0)
{
int sides=n;
topFace=(int)(Math.random()*sides)+1;
}
else{
JOptionPane.showMessageDialog(null, " Die : precondition voliated");
}
}
public int getTopFace(int topFace)
{
return topFace;
}
public int role(int[] die)
{
topFace=(int)(Math.random()*sides)+1;
return topFace;
}
}
Make an object of your class SnakeEyes in your main method, and call the required functions using that object.
Example:
SnakeEyes diceObj = new SnakeEyes();
int topFace = diceObj.role(n,....);
If you want to call this functions from main this functions must be "static", because main its a static function and static function can only call other static functions.
But... this is a very ugly design for a java program, before jumping to write java code you need to understand at least a little about object orientation. For example, why you can't call a non-static function from a static function?, the answer of this question requires knowledge about object orientation and its a knowledge you need if you want to write serious java code.

How can I tell if a method is being called?

How can I tell if a method is being called so that I can add a counter to measure the total calls of this method?
Edit for clarification.
assuming that I have
class anything{
public String toString() {
++counter;
return "the time this method is being called is number " +counter;
}
}//end class
and I am creating an instance of anything in a main method 3 times,
and the output I want if I call its toString() the whole 3 times is this:
the time this method is being called is number 1
the time this method is being called is number 2
the time this method is being called is number 3
I want the counter being added succesfully inside the class and inside the ToString() method and not in main.
Thanks in advance.
You can use a private instance variable counter, that you can increment on every call to your method: -
public class Demo {
private int counter = 0;
public void counter() {
++counter;
}
}
Update : -
According to your edit, you would need a static variable, which is shared among instances. So, once you change that varaible, it would be changed for all instances. It is basically bound to class rather than any instance.
So, your code should look like this: -
class Anything { // Your class name should start with uppercase letters.
private static int counter = 0;
public String toString() {
++counter;
return "the time this method is being called is number " +counter;
}
}
The best way to do this is by using a private integer field
private int X_Counter = 0;
public void X(){
X_Counter++;
//Some Stuff
}
You have 2 options...
Count the messages for one instance:
public class MyClass {
private int counter = 0;
public void counter() {
counter++;
// Do your stuff
}
public String getCounts(){
return "The time the method is being called is number " +counter;
}
}
Or count the global calls for all created instances:
public class MyClass {
private static int counter = 0;
public void counter() {
counter++;
// Do your stuff
}
public static String getCounts(){
return "the time the method is being called is number " +counter;
}
}
It depends on what your purpose is. If inside you application, you want to use it, then have a counter inside every method to give details.
But if its an external library, then profilers like VisualVM or JConsole will give you number of invocations of each method.

Luse Constructor With Variable Inside

I'm learning about constructors.
When I try to compile the following code, I get the error "variable input and shape are not initialized."
Could anyone tell me why and how to solve it?
public class Try {
public static void main(String[] args)
{
String input;//user key in the height and width
int shape;//triangle or square
Count gen = new Count(input , shape);//is this the right way to code?
gen.solve();
}
}
public class Count {
public Count(String inp, int shp) {
String input_value = inp;
shape_type = shp;
}
public void solve () {
if shape_type==3{
//count the triangle
}
else if shape_type==4{
//count the square
}
}
}
You haven't given shape or input values yet before you try using them. Either you can give them dummy values for now, like
String input = "test";
int shape = 3;
Or get the string and integer from the user; in that case, you might want to take a look at how to use a Scanner.
By leaving input and shape without values, at:
String input;
int shape;
they are uninitialized, so Java doesn't know what their values really are.
I assume this is some kind of homework. I took the liberty of reformating and fixing your code a little.
You have to initialize any variable you are going to use. The only exception is when you are using class members (those are initialized automatically to some default value). See below that the members of the Count class aren't explicitly initialized.
This is some working code. Also note that i change the solve method a little (the if blocks should have had () around the expression. But what you are trying to do is usually better done with a switch block as shown below. Also I declared two members inside the Count class to remember the values provided at construction time in order to be able to use them when calling the solve() method.
public class Try {
public static void main(String[] args) {
String input = null; //user key in the height and width
int shape = 0; //triangle or square
Count gen = new Count(input, shape);//is this the right way to code?
gen.solve();
}
}
class Count {
String input_value;
int shape_type;
public Count(String inp, int shp) {
this.input_value = inp;
this.shape_type = shp;
}
public void solve() {
switch (this.shape_type) {
case 3:
// count the triangle
break;
case 4:
// count the square
break;
}
}
}
Proper formatting of the code usually helps :).

Categories