Can you please decribe exact what each section is doing and the purpose of the array? Im very new to java and am trying to understand this problem in terms of translating the algorithm in java format.
OK, it's not my code, but I'll go through it with you.
- import java.util.Scanner; //You have to import Scanner if you want to use it
As the comment (that text behind "//") says, the external class
Scanner which is in the package
java.util has to be imported, so that our program knows what it is. You could also have an own class called Scanner, that does something completely else, say in
org.mystuff.hardware (I just invented that one).
This opens and closes a class called "One".
- public static void main(String[] args) {
-
...
-
}
This is the main method. When you run your application, the main method you point to is called. Everything else must be started from here.
- Scanner scanner = new Scanner(System.in);
Here we are creating a new Object from the (imported) class Scanner. As you can see in it's
API Documentation, the Scanner class has a constructor which takes an InputStream.
System.in is the standard input.
- System.out.print("Enter the amount: ");
Prints the String "Enter the amount: " to the standard output (normally a console window).
- double amount = scanner.nextDouble(); //Java is case sensitive so nextDouble() != nextdouble
Here, our Scanner object reads a double value.
- //You set the coins and/or notes denominations here
-
// 1c 5c 10c 25c 50c $1 $5 $10
-
double[] coins = {0.01, 0.05, .1, 0.25, 0.5, 1, 5, 10}; //Put your denominations here
This is just an array with the given double values.
- double[] soln = new double[coins.length];
-
double current = 0.0;
Setting some variables, that we'll need later
- int i = coins.length - 1;
-
while(i >= 0) {
-
double val = coins[i];
-
while((val + current) <= amount) {
-
current = current + val;
-
soln[i] = soln[i] + coins[i];
-
}
-
i--;
-
}
This is a while loop with another nested while loop inside. The outer loop could have been a for loop too.
What happens is: The variable
val is created with the value of the i-th coin in the array. Then the while loop checks, if the current amount of money is still small enough to add whatever coin you're using at the moment and still be within the amount given by the user. If so, the current coin is added to the current amount and the variable [i]soln is risen by the value of that coin. This way, the array will show you how much money was paid with by which type of coin. Last but not least, the counter
i is decremented (=> i = i - 1).
- System.out.println(current); // Check this value for amounts containing .1
-
for(int j = 0;j < coins.length; j++) {
-
System.out.println(coins[j] + " : " + soln[j] / coins[j]);
-
}
Basically print out your results.
There, I hope that helps you understand the program and Java in general.
Greetings,
Nepomuk