Battle of Numbers - java

Hi everyone I'm a newbie in Java and I have a sample problem. I also have my own solution. Is there any other better way to solve this problem?
In far far away kingdom, there were battles of numbers. The king in that kingdom asks you to create a program that will determine the winner / champion of that event. The number of contestant is undetermined. The winner of the match is usually the BIGGEST number. The match is a single elimination. The sequence of the match is First IN vs Last IN, Second In vs Last Second In, etc... If there are no opponents for a particular number, he or she will be considered as default winner.
Sample Output:
Enter the Number of Contestant: 5
Enter Contestant # 1: 50
Enter Contestant # 2: 30
Enter Contestant # 3: 8
Enter Contestant #4: 11
Enter Contestant #5: 20
Simulation:
Round 1: 50 vs 20 Winner is: 50
Round 2: 30 vs 11 Winner is: 30
Round 3: Default Winner is: 8
Next …
Round 4: 50 vs 8 Winner is: 50
Round 5: Default Winner is 30
Next …
Round 6: 50 vs 30 Winner is: 50
Champion: 50
Total Bracket Matches: 3
Total Rounds: 6
My solution:
import java.util.Scanner;
public class BattleofNumbers{
public static void main(String[] args){
double num1, num2, num3, num4, num5;
double chal1, chal2, chal3, champion;
double bracket, round = 0;
System.out.println("Please Enter 5 Numbers: ");
System.out.println("");
Scanner in = new Scanner(System.in);
num1 = in.nextDouble();
num2 = in.nextDouble();
num3 = in.nextDouble();
num4 = in.nextDouble();
num5 = in.nextDouble();
System.out.println("");
if (num1 > num5){
chal1 = num1;
round++;
System.out.println("Round 1 Winner: " + chal1);
}
else{
chal1 = num5;
round++;
System.out.println("Round 1 Winner: " + chal1);
}
if (num2>num4){
chal2 = num2;
round++;
System.out.println("Round 2 Winner: " + chal2);
}else{
chal2 = num4;
round++;
System.out.println("Round 2 Winner: " + chal2);
}
if (chal1>num3){
chal3 = chal1;
round++;
System.out.println("Round 3 Winner: " + chal3);
}else{
chal3 = num3;
round++;
System.out.println("Round 3 Winner: " +chal3);
}
if (chal3 > chal2){
champion = chal3;
round++;
System.out.println("Round 4 Winner: " + champion);
}else{
champion = chal2;
round++;
System.out.println("Round 4 Winner: " + champion);
}
bracket = round / 2;
System.out.println("=====================");
System.out.println("The Champion: " + champion);
System.out.println("No. of Rounds: " + round );
System.out.println("No. of Brackets: " + bracket);
}
}

I tried a small implementation using arrays and I would call it semi-recursion. I'm sure it's not perfect, but it's a more generic approach because the amount of input numbers is dynamic and the condition check programmed only once. Feel free to give feedback on this, maybe someone has an idea to perform each check recursively.
import java.util.Scanner;
public class BattleofNumbers {
double[] nums;
int amount, round = 0;
double champ;
Scanner in;
public BattleofNumbers() {
in = new Scanner(System.in);
initValues();
processGame();
}
public void processGame() {
champ = calcChamp(nums);
System.out.println("=====================");
System.out.println("The Champion: " + champ);
System.out.println("No. of Rounds: " + round);
System.out.println("No. of Brackets: "
+ (int) Math.ceil((double) round / 2));
}
private void initValues() {
System.out.println("Please enter amount of numbers:");
amount = in.nextInt();
nums = new double[amount];
for (int i = 0; i < amount; i++) {
System.out.println("Please enter " + (i + 1) + ". number:");
nums[i] = in.nextDouble();
}
System.out.println("");
}
public double calcChamp(double[] nums) {
double[] nexts = new double[(int)Math.ceil(((double) nums.length / 2))];
for (int first = 0, second = (nums.length - 1); first <= second; first++, second--) {
if (nums[first] > nums[second]) {
nexts[first] = nums[first];
} else {
nexts[first] = nums[second];
}
round++;
System.out
.println("Winner of round " + round + ": " + nexts[first]);
}
if (nexts.length == 1) {
return nexts[0];
} else {
return calcChamp(nexts);
}
}
public static void main(String[] args) {
new BattleofNumbers();
}
}

I don't know how experienced you are, but you should use arrays instead of 5 single variables: double[] nums = new double[5];. Also, the variable "brackets" isn't needed because it is always round/2 so you can replace it: System.out.println("No. of Brackets: " + round/2);
Because line 2 and line 3 of every if-else-block are used in both the if- and the else-block, you should outsource them (and thereby reduce the amount of code):
if (num1 > num5){
chal1 = num1;
// round++;
// System.out.println("Round 1 Winner: " + chal1);
}
else {
chal1 = num5;
// round++;
// System.out.println("Round 1 Winner: " + chal1);
}
round++;
System.out.println("Round 1 Winner: " + chal1);
"round" seems to be constant at 4. You could stop counting it up and just declare it with 4: double round = 4;

This solution shows you how you can use ArrayList for such things (and how it is unlikely to be used in real code):
import java.util.ArrayList;
import java.util.Scanner;
public class Prog{
public static void main(String[] args){
ArrayList<Double> nums = new ArrayList<Double>();
Scanner in = new Scanner(System.in);
System.out.println("How many contestants are there? ");
int size = in.nextInt();
while(size-- > 0){
System.out.println("Contestant: ");
nums.add(in.nextDouble());
}
while(nums.size() > 1){
System.out.println("ROUND STARTED, contestants are: " + nums);
int i = 0;
while(i < nums.size()){
nums.set(i, Math.max(nums.get(i), nums.get(nums.size()-1)));
if(i != nums.size() - 1)
nums.remove(nums.size() -1);
i++;
}
}
System.out.println("Competition has ended, the winner is: " + nums.get(0));
}
}

Related

How can i add the random number to my total for java(blackjack)?

This is my code:
import java.util.*;
import java.util.Scanner;
public class Assignment2 {
public static void main(String args[]){
Scanner stdin = new Scanner(System.in);
Random random = new Random();
int ran2 = (random.nextInt(10));
int ran1 = (random.nextInt(10));
int total = ran1 + ran2;
char exit = 'y';
System.out.println("First cards: " + ran1 + ", " + ran2);
System.out.println("Total: " + total);
while(exit != 'n' && total < 21){
System.out.println("Do you want another card? (y/n): ");
exit = stdin.next().charAt(0);
System.out.println("Card: "+ (random.nextInt(10)));
total = total + (random.nextInt(10));
System.out.println("Total: "+ total);
}
}
}
When I enter n, how can I make it so the program exit, instead of printing out the total again?
Check this out:
public class Assignment2 {
public static void main(String args[]){
int next = 0;
Scanner stdin = new Scanner(System.in);
Random random = new Random();
int ran2 = (random.nextInt(10));
int ran1 = (random.nextInt(10));
int total = ran1 + ran2;
char exit = 'y';
System.out.println("First cards: " + ran1 + ", " + ran2);
System.out.println("Total: " + total);
while(exit != 'n' && total < 21){
System.out.println("Do you want another card? (y/n): ");
exit = stdin.next().charAt(0);
next = random.nextInt(10);
System.out.println("Card: "+ next);
total = total + next;
System.out.println("Total: "+ total);
}
if (exit.equals('n'))
system.exit(0);
}
}
Now the program exists after you enter n by calling system.exit(0).
You need to call nextInt just once, so you won't create 2 different random numbers. So I put the first call into a variable next so you could use it as many times as you please without having to call nextInt again.
If you want the program to exit immediately after the user enters n, you will want to put the if statement right after the exit = stdin.next().charAt(0);
If you want to exit the loop, you can break from it. Basically you have to do this(I have written comments to highlight the alterations)-
import java.util.*;
import java.util.Scanner;
public class Assignment2 {
public static void main(String args[]){
Scanner stdin = new Scanner(System.in);
Random random = new Random();
int ran2 = (random.nextInt(10));
int ran1 = (random.nextInt(10));
int total = ran1 + ran2;
char exit = 'y';
System.out.println("First cards: " + ran1 + ", " + ran2);
System.out.println("Total: " + total);
while(exit != 'n' && total < 21){
System.out.println("Do you want another card? (y/n): ");
exit = stdin.next().charAt(0);
//you need to check here if the user entered 'n'. I have used a break opertion
//to break from the loop and print the total outside the loop. But if you want
//to exit the program altogether, just replace break with exit(0) :)
if(total >= 21 or exit == 'y') {
break;
}
//As Idos correctly pointed out that by calling random.nextInt(10) two
//times you have a very big chance of creating two different random numbers.
//So it makes sense to put the first call into a variable nextNumber.
int nextNumber = random.nextInt(10);
total = total + (nextNumber);
//Now we should again check for total. If it is greater than or equal to 21
//I am again breaking from the loop. Feel free to replace break with exit(0).
if(total >= 21) {
break;
}
System.out.println("Total: "+ total);
}
System.out.println("Your total- "+ total);
}
}

trying to understand my error in my pig java game

I am working on my final project for my intro to java class and i am having a hard time understanding the errors in my project and why it will not run if you could tell me why i would greatly appreciate it
public static void main(String[] args) {
Scanner scanner1;
int dice, dice2;
int pScore, cScore = 0;
int pTotalScore = 0;
int cTotalScore = 0;
final int maxScore = 750;
String input = "R";
String input2 = "R";
char repeat;
Random randomNumbers = new Random();
System.out.println("Welcome to Our version of the dice game Pig");
System.out.println("Here are the instructions");
System.out.println("On a turn, the player or computer rolls the die repeatedly");
System.out.println("Until either a 1,7,12, or 17 is rolled");
System.out.println("or the player or computer holds");
System.out.println("If a 1,7,12, or 17 is rolled, that player's turn ends");
System.out.println("and no points are earned");
System.out.println("If the player chooses to hold, all of the points rolled during");
System.out.println("that turn are added to his or her score.");
System.out.println("First player to 750 points or more WINS!");
System.out.print("\nPlease enter your name: ");
scanner1 = new Scanner(System.in);
String pName = scanner1.nextLine();
System.out.print("\nI Hope You have fun," + pName);
do { // run at least once. Start of loop
dice = randomNumbers.nextInt(6) + 1;
System.out.println();
System.out.printf("%s you rolled a %d %n", pName, dice);
if (dice == 1 || dice == 7 || dice == 12 || dice == 17) // if these numbers, end
{
pScore = 0;
System.out.println("Turn over.");
System.out.println(" " + pName + " total is " + pScore + " ");
break;
} else { // else ask for re-roll
pScore = dice;
pTotalScore += pScore;
System.out.print(+pScore + " Your turn total is " + pTotalScore + " ");
System.out.print("Enter (R) to roll or (H)to hold: ");
input = scanner1.nextLine();
repeat = input.charAt(0);
}
if (repeat != 'R') { // if something other than R, end
break;
}
} while (pTotalScore < 750 || cTotalScore < 750); // allow repeat so long as scores are less than 750
if (repeat == 'H') {
System.out.println("Turn over.");
System.out.print("Current score: " + pname + " has " + pTotalScore);
System.out.println("The Computer has " + cTotalScore);
break;
}
while (input.equalsIgnoreCase("R"));
if (pTotalScore >= maxScore) {
System.out.println("Your total Score is " + totalScore);
System.out.println(+pname + "WINS!");
break;
}
System.out.println();
System.out.println("It is the Computer's turn.");
do {
dice2 = randomNumbers.nextInt(6) + 1;
System.out.println("The Computer rolled: " + dice2);
if (dice2 == 1 || dice2 == 7 || dice2 == 12 || dice2 == 17) {
cScore = 0;
System.out.print("Turn over");
System.out.println("The Computer total is " + cTotalScore);
break;
} else {
cScore = dice2;
cTotalScore += cScore;
System.out.print("The Computer's total is " + cTotalScore + " ");
System.out.print("Enter (r) to Roll or (H)to Hold: ");
input = keyboard.nextLine();
repeat = input.charAt(0);
}
if (repeat == 'H') {
System.out.println("Turn over");
System.out.print("Current score:" + pName + " has " + pTotalScore);
System.out.println(", The Computer has " + cTotalScore);
break;
}
} while (input2.equalsIgnoreCase("R"));
if (cTotalScore >= maxScore) {
System.out.println("The Computer's score is " + cTotalScore + "\n");
System.out.println("The Computer wins!!!!");
System.out.printl("Run The uprisng has begun!!!!!!");
break;
}
Final3.java:112: error: reached end of file while parsing } ^ 1 error
now the problem is i get the error basically means im missing a } but i cant see where it would be nd no matter where i put it it still says
Final3.java:112: error: reached end of file while parsing } ^ 1 error
You have one while loop that does nothing - while (input.equalsIgnoreCase("R")); - and you didn't close your main method. Add } at the end.
Add a closing brace "}" in the end.I hope this will solve your purpose.

Java Lottery Array Program

I am designing a program for my class that is supposed to simulate a lottery game. I am supposed to design a method that generates random lottery numbers, a method that asks and stores the user for their number choices, a method that compares the arrays to find how many numbers are the same, and then I am supposed to call them all back up to the main method, and create my output statement that contains some if statements that determine which prize is awarded for the particular amount of matches.
Here is what I have thus far
import java.util.*;
public class LotteryGame {
/**
The main method is the program's starting point
*/
public static void main(String[] args){
int NUM_DIGITS = 5;
int[] userDigits = new int[5];
int[] lotteryNumbers = new int[5];
int sameNum;
generateNumbers(lotteryNumbers);
getUserData(userDigits);
compareArrays();
System.out.println("Lottery numbers: " + lotteryNumbers[0] + " " +
lotteryNumbers[1] + " " + lotteryNumbers[2] + " " + lotteryNumbers[3] +
" " + lotteryNumbers[4] + " ");
System.out.println("Player numbers: " + userDigits[0] + " " + userDigits[1] + " " + userDigits[2] + " " + userDigits[3] + " " + userDigits[4] + " ");
System.out.println("Number of matching digits: " + sameNum);
if (sameNum == 5){
System.out.println("GRAND PRIZE WINNER - $5 MILLION!!");
}
if (sameNum == 4){
System.out.println("SUPER PRIZE WINNER - $500,000!!");
}
if (sameNum == 3){
System.out.println("GOOD PRIZE WINNER - $5,000!!");
}
if (sameNum == 2){
System.out.println("NICE PRIZE WINNER - $500!!");
}
if (sameNum == 1){
System.out.println("WINNER - $5!!");
}
if (sameNum ==0){
System.out.println("No matching numbers - better luck next time");
}
}
public static int generateNumbers(int [] lotteryNumbers){
Random randNum = new Random();
lotteryNumbers[0] = randNum.nextInt(10);
lotteryNumbers[1] = randNum.nextInt(10);
lotteryNumbers[2] = randNum.nextInt(10);
lotteryNumbers[3] = randNum.nextInt(10);
lotteryNumbers[4] = randNum.nextInt(10);
return lotteryNumbers[4];
}
public static int getUserData (int [] userDigits){
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter digit 1: ");
userDigits[0] = keyboard.nextInt();
System.out.print("Enter digit 2: ");
userDigits[1] = keyboard.nextInt();
System.out.print("Enter digit 3: ");
userDigits[2] = keyboard.nextInt();
System.out.print("Enter digit 4: ");
userDigits[3] = keyboard.nextInt();
System.out.print("Enter digit 5: ");
userDigits[4] = keyboard.nextInt();
return userDigits[4];
}
public static int compareArrays (int [] userDigits,
int [] lotteryNumbers){
int sameNum = 0;
for (int i = 0; i < 5; i++){
for (int x = 0; x < 5; x++){
if (lotteryNumbers[i] == userDigits[x]){
sameNum++;
}
return sameNum;
}
return sameNum;
}
return sameNum;
}
}
I am very new to arrays (and Java at that) so my problems are in my return/call statements. Please excuse my spacey coding style and any blatant mistakes that I have made. Any tips,advice, solutions, or if you notice anything wrong with what I have please let me know. Thanks!
Keep in mind that randNum.nextInt(10) will give you lottery numbers that range from 0 to 9. You can use a for loop to assign the random numbers to the lotteryNumbers array easier. Also, you should make sure that the random lottery numbers don't repeat.
In your compareArrays function, just put one return sameNum call after the outermost for loop, otherwise it won't update with the correct number of matching numbers. You need to give compareArrays() the correct parameters (userDigits and lotteryNumbers) and set sameNum equal to this result.
Several points you might find useful:
You might want to use NUM_DIGITS for the initiation of the arrays since that's the whole point of having named constant:
int[] userDigits = new int[NUM_DIGITS];
int[] lotteryNumbers = new int[NUM_DIGITS];
You can use Arrays.toString() to output arrays, e.g.:
System.out.println(Arrays.toString(lotteryNumbers));
Instead of multiple ifs use switch, plus do not repeat the whole print statement, only assign the part that differs:
String prize = "";
switch (sameNum) {
case 5: prize = "GRAND PRIZE WINNER - $5 MILLION!!";
break;
case 4: prize = "SUPER PRIZE WINNER - $500,000!!";
break;
case 3: prize = "GOOD PRIZE WINNER - $5,000!!";
break;
case 2: prize = "NICE PRIZE WINNER - $500!!";
break;
case 1: prize = "WINNER - $5!!";
break;
case 0: prize = "No matching numbers - better luck next time";
break;
default: prize = "Something weird happened";
}
System.out.println(prize);
I've updated your code with the changes you'll need.
Added NUM_DIGITS to your initializer
Closed your Scanner
Removed the early returns in your comparison method
Assigned the return value of the comparison method to sameNum
Set the return value of the generation and get methods to void
The other suggestions might be something you want to incorporate (such as the switch/case).
import java.util.Random;
import java.util.Scanner;
public class App {
public static void main(String[] args) {
int NUM_DIGITS = 5;
int[] userDigits = new int[NUM_DIGITS];
int[] lotteryNumbers = new int[NUM_DIGITS];
int sameNum;
generateNumbers(lotteryNumbers);
getUserData(userDigits);
sameNum = compareArrays(lotteryNumbers, userDigits);
System.out.println("Lottery numbers: " + lotteryNumbers[0] + " "
+ lotteryNumbers[1] + " " + lotteryNumbers[2] + " "
+ lotteryNumbers[3] + " " + lotteryNumbers[4] + " ");
System.out.println("Player numbers: " + userDigits[0] + " "
+ userDigits[1] + " " + userDigits[2] + " " + userDigits[3]
+ " " + userDigits[4] + " ");
System.out.println("Number of matching digits: " + sameNum);
if (sameNum == 5) {
System.out.println("GRAND PRIZE WINNER - $5 MILLION!!");
}
if (sameNum == 4) {
System.out.println("SUPER PRIZE WINNER - $500,000!!");
}
if (sameNum == 3) {
System.out.println("GOOD PRIZE WINNER - $5,000!!");
}
if (sameNum == 2) {
System.out.println("NICE PRIZE WINNER - $500!!");
}
if (sameNum == 1) {
System.out.println("WINNER - $5!!");
}
if (sameNum == 0) {
System.out.println("No matching numbers - better luck next time");
}
}
public static void generateNumbers(int[] lotteryNumbers) {
Random randNum = new Random();
lotteryNumbers[0] = randNum.nextInt(10);
lotteryNumbers[1] = randNum.nextInt(10);
lotteryNumbers[2] = randNum.nextInt(10);
lotteryNumbers[3] = randNum.nextInt(10);
lotteryNumbers[4] = randNum.nextInt(10);
return lotteryNumbers[4];
}
public static void getUserData(int[] userDigits) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter digit 1: ");
userDigits[0] = keyboard.nextInt();
System.out.print("Enter digit 2: ");
userDigits[1] = keyboard.nextInt();
System.out.print("Enter digit 3: ");
userDigits[2] = keyboard.nextInt();
System.out.print("Enter digit 4: ");
userDigits[3] = keyboard.nextInt();
System.out.print("Enter digit 5: ");
userDigits[4] = keyboard.nextInt();
keyboard.close();
return userDigits[4];
}
public static int compareArrays(int[] userDigits, int[] lotteryNumbers) {
int sameNum = 0;
for (int i = 0; i < 5; i++) {
for (int x = 0; x < 5; x++) {
if (lotteryNumbers[i] == userDigits[x]) {
sameNum++;
}
}
}
return sameNum;
}
}

How to get my program to start over when the user hits "y" on

So I've used System.out.print("Enter more test scores? (y/n): "); yet when I run it and all the scores are summarizes the user isn't given the chance to do it again here is my code. Do you guys think I may have put it in the wrong place.
public class TestScoreApp
{
public static void main(String[] args) {
// display operational messages
System.out.println("Please enter the number of test scores to be entered");
System.out.println("To end the program enter 999.");
System.out.println(); // print a blank line
int scoreTotal = 0;
int scoreCount = 0;
int testScore = 0;
int min = 100;
int max = 0;
int counter = 0;
int setNumber = 0;
String userAnswer = "n";
Scanner sc = new Scanner(System.in);
// get a series of test scores from the user
outerLoop:
do {
// user enters number of test scores to be entered
System.out.print("Enter the number of test scores to be entered: ");
setNumber = sc.nextInt();
if (setNumber > 0 && setNumber != 999)
{
while (setNumber > 0)
{
// user enters test scores
System.out.print("Enter score: ");
testScore = sc.nextInt();
// accumulate score count and score total
if (testScore <= 100)
{
scoreCount += 1;
scoreTotal += testScore;
setNumber --;
} //Added for Exercise 2-2, #4 modified if statement
else if (testScore > 100 || testScore < 0) {
System.out.println("Invalid entry, score not counted");
} else if (testScore == 999) {
System.out.println("Average test score complete");
}
if (testScore > max && testScore <= 100) {
max = testScore;
}
if (testScore < min && testScore >= 0) {
min = testScore;
}
if (setNumber == counter)
{
break outerLoop;
}
//End of test scores while loop
}
userAnswer = sc.next();
}
}// end of do loop
while(userAnswer.compareTo("y") == 0 );
System.out.print("Enter more test scores? (y/n): ");
// display the score count, score total, and average score
// Added casting from int ot double Exercise 3-2 #5
double averageScore = (double) scoreTotal / (double) scoreCount;
// Added number formatting ( 1 decimal place)
NumberFormat number = NumberFormat.getNumberInstance();
number.setMaximumFractionDigits(1);
String message = "\n"
+ "Score count: " + scoreCount + "\n"
+ "Score total: " + scoreTotal + "\n"
+ "Average score: " + averageScore + "\n"
//Added for Exercise 3-2 #4 add min/max
+ "Max score: " + max + "\n"
+ "Min score: " + min + "\n";
System.out.println(message);
}
}
I dont know what exactly you want to do, if you want to ask if the user want to add more scores after the default scores (that user set on beggining) so this is the answer:
import java.text.NumberFormat;
import java.util.Scanner;
public class TestScoreApp {
public static void main(String[] args) {
// display operational messages
System.out.println("Please enter the number of test scores to be entered");
System.out.println("To end the program enter 999.");
System.out.println(); // print a blank line
// declarations
int scoreTotal = 0;
int scoreCount = 0;
int testScore = 0;
int min = 100;
int max = 0;
int counter = 0;
int setNumber = 0;
String userAnswer = "n";
Scanner sc = new Scanner(System.in);
// get a series of test scores from the user
// outerLoop:
// do {
// user enters number of test scores to be entered
System.out.print("Enter the number of test scores to be entered: ");
setNumber = sc.nextInt();
if (setNumber > 0 && setNumber != 999) {
do { // put the loop condition below
// user enters test scores
System.out.print("Enter score: ");
testScore = sc.nextInt();
// accumulate score count and score total
if (testScore <= 100) {
scoreCount += 1;
scoreTotal += testScore;
setNumber--;
} // Added for Exercise 2-2, #4 modified if statement
else if (testScore > 100 || testScore < 0) {
System.out.println("Invalid entry, score not counted");
} else if (testScore == 999) {
System.out.println("Average test score complete");
}
if (testScore > max && testScore <= 100) {
max = testScore;
}
if (testScore < min && testScore >= 0) {
min = testScore;
}
// if (setNumber == counter) {
// break outerLoop;
// }
if (setNumber == counter) { // test if the counter reached zero
System.out.print("Enter more test scores? (y/n): "); // ask if the user want to add more
userAnswer = new Scanner(System.in).next(); // read the input
if (userAnswer.toCharArray()[0] == 'y') { // if yes, do
setNumber += 1; // add +1 to setNumber, so user can add more one score
}
}
} while (setNumber > 0);
}
// display the score count, score total, and average score
// Added casting from int ot double Exercise 3-2 #5
double averageScore = (double) scoreTotal / (double) scoreCount;
// Added number formatting ( 1 decimal place)
NumberFormat number = NumberFormat.getNumberInstance();
number.setMaximumFractionDigits(1);
String message = "\n" + "Score count: " + scoreCount + "\n"
+ "Score total: " + scoreTotal + "\n" + "Average score: "
+ averageScore + "\n"
// Added for Exercise 3-2 #4 add min/max
+ "Max score: " + max + "\n" + "Min score: " + min + "\n";
System.out.println(message);
}
}
There are several modifications to be done in the program.
When you are asking user to enter the choice for inputting more, you should accept his/her choice in your userAnswer variable before closing off the do-while loop SO THAT THE USER CHOICE CAN BE CHECKED AFTER EACH ITERATION!
There is no need to break the OUTER-LOOP without checking user's input!
scoreCount & scoreTotal need to be initialised with 0 again in the beginning of the do-while loop.
The corrected program along with the imports needed :-
import java.text.NumberFormat;
import java.util.Scanner;
public class JavaApplication7 {
public static void main(String[] args) {
System.out.println("Please enter the number of test scores to be entered");
System.out.println("To end the program enter 999.");
System.out.println(); // print a blank line
int scoreCount = 0,scoreTotal = 0;
int testScore = 0;
int min = 100;
int max = 0;
int counter = 0;
int setNumber = 0;
String userAnswer = "n";
Scanner sc = new Scanner(System.in);
// get a series of test scores from the user
do {
// user enters number of test scores to be entered
System.out.print("Enter the number of test scores to be entered: ");
setNumber = sc.nextInt();
if (setNumber > 0 && setNumber != 999)
{
scoreCount=0;
scoreTotal=0;
while (setNumber > 0)
{
// user enters test scores
System.out.print("Enter score: ");
testScore = sc.nextInt();
if (testScore <= 100)
{
scoreCount += 1;
scoreTotal += testScore;
setNumber --;
} //Added for Exercise 2-2, #4 modified if statement
else if (testScore > 100 || testScore < 0) {
System.out.println("Invalid entry, score not counted");
} else if (testScore == 999) {
System.out.println("Average test score complete");
}
if (testScore > max && testScore <= 100) {
max = testScore;
}
if (testScore < min && testScore >= 0) {
min = testScore;
}
}
// display the score count, score total, and average score
// Added casting from int ot double Exercise 3-2 #5
double averageScore = (double) scoreTotal / (double) scoreCount;
// Added number formatting ( 1 decimal place)
NumberFormat number = NumberFormat.getNumberInstance();
number.setMaximumFractionDigits(1);
String message = "\n"
+ "Score count: " + scoreCount + "\n"
+ "Score total: " + scoreTotal + "\n"
+ "Average score: " + averageScore + "\n"
//Added for Exercise 3-2 #4 add min/max
+ "Max score: " + max + "\n"
+ "Min score: " + min + "\n";
System.out.println(message);
}
System.out.print("Enter more test scores? (y/n): ");
userAnswer=sc.next(); // Single Error----Only corrected piece of code.
}while(userAnswer.compareTo("y") == 0 );
// end of do loop
}
}
You are asking the user:
System.out.print("Enter more test scores? (y/n): ");
after you exit from the while loop. This won't work. Just put this line exactly before:
userAnswer = sc.next();

unable to get the correct output for input .11

I have an assignment at school and I have to display the correct change for an amount that is being input by the user that is less than 1.00 but greater than 0. Every amount works except anything in a double digit that has a 1 or a 6 on the tenth spot. for example .11, .16, .21, .26 etc.
this is my code
import java.util.Scanner;
public class AmountChange
{
public static void main(String[] args)
{
//
double amt;
int cents, quarter, dime, nickle, penny;
Scanner keyboard = new Scanner(System.in);
//To get the users input
System.out.println("Change in Coins");
System.out.println("---------------");
System.out.println("Enter the amount less than $1.00, " +
"\nbut more than zero.");
System.out.print("\nEnter amount: ");
amt = keyboard.nextDouble();
//Loop for incorrect input
while ( amt < 0 || amt > 1.00 )
{
System.out.println("Please enter the amount less than $1.00,"
+ "\nbut more than zero.");
System.out.print("\nRe-enter amount: ");
amt = keyboard.nextDouble();
}
//
cents = (int)( amt * 100 + .1 );
quarter = cents/25;
cents %= 25;
dime = cents/10;
cents %= 10;
nickle = cents/5;
cents %= 5;
penny = cents;
// ----------------------------------------------------------
if (quarter > 1)
{
System.out.print("\nYou will need " + quarter + " quarters, ");
}
else if (quarter == 1)
{
System.out.print("\nYou will need " + quarter + " quarter ,");
}
else
{
System.out.print("\nYou will need no quarters, ");
}
// ----------------------------------------------------------
if (dime > 1)
{
System.out.print(dime + " dimes, ");
}
else if (dime == 1)
{
System.out.print(dime + " dime, ");
}
else
{
System.out.print("no dimes, ");
}
// ----------------------------------------------------------
if (nickle > 1)
{
System.out.print(nickle + " nickles, ");
}
else if (nickle == 1)
{
System.out.print(nickle + " nickle, ");
}
else
{
System.out.print("no nickles, ");
}
// ----------------------------------------------------------
if (penny > 1)
{
System.out.print("and " + penny + " pennies.");
}
else if (quarter == 1)
{
System.out.print("and " + penny + " penny.");
}
else
{
System.out.print("and no pennies.");
}
}
}
Ah, the joys of cut and paste :-)
if (penny > 1)
{
System.out.print("and " + penny + " pennies.");
}
else if (quarter == 1) // <<<<< LOOK HERE !!!
{
System.out.print("and " + penny + " penny.");
}
else
{
System.out.print("and no pennies.");
}
That should be penny, not quarter.
And, in fact, it actually does work for .26 (despite your assertion) since quarter is set to 1, the same as penny. In fact it'll work for any value where the number of quarters equals the number of pennies (.26, .52, .78), but only by accident.
As an aside, one other thing you may want to think about is refactoring all that repeated code with something like:
import java.util.Scanner;
public class Test
{
static double getAmount(Scanner keyboard) {
System.out.println("Enter the amount between zero and $1.00.");
System.out.print("\nEnter amount: ");
return keyboard.nextDouble();
}
static String mkeTxt (int val, String prefix, String singular, String plural) {
if (val == 0)
return prefix + "no " + plural;
if (val == 1)
return prefix + "1 " + singular;
return prefix + val + " " + plural;
}
public static void main(String[] args)
{
double amt;
int cents, quarter, dime, nickle, penny;
Scanner keyboard = new Scanner(System.in);
System.out.println("Change in Coins");
System.out.println("---------------");
amt = getAmount(keyboard);
while ( amt < 0 || amt > 1.00 )
amt = getAmount(keyboard);
cents = (int)( amt * 100 + .1 );
quarter = cents/25;
cents %= 25;
dime = cents/10;
cents %= 10;
nickle = cents/5;
cents %= 5;
penny = cents;
System.out.print("\nYou will need ");
System.out.print(mkeTxt(quarter,"", "quarter", "quarters"));
System.out.print(mkeTxt(dime,", ", "dime", "dimes"));
System.out.print(mkeTxt(nickle,", ", "nickle", "nickles"));
System.out.print(mkeTxt(penny," and ", "penny", "pennies"));
System.out.println(".");
}
}
The use of a function to output the prompt and accept input makes the user input code a little easier to maintain as you only need to change interaction in one place.
The real saver is the mkTxt() function to give you a string that auto-magically adjusts to the quantity of coins. It gets rid of that voluminous group of if/then/else blocks in main(), aiding readability somewhat.
If you ever find yourself doing a similar thing many times but with different values, that positively cries out to be changed into a function or loop of some description.
You just have a simple typo!
Change:
else if (quarter == 1){
System.out.print("and " + penny + " penny.");
} else {
System.out.print("and no pennies.");
}
To,
else if (penny == 1){
System.out.print("and " + penny + " penny.");
} else {
System.out.print("and no pennies.");
}

Categories

Resources