I am learning Java and am making code that converts pennies in to change. It is completed however, I am unsure what to enter for the while loop. I would have used while(!change.equals("END")) but this can't be done because change is an integer, so what can I do?
class Main {
public static void main(String args[]) {
System.out.print("#Please enter the amount of change : ");
int change = BIO.getInt();
if (change <= 500 && change >= 1) {
System.out.print("Amount" + "\t" + "Coins" + "\n");
}
while (change =) {
int twopounds, pounds, fifty, twenty, ten, five, two, one;
twopounds = change / 200;
int left = change % 200;
pounds = left / 100;
left = left % 100;
fifty = left / 50;
left = left % 50;
twenty = left / 20;
left = left % 20;
ten = left / 10;
left = left % 10;
five = left / 5;
left = left % 5;
two = left / 2;
left = left % 2;
one = left / 1;
int nbCoins = twopounds + pounds + fifty + twenty + ten + five + two + one;
if (change > 500 || change < 1) {
System.out.print("Invalid amount " + change + "p" + "\n");
}
if (change <= 500 && change >= 1) {
if (nbCoins == 1) {
System.out.print(change + "p " + "\t" + nbCoins + " coin ");
} else {
System.out.print(change + "p " + "\t" + nbCoins + " coins ");
}
if (twopounds > 0) {
System.out.print(twopounds > 1 ? twopounds + "*200p " : "200p ");
}
if (pounds > 0) {
System.out.print(pounds > 1 ? pounds + "*100p " : "100p ");
}
if (fifty > 0) {
System.out.print(fifty > 1 ? fifty + "*50p " : "50p ");
}
if (twenty > 0) {
System.out.print(twenty > 1 ? twenty + "*20p " : "20p ");
}
if (ten > 0) {
System.out.print(ten > 1 ? ten + "*10p " : "10p ");
}
if (five > 0) {
System.out.print(five > 1 ? five + "*5p " : "5p ");
}
if (two > 0) {
System.out.print(two > 1 ? two + "*2p " : "2p ");
}
if (one > 0) {
System.out.print(one > 1 ? one + "*1p " : "1p ");
}
System.out.print("\n");
}
System.out.print("#Please enter the amount of change : ");
change = BIO.getInt();
}
}
}
Thanks :)
It depends on what BIO is. Generally, there are options like .hasNextToken() if it is Enumerable. But, without knowing what that variable is declared as, I can't tell you what your trigger would be.
maybe this will work:
boolean flag = true;
while(flag){
//do things
if(condition_when_you_want_your_loop_to_stop){
flag = false;
}
}
Related
I'm attempting to fill a 2D array with the numbers 1 to 1000 and then show all the factors of those numbers. I then need to find all the prime numbers in the same array and output them. Here's what I have so far, keep in mind that I was hoping to do every step in its own method then return them but have not got that far yet
int i = 0;
//int x = 0;
String primeNumber = "";
int[] [] factorArray = new int [1000] [];
for (int x = 0 ; x < 1000 ; x++)
{
int remainder;
int y;
remainder = x % 2;
y = x / 2;
if (remainder != 0)
System.out.println (x + ": " + "1, " + x);
else if (remainder == 0)
System.out.println (x + ": " + (y) + " , " + (y / 2) + " , " + " 1, " + x);
}
for (i = 1 ; i <= 1000 ; i++)
{
int ctr = 0;
for (int x = i ; x >= 1 ; x--)
{
if (i % x == 0){
ctr = ctr + 1;
}
}
if (ctr == 2)
{
primeNumber = primeNumber + i + " ";
}
}
System.out.print ("Prime numbers from 1 - 1000 are : \n" + primeNumber);
I need to modify the code so that,
its structure is better
it is more readable
it uses methods and parameters
only one statement needs to be changed if a different number of integers is to be input
My new code is at the bottom but it's not working yet, can't quite figure out what else I need to do to it. If anyone could help that would be fab.
Original Code
import java.util.Scanner;
public class MakeMeBetter
{
public static void main(String[] args)
{
int[] a = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
Scanner b = new Scanner(System.in);
System.out.println("Please input 10 numbers in the range 1-19 :> ");
int c = b.nextInt();
while (c < 1 || c > 19)
{
System.out.println("Not in the range 1-19, please try again :> ");
}
a[0] = c;
int d = b.nextInt();
while (d < 1 || d > 19)
{
System.out.println("Not in the range 1-19, please try again :> ");
}
a[1] = d;
int e = b.nextInt();
while (e < 1 || e > 19)
{
System.out.println("Not in the range 1-19, please try again :> ");
}
a[2] = e;
int f = b.nextInt();
while (f < 1 || f > 19)
{
System.out.println("Not in the range 1-19, please try again :> ");
}
a[3] = f;
int g = b.nextInt();
while (g < 1 || g > 19)
{
System.out.println("Not in the range 1-19, please try again :> ");
}
a[4] = g;
int h = b.nextInt();
while (h < 1 || h > 19)
{
System.out.println("Not in the range 1-19, please try again :> ");
}
a[5] = h;
int i = b.nextInt();
while (i < 1 || i > 19)
{
System.out.println("Not in the range 1-19, please try again :> ");
}
a[6] = i;
int j = b.nextInt();
while (j < 1 || j > 19)
{
System.out.println("Not in the range 1-19, please try again :> ");
}
a[7] = j;
int k = b.nextInt();
while (k < 1 || k > 19)
{
System.out.println("Not in the range 1-19, please try again :> ");
}
a[8] = k;
int l = b.nextInt();
while (l < 1 || l > 19)
{
System.out.println("Not in the range 1-19, please try again :> ");
}
a[9] = l;
System.out.println("\nArray contents");
System.out.print((a[0] < 10 ? " " : "") + a[0] + " ");
System.out.print((a[1] < 10 ? " " : "") + a[1] + " ");
System.out.print((a[2] < 10 ? " " : "") + a[2] + " ");
System.out.print((a[3] < 10 ? " " : "") + a[3] + " ");
System.out.print((a[4] < 10 ? " " : "") + a[4] + " ");
System.out.print((a[5] < 10 ? " " : "") + a[5] + " ");
System.out.print((a[6] < 10 ? " " : "") + a[6] + " ");
System.out.print((a[7] < 10 ? " " : "") + a[7] + " ");
System.out.print((a[8] < 10 ? " " : "") + a[8] + " ");
System.out.print((a[9] < 10 ? " " : "") + a[9] + " ");
System.out.println();
boolean noSwap = false;
int startAt = 0;
int stopAt = 9;
while (startAt < stopAt && noSwap == false)
{
noSwap = true;
for (int m=startAt; m<stopAt; m++)
{
if (a[m] > a[m+1])
{
int t = a[m];
a[m] = a[m+1];
a[m+1] = t;
noSwap = false;
}
}
stopAt = stopAt - 1;
}
System.out.println("\nArray contents");
System.out.print((a[0] < 10 ? " " : "") + a[0] + " ");
System.out.print((a[1] < 10 ? " " : "") + a[1] + " ");
System.out.print((a[2] < 10 ? " " : "") + a[2] + " ");
System.out.print((a[3] < 10 ? " " : "") + a[3] + " ");
System.out.print((a[4] < 10 ? " " : "") + a[4] + " ");
System.out.print((a[5] < 10 ? " " : "") + a[5] + " ");
System.out.print((a[6] < 10 ? " " : "") + a[6] + " ");
System.out.print((a[7] < 10 ? " " : "") + a[7] + " ");
System.out.print((a[8] < 10 ? " " : "") + a[8] + " ");
System.out.print((a[9] < 10 ? " " : "") + a[9] + " ");
System.out.println();
double n = (a[0] + a[1] + a[2] + a[3] +
a[4] + a[5] + a[6] + a[7] +
a[8] + a[9]) / 10;
System.out.println("The minimum number is: " + a[0]);
System.out.println("The maximum number is: " + a[9]);
System.out.println("The average value is: " + n);
System.out.println("The median is: " + a[4]);
}
}
New Code
import java.util.Scanner;
import java.math.*;
public class MakeMeBetterImproved {
public static void main(String[] args) {
Scanner kybd = new Scanner(System.in);
int[] numbers = new int[10];
int array = 0;
System.out.println("Enter 10 integers: ");
for (int i = 0; i < numbers.length; i++) {
numbers[i] = kybd.nextInt();
int MyIntArray = array + i;
}
System.out.println("The minimum number is: " + math.min);
System.out.println("The maximum number is: " + math.max);
System.out.println("The average value is: " + math.average);
System.out.println("The median is: " + math.median);
}
}
Consider using a more dynamic structure than a primitive array.
I like ArrayLists: http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
Reorganize your long code into while or for loops.
An example:
ArrayList<Integer> a = new ArrayList<Integer>();
Scanner b = new Scanner(System.in);
Integer c = null;
while (a.size() != 10) {
System.out.println("Please input a number in the range 1-19 :> ");
c = b.nextInt();
while (c < 1 || c > 19)
{
System.out.println("Not in the range 1-19, please try again :> ");
c = b.nextInt();
}
a.add(c);
}
System.out.println("\nArray contents");
for (int i=0; i<10; i++) {
System.out.print((a.get(i) < 10 ? " " : "") + a.get(i) + " ");
}
(And so on...)
Could you try this? I made a few changes.
package p2;
import java.util.Arrays;
import java.util.Scanner;
public class TicTacToe {
public static void main(String[] args) {
Scanner kybd = new Scanner(System.in);
int[] numbers = new int[10];
int sum = 0;
System.out.println("Enter 10 integers: ");
for (int i = 0; i < numbers.length; i++) {
numbers[i] = kybd.nextInt();
sum += numbers[i];
}
Arrays.sort(numbers);
System.out.println("The minimum number is: " + numbers[0]);
System.out.println("The maximum number is: " + numbers[9]);
System.out.println("The average value is: " + sum / numbers.length);
System.out.println("The median is: " + median(numbers));
}
public static double median(int[] m) {
int middle = m.length / 2;
if (m.length % 2 == 1) {
return m[middle];
} else {
return (m[middle - 1] + m[middle]) / 2.0;
}
}
}
I am learning Java and am making code that converts the number of pennies in to change when entered.
One thing I need to change is my output so that if there is only one coin it prints solely as 20p rather than 1*20p.
I would also appreciate if anyone notes any other improvements that could be made.
Thanks :)
class Main {
public static void main( String args[] ) {
System.out.print("#Please enter the amount of change : ");
int change = BIO.getInt();
while(change > 0)
{
int twopounds, pounds, fifty, twenty, ten, five, two, one;
twopounds = change / 200;
int left = change % 200;
pounds = left / 100;
left = left % 100;
fifty = left / 50;
left = left % 50;
twenty = left / 20;
left = left % 20;
ten = left / 10;
left = left % 10;
five = left / 5;
left = left % 5;
two = left / 2;
one = left / 1;
int nbCoins = twopounds + pounds + fifty + twenty + ten + five + two + one;
if (change == 1)
{
System.out.print("1 coin" + "\n");
}
if (change > 500)
{
System.out.print("Invalid amount " + change + "p" + "\n");
}
if (change <= 500 && change > 1)
System.out.print(change + "p " + nbCoins +" coins ");
{
if ( twopounds > 0 )
{
System.out.print( twopounds > 0 ? twopounds + "*200p " : "" );
}
if ( pounds > 0 )
{
System.out.print( pounds > 0 ? pounds + "*100p " : "" );
}
if ( fifty > 0 )
{
System.out.print( fifty > 0 ? fifty + "*50p " : "" );
}
if ( twenty > 0 )
{
System.out.print( twenty > 0 ? twenty + "*20p " : "" );
}
if ( ten > 0 )
{
System.out.print( ten > 0 ? ten + "*10p " : "" );
}
if ( five > 0 )
{
System.out.print( five > 0 ? five + "*5p " : "" );
}
if ( two > 0 )
{
System.out.print( two > 0 ? two + "*2p " : "" );
}
if ( one > 0 )
{
System.out.print( one > 0 ? one + "*1p " : "" );
}
System.out.print("\n");
}
System.out.print("#Please enter the amount of change : ");
change = BIO.getInt();
}
}
}
what you could do is define your coins as emums,
ie:
enum Coin {
twopounds(200), pounds(100), fifty(50), twenty(20), ten(10), five(5), two(
2), one(1);
int value;
Coin(int value) {
this.value = value;
}
int getCoins(int amount){
return amount/value;
}
int getReminder(int amount){
return amount%value;
}
}
then you could do
int change = 321;
for (Coin coin : Coin.values()){
int count = coin.getCoins(change );
if (count!=0){
System.out.println(coin.name()+" : " +count);
}
change = coin.getReminder(change );
}
and that will prints you your change in coins,
you could take this further, and define your wallet where you hold all your money
ie
class Wallet{
int money;
int getAllCoins(Coin coin){
int coins = coin.getCoins(money);
money=coin.getReminder(money);
return coins;
}
}
but this will be overkill for this simple scenario
You don't want entries with 1 coin to be displayed as 1*value so replace the comparison
System.out.print( twopounds > 0 ? twopounds + "*200p " : " " );
to
System.out.print( twopounds > 1 ? twopounds + "*200p " : "200p " );
in other words, you compare the numberOfCoins to one, if it's just one coin, then write just the value of the coin. Else write numberOfCoins * value
Replace the relevant part of your code with this:
if ( twopounds > 0 )
{
System.out.print( twopounds > 1 ? twopounds + "*200p " : "200p " );
}
if ( pounds > 0 )
{
System.out.print( pounds > 1 ? pounds + "*100p " : "100p " );
}
if ( fifty > 0 )
{
System.out.print( fifty > 1 ? fifty + "*50p " : "50p " );
}
if ( twenty > 0 )
{
System.out.print( twenty > 1 ? twenty + "*20p " : "20p " );
}
if ( ten > 0 )
{
System.out.print( ten > 1 ? ten + "*10p " : "10p " );
}
if ( five > 0 )
{
System.out.print( five > 1 ? five + "*5p " : "5p " );
}
if ( two > 0 )
{
System.out.print( two > 1 ? two + "*2p " : "2p " );
}
if ( one > 0 )
{
System.out.print( one > 1 ? one + "*1p " : "1p " );
}
why do my last two if statements have illegal start of expression and else without if errors? also I cannot post my code here because it wants formatting and I do not know how to do it properly. how do I post an actual code view?
I have changed it and this is the edited code. thank you for all of your help.
//Import Java scanner
import java.util.Scanner;
//This class ask a user for their item count and informs the user of the best packing method.
public class PackingOrganizer{
public static void main(String[] args){
//declare constants and variables
int CARTONS = 4, BOXES = 5;
double containerAmount;
double containerAmount2;
//Get users item count
Scanner input = new Scanner(System.in);
System.out.print("Enter number of items : (All partial items are to be rounded up. ex. 6.5 items is rounded to 7 items)");
double itemCount = input.nextDouble();
//Check to see if input is an integer value
if (itemCount != (int) itemCount)
System.out.println("Invalid input round all partial numbers up");
//processing phase
else if (itemCount % CARTONS == 0){
containerAmount =( itemCount /CARTONS );
System.out.println("Cartons can be used. The " + itemCount + " items will require " + containerAmount + " cartons ");}
else if (itemCount % BOXES ==0){
containerAmount = (itemCount / BOXES);
System.out.println("Boxes can be used. The " + itemCount + " items will require " + containerAmount + " Boxes ");}
else if ((itemCount % BOXES != 0) && (itemCount % CARTONS != 0))
System.out.println("Neither boxes nor cartons can be used for your: " + itemCount + " items.");
else if ((itemCount % BOXES == 0) && (itemCount % CARTONS == 0 ));{
containerAmount = (itemCount/BOXES);
containerAmount2 = (itemCount/CARTONS);
System.out.println("Cartons can be used. The " + itemCount + " items will require " + containerAmount2 +"." + " Boxes can be used. The " + itemCount + " items will require" + containerAmount +" boxes ");}
}
}
In the third else statement, you have some parentheses missing. The entire boolean condition must be enclosed in parentheses. Also, you should use == instead of =, because == checks for equality, and = is the assignment operator. Also, the third else if statement has a semicolon instead of an opening curly brace at its end, and the statement directly following it needs a quotation mark, a parenthesis, and a semicolon added at the end.
You need == in the last else if not =
= is an assignment operator, whereas == checks for equality (with primitives).
else if (itemCount % BOXES != 0) && (itemCount % CARTONS != 0);
System.out.println("Neither boxes nor cartons can be used for your: " + itemCount + " items.
else if (itemCount % BOXES = 0) && (itemCount % CARTONS = 0 );{
Should be this, without the semicolons after the else if statments. You are saying your statement is done when you leave them in there and the compiler is confused by the next else statements.
EDIT: Also as the other answers talk about, wrap your ifs in parthesis, and you should use == when doing a comparison.
else if ((itemCount % BOXES != 0) && (itemCount % CARTONS != 0))
System.out.println("Neither boxes nor cartons can be used for your: " + itemCount + " items.
else if ((itemCount % BOXES == 0) && (itemCount % CARTONS = 0 )){
Too may bracketing errors to keep track of them all. And you need to fix the = to == as mentioned my another ansewer. Here's the refactor. You can compare it with your current code.
import java.util.Scanner;
//This class ask a user for their item count and informs the user of the best packing method.
public class PackingOrganizer {
public static void main(String[] args) {
//declare constants and variables
int CARTONS = 4, BOXES = 5;
double containerAmount;
double containerAmount2;
//Get users item count
Scanner input = new Scanner(System.in);
System.out.print("Enter number of items : (All partial items are to be rounded up. ex. 6.5 items is rounded to 7 items)");
double itemCount = input.nextDouble();
//Check to see if input is an integer value
if (itemCount != (int) itemCount) {
System.out.println("Invalid input round all partial numbers up");
} //processing phase
else if (itemCount % CARTONS == 0) {
containerAmount = (itemCount / CARTONS);
System.out.println("Cartons can be used. The " + itemCount + " items will require " + containerAmount + " cartons ");
} else if (itemCount % BOXES == 0) {
containerAmount = (itemCount / BOXES);
System.out.println("Boxes can be used. The " + itemCount + " items will require " + containerAmount + " Boxes ");
} else if ((itemCount % BOXES != 0)
&& (itemCount % CARTONS != 0)) {
System.out.println("Neither boxes nor cartons can be used for your: " + itemCount + " items");
} else if ((itemCount % BOXES == 0)
&& (itemCount % CARTONS == 0)) {
containerAmount = (itemCount / BOXES);
containerAmount2 = (itemCount / CARTONS);
System.out.println("Cartons can be used. The " + itemCount + " items will require " + containerAmount2 + "." + " Boxes can be used. The " + itemCount + " items will require" + containerAmount + " boxes ");
}
}
}
I'm working on a coin flip assignment and I have the majority of it functioning properly (albeit in a less elegant fashion compared to the code I see on here).
I'm trying to find a way to tell the user which number appears most in their flips, and if heads are assigned to even #s, and tails to odd #s, which one came up the most. I'm looking for suggestions to implement these features.
Here is the code thus far:
import java.io.*;
import java.util.*;
public class coinFlip {
public static void main(String[] args) throws IOException {
// declare in as a BufferedReader; used to gain input from the user
BufferedReader in;
in = new BufferedReader(new InputStreamReader(System.in));
//declare variables
int flips;
int anArray[];
int x;
int r;
int counter1 = 0;
int counter2 = 0;
int counter3 = 0;
int counter4 = 0;
int counter5 = 0;
int counter6 = 0;
int counter7 = 0;
int counter8 = 0;
int counter9 = 0;
int counter10 = 0;
System.out.println("How many times would you like to flip your coin?");
flips = Integer.parseInt(in.readLine());
if (flips > 1000) {
System.out.println("Invalid input, restart program!");
}
if(flips <= 1000) {
System.out.println("You want to flip " + flips + " times");
anArray = new int[flips];
for(x = 0; x < flips; x++) {
r = (int) Math.round(Math.random()*9)+1;
anArray[x] = r;
System.out.println(anArray[x]);
if (anArray[x] == 1) {
counter1 += 1;
}
else if (anArray[x] == 2) {
counter2 += 1;
}
else if (anArray[x] == 3) {
counter3 += 1;
}
else if (anArray[x] == 4) {
counter4 += 1;
}
else if (anArray[x] == 5) {
counter5 += 1;
}
else if (anArray[x] == 6) {
counter6 += 1;
}
else if (anArray[x] == 7) {
counter7 += 1;
}
else if (anArray[x] == 8) {
counter8 += 1;
}
else if (anArray[x] == 9) {
counter9 += 1;
}
else if (anArray[x] == 10) {
counter10 += 1;
}
}
System.out.println("\n You rolled 1 " + counter1 + " times.");
System.out.println("You rolled 2 " + counter2 + " times.");
System.out.println("You rolled 3 " + counter3 + " times.");
System.out.println("You rolled 4 " + counter4 + " times.");
System.out.println("You rolled 5 " + counter5 + " times.");
System.out.println("You rolled 6 " + counter6 + " times.");
System.out.println("You rolled 7 " + counter7 + " times.");
System.out.println("You rolled 8 " + counter8 + " times.");
System.out.println("You rolled 9 " + counter9 + " times.");
System.out.println("You rolled 10 " + counter10 + " times.");
}
}
}
import java.io.*;
import java.util.Random;
public class CoinFlip {
public static void main(final String[] args) throws IOException {
// declare in as a BufferedReader; used to gain input from the user
final BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
//declare variables
System.out.println("How many times would you like to flip your coin?");
final int flips = Integer.parseInt(in.readLine());;
if (flips > 1000) {
System.out.println("Invalid input, restart program!");
return;
}
System.out.println("You want to flip " + flips + " times");
final int[] counters = new int[10],
side = new int[2];
int r=0,x,max=0;
final Random rand = new Random();
for(x = 0; x < flips; ++x) {
r = rand.nextInt(10);
System.out.println(r+1);
counters[r]++;
}
for ( x = 0; x < counters.length; ++x )
{
System.out.println("You rolled " + (x+1) + " " + counters[x] + " times.");
if ( counters[x] > max )
{
max = counters[x];
r = x+1;
}
side[x%2] += counters[x];
}
System.out.println(r + " was rolled most.");
System.out.println("You rolled " + side[0] + " heads and " + side[1] + " tails." );
}
}
Using loops, as shown in another answer, will make life much easier.
There is a more critical logic error in your code:
You round the output of Math.random(), which gives a float between 0 and 1, and round that to get an integer. The following table shows what output you'll get from your code in respect to the RNG:
| Math.random() output | Resulting Integer |
| 0 ~ 0.04999 | 0 |
| 0.05 ~ 0.14999 | 1 |
| ...... | ..... |
| 0.95 ~ 0.99999 | 10 |
See the problem? 0 and 10 appear only half as much as the other numbers.
You should either floor() the output, or use Random.nextInt() to generate a uniform distribution of ints.
This would make your life much easier:
int counter[10];
...
for(x = 0; x < flips; x++) {
r = (int) Math.round(Math.random()*9)+1;
anArray[x] = r;
System.out.println(anArray[x]);
counter[r-1]++;
}
for(i=1; i <= counter.length; i++)
System.out.println("You rolled " + i + " " + counter[i-1] + " times.");
For your other two problems, there's nothing to really "suggest". Just iterate over counter, remember the largest value, and add up the even and odd indices separately.