Output after multiplication shows weird characters, JAVA - java

Hello fellow programmers.
Maybe it's a trivial question, yet I cant figure out solution, neither I can find any clue how to solve this. If its double post I am really sorry.
Here's the code: !! Don't forget to import your "java.util.Scanner" !!
double id[]=new double[4];
double price[]=new double[4];
String productName[]=new String[4];
id[0]=10001;
id[1]=10002;
id[2]=10003;
id[3]=10004;
price[0]=20;
price[1]=25;
price[2]=40;
price[3]=10;
productName[0]="T-Shirt";
productName[1]="More expensive T-Shirt";
productName[2]="Jacket";
productName[3]="Singlet";
int x=0;
int z=0;
int options;
double discount;
System.out.println("Type in number of your choice between 1 to 4");
Scanner menu = new Scanner(System.in);
options = menu.nextInt();
do {
System.out.println("Chosen product n.: "+ options);
}while (x > 0);
switch (options){
case 1:
System.out.println("Id of product: " + id[0] + " " + "Product price:" +price[0] + " " + "Name of product: " + productName[0]);
break;
case 2:
System.out.println("Id of product: " + id[1] + " " + "Product price: " +price[1] + " " + "Name of product: " + productName[1]);
break;
case 3:
System.out.println("Id of product: " + id[2] + " " + "Product price: " +price[2] + " " + "Name of product: " + productName[2]);
break;
case 4:
System.out.println("Id of product: " + id[3] + " " + "Product price: " +price[3] + " " + "Name of product: " + productName[3]);
break;
}
discount=idPrice(price);
System.out.println("Price after discount: " + price);
}
static double idPrice(double finalPrice[])
{
return (finalPrice[1]/0.8);
}
}
Here's the output after typing number 1:
Type in number of your choice between 1 to 4
1
Chosen product n.: 1
Id of product: 10001.0 Product price: 20.0 Name of product: T-Shirt
Price after discount: [D#3590efa8
As you can see the Price after discount is a mess. It should output number 20(25*0.8 (Hell yea 20% discount)).
That's the first question.
Next thing is. How can I spicify which finalPrice will be multiplied?
Thank you all. Hope it will be helpfull to someone else also.

You're printing an array, not it's elements.
In order to do so, you have to iterate through them:
for (double d : prices) {
System.out.println(d);
}
Edit:
After reading the comments, you should print the discount variable:
System.out.println("Price after discount: " + discount);

System.out.println("Price after discount: " + price);
Print Array of double------------------^
You need to iterate to print the price array like below
for (double d : price) {
System.out.println("Price is "+d);
}

Use java.util.Arrays.toString(price) to get a readable result.
What you are getting now is the default toString method of the Object object:
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}

Related

How can I print something based on the result of a boolean method?

I have two methods
*`public boolean validateMarks() {
return (this.qualifyingMarks >= 65 && this.qualifyingMarks <= 100);
}
public boolean validateCourseId() {
return (this.courseId >= 1001 && this.courseId <= 1005);
}`*
validateMarks(): Used to validate qualifying exam marks - qualifying marks is in the range of 65 to 100(both inclusive)
validateCourseId(): Used to validate the course entered, based on the courseId - given in the table above
calculateCourseFee(): Used to calculate the course fee after applying the discount.
So when is less than 65 print print "not elegible, you've failed" and when the course is not valid "course is not correct, please try again with the correct number of the course"
and this is my calculateCourseFee method
***if(this.validateMarks()) {
this.courseFee = fee - (fee * discount);
System.out.println("****Course Allocation Details****" + "\n" +
"Student Name: " + this.getStudentName() + "\n" +
"Course Id: " + this.getCourseId() + "\n" +
"Qualifying Exam Marks: " + this.getQualifyingMarks() + "\n" +
"Student's Registration Id: " + this.getRegistrationId() + "\n" +
"Total Course Fee: " + this.getCourseFee() + "\n" +
"Hostel Required: " + hostel);
}else {
System.out.println("wrong for marks ");
}
if(this.validateCourseId()) {
this.courseFee = fee - (fee * discount);
System.out.println("****Course Allocation Details****" + "\n" +
"Student Name: " + this.getStudentName() + "\n" +
"Course Id: " + this.getCourseId() + "\n" +
"Qualifying Exam Marks: " + this.getQualifyingMarks() + "\n" +
"Student's Registration Id: " + this.getRegistrationId() + "\n" +
"Total Course Fee: " + this.getCourseFee() + "\n" +
"Hostel Required: " + hostel);
}else {
System.out.println("Wroog for course");
}
***
I make two different ifs for the two requirements, but everytime I run it, it prints the else statement to, even if marks is greather than 65... am I missing something?
Reviewing my code and tell me what am I missing or what am I doing wrong
The portion of the code you have shown here seems to be working as expected.
public class Driver {
public static void main(String args[]) {
Eligible e1 = new Eligible();
e1.calculateCourseFee();
}
}
class Eligible{
int qualifyingMarks = 66;
int courseId = 1002;
public boolean validateMarks() {
return (this.qualifyingMarks >= 65 && this.qualifyingMarks <= 100);
}
public boolean validateCourseId() {
return (this.courseId >= 1001 && this.courseId <= 1005);
}
public void calculateCourseFee(){
if(this.validateMarks()) {
System.out.println("works for marks");
}else {
System.out.println("wrong for marks ");
}
if(this.validateCourseId()) {
System.out.println("works for course");
}else {
System.out.println("Wroog for course");
}
}
}
output:
works for marks
works for course
Maybe the issues is with how you set the values for the qualifyingMarks and courseId variables?
I wish I could give you a like or thumbs up, I finally did it, thanks to all of your answers you gave me, and I just combined the two ifs into one. here's the code:
if(this.validateCourseId() && this.validateMarks()) {
this.courseFee = fee - (fee * discount);
System.out.println("****Course Allocation Details****" + "\n" +
"Student Name: " + this.getStudentName() + "\n" +
"Course Id: " + this.getCourseId() + "\n" +
"Qualifying Exam Marks: " + this.getQualifyingMarks() + "\n" +
"Student's Registration Id: " + this.getRegistrationId() + "\n" +
"Total Course Fee: " + this.getCourseFee() + "\n" +
"Hostel Required: " + hostel);
}else if(!this.validateCourseId()) {
System.out.println("Wrong course");
}
else if(!this.validateMarks()) {
System.out.println("You've failed");
}
Thanks everyone!!
maybe qualifyingMarks is zero or another value, print qualifyingMarks in method "validateMarks",u will get the reason of your problem.

Need to be pointed in the right direction with my Loops code

newbie at Java here. My professor returned my file with this comment
"3) The program does not implement the new loop correctly. The purpose of the loop was to allow the user to enter in their four numbers and do the math. The program should then ask the user if they want to continue, If they do, the program should allow the entry of four more numbers. The should continue until the user specifically says no they want to stop.
"
I am confused about how to ask the user if they wanted to continue then allow re entry of four more numbers again.
I'm having issues on entering the proper error message as well.
import java.util.Scanner;
public class Loops {
public static void main(String[] args) {
// 1. Declare two integer variables and two double variables
int iNumber;
int iNumber2;
double iDecimal;
double iDecimal2;
int count;
char yesNo = 'y'; // When a char variable is declared, the value needs to be a char not a string. Therefore, it needs a single quote instead of a double quote.
// 2. Instantiate a Scanner object
Scanner input = new Scanner(System.in);
// 3. Place the entry of the number into a loop that requires the user to enter the values at least one time.
//int i = 1;
// NOTE – Steps 4 through 8 are EXACTLY the same as the CE-Decision exercise. You may reuse that code if you would like.
// 4. Using print, display two lines that allows the user to enter in the two integer values on the same line as the prompt.
System.out.print("Input integer value 1: ");
iNumber = input.nextInt();
System.out.print("Input integer value 2: ");
iNumber2 = input.nextInt();
// 5. Using print, display two lines that allows the user to enter in the two double values on the same line as the prompt.
System.out.print("Input double value 1: ");
iDecimal = input.nextDouble();
System.out.print("Input double value 2: ");
iDecimal2 = input.nextDouble();
// 6. Using multiple printf statements, display the result of adding, subtracting, multiplying, dividing and moding the two integer values.
if (iNumber > iNumber2)
{
System.out.println("\nNumber 1 is greater than Number 2: ");
//+ instead of , for Printlns. , for printf. To add, use parenthesis.
System.out.println("\nInput integer value 1: "+ iNumber);
System.out.println("Input integer value 2: "+ iNumber2);
System.out.println("Input double value 1: "+ iDecimal);
System.out.println("Input double value 2: "+ iDecimal2);
System.out.println("\nInteger output: ");
System.out.printf("%s%d%s%d%s%d%n", "Adding ", iNumber, " and ", iNumber2, " = ", iNumber + iNumber2);
System.out.printf("%s%d%s%d%s%d%n", "Subtracting ", iNumber, " and ", iNumber2, " = ", iNumber - iNumber2);
System.out.printf("%s%d%s%d%s%d%n", "Multiplying ", iNumber, " and ", iNumber2, " = ", iNumber * iNumber2);
System.out.printf("%s%d%s%d%s%d%n", "Dividing ", iNumber, " and ", iNumber2, " = ", iNumber / iNumber2);
System.out.printf("%s%d%s%d%s%d%n", "Moding ", iNumber, " and ", iNumber2, " = ", iNumber % iNumber2);
System.out.println("\nDouble output: ");
System.out.printf("%s%.2f%s%.2f%s%.2f%n", "Adding ", iDecimal, " and ", iDecimal2, " = ", iDecimal + iDecimal2);
System.out.printf("%s%.2f%s%.2f%s%.2f%n", "Subtracting ", iDecimal, " and ", iDecimal2, " = ", iDecimal - iDecimal2);
System.out.printf("%s%.2f%s%.2f%s%.2f%n", "Multiplying ", iDecimal, " and ", iDecimal2, " = ", iDecimal * iDecimal2);
System.out.printf("%s%.2f%s%.2f%s%.2f%n", "Dividing ", iDecimal, " and ", iDecimal2, " = ", iDecimal / iDecimal2);
}
else if (iNumber < iNumber2)
{
System.out.println("\nNumber 2 is greater than Number 1:");
//+ instead of , for Printlns. , for printf. To add, use parenthesis.
System.out.println("\nInput integer value 1: " + iNumber);
System.out.println("Input integer value 2: " + iNumber2);
System.out.println("Input double value 1: " + iDecimal);
System.out.println("Input double value 2: " + iDecimal2);
System.out.println("\nInteger output: ");
System.out.printf("%s%d%s%d%s%d%n", "Adding ", iNumber, " and ", iNumber2, " = ", iNumber + iNumber2);
System.out.printf("%s%d%s%d%s%d%n", "Subtracting ", iNumber, " and ", iNumber2, " = ", iNumber - iNumber2);
System.out.printf("%s%d%s%d%s%d%n", "Multiplying ", iNumber, " and ", iNumber2, " = ", iNumber * iNumber2);
System.out.printf("%s%d%s%d%s%d%n", "Division ", iNumber, " and ", iNumber2, " = ", iNumber / iNumber2);
System.out.printf("%s%d%s%d%s%d%n\n", "Moding ", iNumber, " and ", iNumber2, " = ", iNumber % iNumber2);
System.out.println("Double output: ");
System.out.printf("%s%.2f%s%.2f%s%.2f%n", "Adding ", iDecimal, " and ", iDecimal2, " = ", iDecimal + iDecimal2);
System.out.printf("%s%.2f%s%.2f%s%.2f%n", "Subtracting ", iDecimal, " and ", iDecimal2, " = ", iDecimal - iDecimal2);
System.out.printf("%s%.2f%s%.2f%s%.2f%n", "Multiplying ", iDecimal, " and ", iDecimal2, " = ", iDecimal * iDecimal2);
System.out.printf("%s%.2f%s%.2f%s%.2f%n", "Dividing ", iDecimal, " and ", iDecimal2, " = ", iDecimal / iDecimal2);
}
else if (iNumber2 == iNumber)
{
System.out.println("\nBoth numbers are equal");
//+ instead of , for Printlns. , for printf. To add, use parenthesis.
System.out.println("\nInput integer value 1: "+ iNumber);
System.out.println("Input integer value 2: "+ iNumber2);
System.out.println("Input double value 1: "+ iDecimal);
System.out.println("Input double value 2: "+ iDecimal2);
System.out.println("\nInteger output: ");
System.out.printf("%s%d%s%d%s%d%n", "Adding ", iNumber, " and ", iNumber2, " = ", iNumber + iNumber2);
System.out.printf("%s%d%s%d%s%d%n", "Subtracting ", iNumber2, " and ", iNumber, " = ", iNumber2 - iNumber);
System.out.printf("%s%d%s%d%s%d%n", "Multiplying ", iNumber, " and ", iNumber2, " = ", iNumber * iNumber2);
System.out.printf("%s%d%s%d%s%d%n", "Division ", iNumber, " and ", iNumber2, " = ", iNumber / iNumber2);
System.out.printf("%s%d%s%d%s%d%n\n", "Moding ", iNumber, " and ", iNumber2, " = ", iNumber % iNumber2);
System.out.println("Double output: ");
System.out.printf("%s%.2f%s%.2f%s%.2f%n", "Adding ", iDecimal, " and ", iDecimal2, " = ", iDecimal + iDecimal2);
System.out.printf("%s%.2f%s%.2f%s%.2f%n", "Subtracting ", iDecimal2, " and ", iDecimal, " = ", iDecimal2 - iDecimal);
System.out.printf("%s%.2f%s%.2f%s%.2f%n", "Multiplying ", iDecimal, " and ", iDecimal2, " = ", iDecimal * iDecimal2);
System.out.printf("%s%.2f%s%.2f%s%.2f%n", "Dividing ", iDecimal, " and ", iDecimal2, " = ", iDecimal / iDecimal2);
}
else if (iNumber2 == 0)
{
System.out.println("\nNumber 2 equals 0:");
//+ instead of , for Printlns. , for printf. To add, use parenthesis.
System.out.println("\nInput integer value 1: "+ iNumber);
System.out.println("Input integer value 2: "+ iNumber2);
System.out.println("Input double value 1: "+ iDecimal);
System.out.println("Input double value 2: "+ iDecimal2);
System.out.println("\nInteger output: ");
System.out.printf("%s%d%s%d%s%d%n", "Adding ", iNumber, " and ", iNumber2, " = ", iNumber + iNumber2);
System.out.printf("%s%d%s%d%n", "Subtracting ", iNumber, " = ", iNumber - iNumber2);
System.out.printf("%s%d%s%d%n", "Multiplying ", iNumber, " = ", iNumber * iNumber2);
if (iNumber2 == 0 || iDecimal2 == 0){
System.out.println("Error: You cannot divide and mod by zero!!!");
}
else {
System.out.printf("%s%d%s%d%s%d%n", "Division ", iNumber, " and ", iNumber2, " = ", iNumber / iNumber2);
System.out.printf("%s%d%s%d%s%d%n\n", "Moding ", iNumber, " and ", iNumber2, " = ", iNumber % iNumber2);
}
System.out.println("Double output: ");
System.out.printf("%s%.2f%s%.2f%s%.2f%n", "Adding ", iDecimal, " and ", iDecimal2, " = ", iDecimal + iDecimal2);
System.out.printf("%s%.2f%s%.2f%n", "Subtracting ", iDecimal, " = ", iDecimal - iDecimal2);
System.out.printf("%s%.2f%s%.2f%n", "Squaring ", iDecimal, " = ", iDecimal * iDecimal2);
System.out.printf("%s%.2f%s%.2f%s%.2f%n", "Dividing ", iDecimal, " and ", iDecimal2, " = ", iDecimal / iDecimal2);
}
// a. Test the two numbers, subtract the smaller number from the larger number. Display the output with the numbers in the proper order. If the numbers are equal, display a message that subtracting a number from itself gives you zero.
// b. If the two numbers are equal, the program should display the message as “Squaring” a number instead of multiplying two numbers.
// c. If the second number is zero, the program should display an error message saying that you cannot divide or mod by zero.
// 7. Using multiple printf statements, display the result of adding, subtracting, multiplying, and dividing the two double values.
// a. Test the two numbers, subtract the smaller number from the larger number. Display the output with the numbers in the proper order. If the numbers are equal, display a message that subtracting a number from itself gives you zero.
// b. If the two numbers are equal, the program should display the message as “Squaring” a number instead of multiplying two numbers.
// c. If the second number is zero, the program should display an error message saying that you cannot divide by zero.
// 8. Make sure that there is a title before each of the two outputs and there are blank lines between the input section and the two output sections.
// 9. Ask the user if they wish to enter in another set of numbers.
count = input.nextInt();
do {
System.out.println("Do you wish to enter another set of numbers?: (y/n)");
yesNo = input.next().charAt(0);
// a. The only valid entries are : y, Y, n or N (single letters)
if (yesNo != 'Y' && yesNo != 'y' && yesNo != 'N' && yesNo != 'n') {
System.out.println("Error = you must enter Y or N. Please retry. "); // Error message should be inside the if statement block or else the error message would always appear.
}
} while (yesNo != 'Y' && yesNo != 'y' && yesNo != 'N' && yesNo != 'n');
}
}
System.out.print("Do you wish to enter another set of numbers?: (y/n)");
String answer = scan.nextLine();
// b. Use the Java construct input.next().charAt(0) to get the character value
// c. Place the input into a loop that tests the entry for validity
// i. If the entry is valid, end the loop
// ii. If the entry is invalid, display an error message and ask the user to reenter their response
// 10. If the user indicated that they wish to enter new values, continue the loop and allow the user to reenter a new set of values.
// a. The user should be allowed to reenter values as many times as they like. Only the entry of ‘n’ or ‘N’ should cause the loop to end.
// 11. If the user indicated that they do not wish to enter any more values, end the loop and display a thank you/goodbye message.
// 12. Comment your code.
//3) The program does not implement the new loop correctly. The purpose of the loop was to allow the user to enter in their four numbers and do the math.
// The program should then ask the user if they want to continue, If they do, the program should allow the entry of four more numbers.
// The should continue until the user specifically says no they want to stop.
enter image description hereenter image description here
This question is barely readable. You should try writing neater questions so more people will be able to assist you. Give a short portion of the code where the problem lies and ask "why is this incorrect?".
As for your question, I think you should have another while loop, which will include the logic you implemented. Something like while(yesNo == 'Y' || yesNo == 'y'). So while this is true, you read 4 inputs from the user. To me it seems like you don't even care if the user entered 'n' or 'y', your do-while loop merely checks input validity.

Static variables are getting initialized again when ever function gets called - Java

I want to have the userScore and computerScore updated every time the user inputs 'y' to play again, but instead, the scores get initialized from 0.
I have made an ArrayList to show the results every time user plays. Does Anyone have any suggestion on a better implementation for this?
Please ignore violation of the DRY principal :)
import java.util.*;
import java.io.*;
class OddsAndEvens{
static int UserScore = 0;
static int computerScore = 0;
static ArrayList<Integer> UserScoreArray = new ArrayList<Integer>();
static ArrayList<Integer> computerScoreArray = new ArrayList<Integer>();
public static void main(String args[]){
BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
String name = "", choice="";
System.out.println("______________________________________________________________________________");
System.out.println();
System.out.println("Let's play a game called Odds and Evens");
System.out.print("What is your name? ");
try{
name = console.readLine();
} catch(Exception e){
System.out.println("Error while name input: " + e);
}
System.out.print("Hi " + name + ", which do you choose? (O)dds or (E)vens? ");
try{
choice = console.readLine().toLowerCase();
} catch(Exception e){
System.out.println("Error while Choosing Odd or Even: " + e);
}
if(choice.startsWith("o")){
System.out.println(name + " chose ODDS, the Computer will be EVENS");
} else if(choice.startsWith("e")){
System.out.println(name + " chose EVENS, the Computer will be ODDS");
} else{
System.out.println("Enter a valid choice "+ name + "..Either O(o) or E(e)");
}
System.out.println("______________________________________________________________________________");
System.out.println();
while(play(console, name, choice, UserScore, computerScore).startsWith("y")){
play(console, name, choice, UserScore, computerScore);
}
}
public static String play(BufferedReader console, String name, String choice, int UserScore, int computerScore){
int numberOfFingers = 0;
UserScoreArray.add(0);
computerScoreArray.add(0);
System.out.println("How many 'fingers' do you put out?(You can only put out 5 fingers)");
try{
numberOfFingers = Integer.parseInt(console.readLine());
} catch(Exception e1){
System.out.println("Error while, taking number of fingers: " + e1);
}
if(numberOfFingers > 5){
System.out.println("You cannot put out more than 5 fingers " + name);
System.out.println("Let's try again!");
play(console, name, choice, UserScore, computerScore);
}
Random rand = new Random();
int computerFingers = rand.nextInt(6);
System.out.println("The computer played: " + computerFingers);
int sum = numberOfFingers + computerFingers;
System.out.println("sum = " + numberOfFingers + "+" + computerFingers);
if(sum%2 == 0){
System.out.println(sum + " is. . . . Even");
if(choice.startsWith("e")){
System.out.println("The Winner is " + name);
UserScore++;
UserScoreArray.add(UserScore);
System.out.println(name + "'s score: " + UserScoreArray.get(UserScoreArray.size() - 1));
System.out.println("Computer's score: " + computerScoreArray.get(computerScoreArray.size() - 1));
} else{
System.out.println("The Winner is Computer");
computerScore++;
computerScoreArray.add(computerScore);
System.out.println(name + "'s score: " + UserScoreArray.get(UserScoreArray.size() - 1));
System.out.println("Computer's score: " + computerScoreArray.get(computerScoreArray.size() - 1));
}
} else{
System.out.println(sum + " is. . . . Odd");
if(choice.startsWith("o")){
System.out.println("The Winner is " + name);
UserScore++;
UserScoreArray.add(UserScore);
System.out.println(name + "'s score: " + UserScoreArray.get(UserScoreArray.size() - 1));
System.out.println("Computer's score: " + computerScoreArray.get(computerScoreArray.size() - 1));
} else{
System.out.println("The Winner is Computer");
computerScore++;
computerScoreArray.add(computerScore);
System.out.println(name + "'s score: " + UserScoreArray.get(UserScoreArray.size() - 1));
System.out.println("Computer's score: " + computerScoreArray.get(computerScoreArray.size() - 1));
}
}
System.out.println("______________________________________________________________________________");
System.out.println(name + "'s Array List contents: " + "\n" + UserScoreArray);
System.out.println("______________________________________________________________________________");
System.out.println("Computer's Array List contents: " + "\n" + computerScoreArray);
System.out.println("______________________________________________________________________________");
System.out.println();
System.out.println("How does the Score look like " + name + ", Want to Play again?(y or n)");
String playAgain = "";
try{
playAgain = console.readLine().toLowerCase();
} catch(Exception e3){
System.out.println("Error in function for playAgain: " + e3);
}
if(playAgain.startsWith("y")){
System.out.println("Starting another game-");
return playAgain;
}
else{
System.out.println("Thank you for playing, see you soon..");
System.exit(0);
}
return "p";
}
}
Please note that static variable is seen in all instances of a class. You don't need to pass it as a parameter to a method.
If you pass it as a parameter, please note the parameter name. If your variable is called "score" and your parameter is called "score" as well, what you are changing (with "score++" or other "score" manipulation) is no longer the "score" class variable, but a method parameter, and changes done to it will no longer be visible when you exit the method. This is called shadowing.
I suggest (for similar questions) a sister-site to SO - one that deals with code reviews. https://codereview.stackexchange.com/ You may learn more there, since here we tend to focus on specific problems.
Try this code , it will works, you need to intialies index 0 of 2 arrays in the beginining of main method
Here is the code:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Random;
class OddsAndEvens{
static int UserScore = 0;
static int computerScore = 0;
static ArrayList<Integer> UserScoreArray = new ArrayList<Integer>();
static ArrayList<Integer> computerScoreArray = new ArrayList<Integer>();
public static void main(String args[]){
UserScoreArray.add(0);
computerScoreArray.add(0);
BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
String name = "", choice="";
System.out.println("______________________________________________________________________________");
System.out.println();
System.out.println("Let's play a game called Odds and Evens");
System.out.print("What is your name? ");
try{
name = console.readLine();
} catch(Exception e){
System.out.println("Error while name input: " + e);
}
System.out.print("Hi " + name + ", which do you choose? (O)dds or (E)vens? ");
try{
choice = console.readLine().toLowerCase();
} catch(Exception e){
System.out.println("Error while Choosing Odd or Even: " + e);
}
if(choice.startsWith("o")){
System.out.println(name + " chose ODDS, the Computer will be EVENS");
} else if(choice.startsWith("e")){
System.out.println(name + " chose EVENS, the Computer will be ODDS");
} else{
System.out.println("Enter a valid choice "+ name + "..Either O(o) or E(e)");
}
System.out.println("______________________________________________________________________________");
System.out.println();
while(play(console, name, choice, UserScore, computerScore).startsWith("y")){
play(console, name, choice, UserScore, computerScore);
}
}
public static String play(BufferedReader console, String name, String choice, int UserScore, int computerScore){
int numberOfFingers = 0;
System.out.println("How many 'fingers' do you put out?(You can only put out 5 fingers)");
try{
numberOfFingers = Integer.parseInt(console.readLine());
} catch(Exception e1){
System.out.println("Error while, taking number of fingers: " + e1);
}
if(numberOfFingers > 5){
System.out.println("You cannot put out more than 5 fingers " + name);
System.out.println("Let's try again!");
play(console, name, choice, UserScore, computerScore);
}
Random rand = new Random();
int computerFingers = rand.nextInt(6);
System.out.println("The computer played: " + computerFingers);
int sum = numberOfFingers + computerFingers;
System.out.println("sum = " + numberOfFingers + "+" + computerFingers);
if(sum%2 == 0){
System.out.println(sum + " is. . . . Even");
if(choice.startsWith("e")){
System.out.println("The Winner is " + name);
UserScore++;
UserScoreArray.add(UserScore + UserScoreArray.get(UserScoreArray.size() - 1));
System.out.println(name + "'s score: " + UserScoreArray.get(UserScoreArray.size() - 1));
System.out.println("Computer's score: " + computerScoreArray.get(computerScoreArray.size() - 1));
} else{
System.out.println("The Winner is Computer");
computerScore++;
computerScoreArray.add(computerScore + computerScoreArray.get(computerScoreArray.size() - 1));
System.out.println(name + "'s score: " + UserScoreArray.get(UserScoreArray.size() - 1));
System.out.println("Computer's score: " + computerScoreArray.get(computerScoreArray.size() - 1));
}
} else{
System.out.println(sum + " is. . . . Odd");
if(choice.startsWith("o")){
System.out.println("The Winner is " + name);
UserScore++;
UserScoreArray.add(UserScore + UserScoreArray.get(UserScoreArray.size() - 1));
System.out.println(name + "'s score: " + UserScoreArray.get(UserScoreArray.size() - 1));
System.out.println("Computer's score: " + computerScoreArray.get(computerScoreArray.size() - 1));
} else{
System.out.println("The Winner is Computer");
computerScore++;
computerScoreArray.add(computerScore + computerScoreArray.get(computerScoreArray.size() - 1));
System.out.println(name + "'s score: " + UserScoreArray.get(UserScoreArray.size() - 1));
System.out.println("Computer's score: " + computerScoreArray.get(computerScoreArray.size() - 1));
}
}
System.out.println("______________________________________________________________________________");
System.out.println(name + "'s Array List contents: " + "\n" + UserScoreArray);
System.out.println("______________________________________________________________________________");
System.out.println("Computer's Array List contents: " + "\n" + computerScoreArray);
System.out.println("______________________________________________________________________________");
System.out.println();
System.out.println("How does the Score look like " + name + ", Want to Play again?(y or n)");
String playAgain = "";
try{
playAgain = console.readLine().toLowerCase();
} catch(Exception e3){
System.out.println("Error in function for playAgain: " + e3);
}
if(playAgain.startsWith("y")){
System.out.println("Starting another game-");
return playAgain;
}
else{
System.out.println("Thank you for playing, see you soon..");
System.exit(0);
}
return "p";
}
}
This happens because of your method parameters.You have two unwanted
method parameters in your play method.just remove UserScore &
computerScore parameters from your play method and your code should work well.
In your class, UserScore & computerScore fields are static. so no
need to pass those field values to another static method within the
same class.In your code those parameters just hide the actual static
fields.when you print the value of UserScore or computerScore in play
method, java just print the value of the local method parameters
instead of static fields.

Variable being calculated in one method isn't going to another

I'm taking a Java class and I've been working on this program that is to calculate credit card balance based on information input through a GUI. In my output Finance Charge, New Balance, and New Payment Due are all coming out as 0. I've tried adding 5 to pinpoint where I messed up and it seems that "balance" isn't being referenced correctly when calculating newBalance. I assume that Finance Charge also has the same issue but fixing balance will help me fix that as well.
//calculates balance
public float calculateBalance()
{
balance = previousBalance + currentPurchases - payments - creditsReturns + lateFees+ 5;
return balance;
}
//sets finance charge
public void setFinanceCharge(float financeCharge)
{
double periodicRate;
periodicRate = .12/12;
float d = (float)periodicRate;
financeCharge = balance * d;
}
//gets finance charge
public float getFinanceCharge()
{
return financeCharge;
}
//Method to calculate new balance
public float calculateNewBalance()
{
//calculate the new balance
newBalance = balance+financeCharge+5;
return newBalance;
}
//setes new payment due
public void setpaymentDue(double newPayment)
{
newPayment = newBalance * .10;
this.paymentDue = (float)newPayment;
}
//gets new payment due
public float getpaymentDue()
{
return paymentDue;
}
//method to display results
public void displayOutput()
{
if (overCreditLimit == 0)
{
JOptionPane.showMessageDialog(null,
"The Customer number is: " + customerNumber + "\n" +
"The Customer name is: " + customerName + "\n" +
"The Credit Limit is: " + creditLimit + "\n" +
"The Previous Balance is: " + previousBalance + "\n" +
"The Current Purchases is: " + currentPurchases + "\n" +
"The Payments is: " + payments + "\n" +
"The Credits/Returns is: " + creditsReturns + "\n" +
"The Late Fees is: " + lateFees + "\n" +
"The Finance Charge is: " + financeCharge + "\n" +
"The New Balance is: " + newBalance + "\n" +
"The New Payment Due is: " + paymentDue + "\n");
}
else
{
overCreditAmount = newBalance - creditLimit - 25;
JOptionPane.showMessageDialog(null, "You are " + overCreditAmount + " dollars over your credit limit,"
+ " a $25 fee has been charged to your new balance");
JOptionPane.showMessageDialog(null,
"The Customer number is: " + customerNumber + "\n" +
"The Customer name is: " + customerName + "\n" +
"The Credit Limit is: " + creditLimit + "\n" +
"The Previous Balance is: " + previousBalance + "\n" +
"The Current Purchases is: " + currentPurchases + "\n" +
"The Payments is: " + payments + "\n" +
"The Credits/Returns is: " + creditsReturns + "\n" +
"The Late Fees is: " + lateFees + "\n" +
"The Finance Charge is: " + financeCharge + "\n" +
"The Amount over Credit Limit is: " + overCreditAmount + "\n" +
"The New Balance is: " + newBalance + "\n" +
"The New Payment Due is: " + paymentDue + "\n");
}
}
One way I see to solve the issue is to run methods within the calculateNewMethod method. For example.
public float calculateNewBalance () {
newBalance = calculateBalance() + getFinanceCharge();
return newBalance;
}
I would also suggest avoiding code where you modify private class varibles and return them within the same method, it make more sense to have one method which modifies it, and one to return the varible.

How can i make the user make another choice when choosing a movie?

I am writing a program where the user has a choice of 7 movies to buy. The user can choose as many movies up to 7 and than will add up the prices of the movies and than print the total price. I must use arrays in my program. My problem is when the user has already chosen their first movie they are given a choice if they want to buy another movie. I'm confused on how I should code my program by giving the user another choice to choose more than 1 movie. I need help on how I should fix my problem because when I run my program I it won't let me have the choice to choose another movie. Here my code:
import java.util.Scanner;
public class MovieHits {
public static void main(String[] args)
{
//Declare Variables
Scanner keyboard = new Scanner(System.in);
int userChoice = 0;
String choice;
int priceTotal = 0;
int [] number = {1, 2, 3, 4, 5, 6, 7};
String [] Movie = new String [7];
int [] movieCost ={ 5, 4, 3, 6, 4, 4, 3};
Movie [0] = "Iron Man";
Movie [1] = "Transformers";
Movie [2] = "Godzilla";
Movie [3] = "Fast and Furious";
Movie [4] = "Captain America";
Movie [5] = "X Men";
Movie [6] = "Rio";
//Welcome the user
System.out.println("Hello, Welcome to TC Movies OnDemand.");
//Display the listed movies so the user can know with movie they want to watch
System.out.println("\nChoose which movie you want to watch: ");
for ( int index = 0; index < 7; index = index + 1 )
{
System.out.println(number[index]+ ": " + Movie[index]);
System.out.println("\t" + "Price: $" + movieCost[index]);
}
//Switch Statement to give user a menu to choose a movie
userChoice = keyboard.nextInt();
switch (userChoice)
{
case 1:
System.out.println("The movie you have chosen is " + Movie[0] + "\nPrice is: " + "$" + movieCost[0]);
break;
case 2:
System.out.println("The movie you have chosen is " + Movie[1] + "\nPrice is: " + "$" + movieCost[1]);
break;
case 3:
System.out.println("The movie you have chosen is " + Movie[2] + "\nPrice is: " + "$" + movieCost[2]);
break;
case 4:
System.out.println("The movie you have chosen is " + Movie[3] + "\nPrice is: " + "$" + movieCost[3]);
break;
case 5:
System.out.println("The movie you have chosen is " + Movie[4] + "\nPrice is: " + "$" + movieCost[4]);
break;
case 6:
System.out.println("The movie you have chosen is " + Movie[5] + "\nPrice is: " + "$" + movieCost[5]);
break;
case 7:
System.out.println("The movie you have chosen is " + Movie[6] + "\nPrice is: " + "$" + movieCost[6]);
break;
default:
System.out.println("I'm Sorry you did not chose a movie.");
break;
}
//Tell the user if they want to get another movie
System.out.println("Do you want to add another movie. Enter Yes or No");
choice = keyboard.next();
do
{
priceTotal = movieCost[userChoice];
}
while (choice.equalsIgnoreCase("Yes"));
{
}
//Tell the user the total price
}
}
I would clean your code up like this:
String choice = "Yes"; //Set to yes by default.
//Welcome the user
System.out.println("Hello, Welcome to TC Movies OnDemand.");
while(choice.equalsIgnoreCase("Yes")){
//Display the listed movies so the user can know with movie they want to watch
System.out.println("\nChoose which movie you want to watch: ");
for ( int index = 0; index < 7; index = index + 1 ){
System.out.println(number[index]+ ": " + Movie[index]);
System.out.println("\t" + "Price: $" + movieCost[index]);
}
userChoice = keyboard.nextInt();
try{
System.out.println("The movie you have chosen is " + Movie[userChoice] + "\nPrice is: " + "$" + movieCost[userChoice]);
}catch(Exception e){
System.out.println("Sorry, you did not choose a movie.");
}
//Tell the user if they want to get another movie
System.out.println("Do you want to add another movie? Enter Yes or No.");
choice = keyboard.next();
}
This refactors your code, meaning you don't have to have to use a long switch statement for every single movie type you have.
We've used userChoice as the actual index to look for, and the try{}catch{} block means that we still can 'catch' invalid input if the user incorrectly enters a movie to watch.
I originally was using a do-while like you had, but that structure never works for me, so I swapped it for a straight-forward while loop that I'm more familiar with.
do {
//Switch Statement to give user a menu to choose a movie
System.out.println("Choose your movie number:");
userChoice = keyboard.nextInt();
switch (userChoice) {
case 1:
System.out.println("The movie you have chosen is " + Movie[0] + "\nPrice is: " + "$" + movieCost[0]);
break;
case 2:
System.out.println("The movie you have chosen is " + Movie[1] + "\nPrice is: " + "$" + movieCost[1]);
break;
case 3:
System.out.println("The movie you have chosen is " + Movie[2] + "\nPrice is: " + "$" + movieCost[2]);
break;
case 4:
System.out.println("The movie you have chosen is " + Movie[3] + "\nPrice is: " + "$" + movieCost[3]);
break;
case 5:
System.out.println("The movie you have chosen is " + Movie[4] + "\nPrice is: " + "$" + movieCost[4]);
break;
case 6:
System.out.println("The movie you have chosen is " + Movie[5] + "\nPrice is: " + "$" + movieCost[5]);
break;
case 7:
System.out.println("The movie you have chosen is " + Movie[6] + "\nPrice is: " + "$" + movieCost[6]);
break;
default:
System.out.println("I'm Sorry you did not chose a movie.");
break;
}
//Tell the user if they want to get another movie
System.out.println("Do you want to add another movie. Enter Yes or No");
choice = keyboard.next();
priceTotal = movieCost[userChoice];
} while (choice.equalsIgnoreCase("Yes"));
}
You should use the do-while loop as follows:
In the do block, put the code that you would like to happen
This should be everything between (and including) "Choose the movie" and retrieving user's choice for repetition.
This means that all of that code is guaranteed to occur once, and will occur again if while condition is met.
The code block for the while condition is above it, and thus is terminated with a semi-colon.
You used do-while loop in wrong place in wrong way.Change Your code to this :
do{
try{
userChoice = keyboard.nextInt();
} catch(Execption e){
System.out.Println("Error in input!");
}
switch (userChoice)
{
case 1:
System.out.println("The movie you have chosen is " + Movie[0] + "\nPrice is: " + "$" + movieCost[0]);
break;
case 2:
System.out.println("The movie you have chosen is " + Movie[1] + "\nPrice is: " + "$" + movieCost[1]);
break;
case 3:
System.out.println("The movie you have chosen is " + Movie[2] + "\nPrice is: " + "$" + movieCost[2]);
break;
case 4:
System.out.println("The movie you have chosen is " + Movie[3] + "\nPrice is: " + "$" + movieCost[3]);
break;
case 5:
System.out.println("The movie you have chosen is " + Movie[4] + "\nPrice is: " + "$" + movieCost[4]);
break;
case 6:
System.out.println("The movie you have chosen is " + Movie[5] + "\nPrice is: " + "$" + movieCost[5]);
break;
case 7:
System.out.println("The movie you have chosen is " + Movie[6] + "\nPrice is: " + "$" + movieCost[6]);
break;
default:
System.out.println("I'm Sorry you did not chose a movie.");
break;
}
//Tell the user if they want to get another movie
try{
System.out.println("Do you want to add another movie. Enter Yes or No");
choice = keyboard.nextLine();
} catch(Execption e){
System.out.Println("Error in input!");
}
priceTotal = movieCost[userChoice];
} while (choice.equalsIgnoreCase("Yes"));

Categories

Resources