converting from if-else to methods - java

Here is my current code:
import java.util.Scanner;//importing scanner
public class QuestionOne {
public static void main(String[] args) {
int numberofDays;//these two lines define variables
int sharePoints;
Scanner keyboard = new Scanner(System.in);//activating scanner
System.out.print("Number of days in the period: ");//asking question
numberofDays = keyboard.nextInt();//obtaining input by defining a variable as a keyboard input
System.out.print("Share points on the first day: ");//asking another question
sharePoints = keyboard.nextInt();//obtaining input by defining a variable as a keyboard input
while (numberofDays < 10 || numberofDays > 20)//while loop makes sure the conditions stay true
{
System.out.println("The number of days doesn’t meet the required criteria, enter it again");
System.out.print("Number of days in the period: ");
numberofDays = keyboard.nextInt();
//above three lines ask for number of days until a value that fits within specification is obtained
}
System.out.println("Day " + " Share Points");
System.out.println(1 + " " + sharePoints);
//above two lines print day and share points, as well as the first line of text (as it does not change)
for (int i = 2; i <= numberofDays; i++) {
if (numberofDays % 2 == 0)
if (i <= numberofDays / 2) {
sharePoints = sharePoints + 50;
System.out.println(i + " " + sharePoints);
} else {
sharePoints = sharePoints - 25;
System.out.println(i + " " + sharePoints);
} else {
if (i <= numberofDays / 2 + 1) {
sharePoints = sharePoints + 50;
System.out.println(i + " " + sharePoints);
} else {
sharePoints = sharePoints - 25;
System.out.println(i + " " + sharePoints);
// above nested if else statements essentially calculate and concatenate the variables to obtain an answer that is then printed and repeated until the number of days is reached (starting from day two)
}
}
}
}
}
This code compiles and works as I want, however, I no longer want it to be in this format. Instead, I would like for it to contain a method named DisplayStock; the input arguments I want for this method are the
number of days in the period and the share points on the first day. The method is used to increase the share points by 50 and decrease the share points by 25 on alternate days in the specified period. The method then
displays a table showing the days and the share points on those days. This method doesn’t return anything.
As for the main method, it will first ask the users to enter the number of days in the specified period and the share points on the first day (with input validation, the program should then call the DisplayStock method that outputs the table.
A sample output currently looks as such if the period is ll days and SharePoint are 550:
Day Share Points
1 550
2 600
3 575
4 625
5 600
6 650
7 625
8 675
9 650
10 700
11 675
So basically, what I am intending to do is convert the code from if-else statements over to methods to alleviate issues with readability and function. Any help would be appreciated! I will continue to work on this but I do not think I will be able to get as far as I intend.

you just want to break the code in to two methods or several
basic will be this:
public static void main(String[] args) {
int numberofDays;//these two lines define variables
int sharePoints;
Scanner keyboard = new Scanner(System.in);//activating scanner
System.out.print("Number of days in the period: ");//asking question
numberofDays = keyboard.nextInt();//obtaining input by defining a variable as a keyboard input
System.out.print("Share points on the first day: ");//asking another question
sharePoints = keyboard.nextInt();//obtaining input by defining a variable as a keyboard input
numberofDays = validator(numberofDays,keyboard); // Validates Keyboard input
//above two lines print day and share points, as well as the first line of text (as it does not change)
outPutTablePrinter(numberofDays,sharePoints);
}
private static void outPutTablePrinter(int numberOfDays,int sharePoints){
System.out.println("Day " + " Share Points");
System.out.println(1 + " " + sharePoints);
for (int i = 2; i <= numberOfDays; i++) {
if (numberOfDays % 2 == 0)
if (i <= numberOfDays / 2) {
sharePoints = sharePoints + 50;
System.out.println(i + " " + sharePoints);
} else {
sharePoints = sharePoints - 25;
System.out.println(i + " " + sharePoints);
} else {
if (i <= numberOfDays / 2 + 1) {
sharePoints = sharePoints + 50;
System.out.println(i + " " + sharePoints);
} else {
sharePoints = sharePoints - 25;
System.out.println(i + " " + sharePoints);
// above nested if else statements essentially calculate and concatenate the variables to obtain an answer that is then printed and repeated until the number of days is reached (starting from day two)
}
}
}
}
private static int validator(int numberOfDays,Scanner keyboard){
while (numberOfDays < 10 || numberOfDays > 20)//while loop makes sure the conditions stay true
{
System.out.println("The number of days doesn’t meet the required criteria, enter it again");
System.out.print("Number of days in the period: ");
numberOfDays = keyboard.nextInt();
}
return numberOfDays;
}

I refactored your code. First, I would prefer printf and your logic can be greatly simplified by incrementing by two in your loop. You do need to check if there is an index + 1 for it to work correctly with odd number of days, but you can do
System.out.printf("Day\tShare Points%n");
for (int i = 0; i < numberofDays; i += 2) {
System.out.printf("%-3d\t%d%n", i + 1, sharePoints);
sharePoints += 50;
if (i + 1 < numberofDays) {
System.out.printf("%-3d\t%d%n", i + 2, sharePoints);
sharePoints -= 25;
}
}
And I get
Day Share Points
1 550
2 600
3 575
4 625
5 600
6 650
7 625
8 675
9 650
10 700
11 675

Following code be used:
import java.util.Scanner;//importing scanner
public class QuestionOne{
static int numberofDays;//these two lines define variables
static int sharePoints;
public static void main(String[]args){
Scanner keyboard = new Scanner (System.in);//activating scanner
System.out.print("Number of days in the period: ");//asking question
numberofDays = keyboard.nextInt();//obtaining input by defining a variable as a keyboard input
System.out.print("Share points on the first day: ");//asking another question
sharePoints = keyboard.nextInt();//obtaining input by defining a variable as a keyboard input
while (numberofDays < 10 || numberofDays > 20)//while loop makes sure the conditions stay true
{
System.out.println("The number of days doesn’t meet the required criteria, enter it again");
System.out.print("Number of days in the period: ");
numberofDays = keyboard.nextInt();
//above three lines ask for number of days until a value that fits within specification is obtained
}
DisplayStock ();
}
public static void DisplayStock (){
System.out.println("Day " + " Share Points");
System.out.println(1 + " " + sharePoints);
//above two lines print day and share points, as well as the first line of text (as it does not change)
for(int i = 2; i <= numberofDays; i++)
{
if(numberofDays % 2 == 0)
if(i <= numberofDays/2)
{
sharePoints = sharePoints + 50;
System.out.println(i + " " + sharePoints);
}
else
{
sharePoints = sharePoints - 25;
System.out.println(i + " " + sharePoints);
}
else
{
if(i <= numberofDays/2 + 1)
{
sharePoints = sharePoints + 50;
System.out.println(i + " " + sharePoints);
}
else
{
sharePoints = sharePoints - 25;
System.out.println(i + " " + sharePoints);
//above nested if else statements essentially calculate and concatenate the variables to obtain an answer that is then printed and repeated until the number of days is reached (starting from day two)
}
}
}
}
}

Related

Need first output to be a number, but its that numbers concatenation

My code is as follows:
import java.util.Scanner;
public class QuestionOne {
public static void main(String[] args) {
int numberofDays;
int sharePoints;
Scanner keyboard = new Scanner(System.in);
System.out.print("Number of days in the period: ");
numberofDays = keyboard.nextInt();
System.out.print("Share points on the first day: ");
sharePoints = keyboard.nextInt();
while (numberofDays < 10 || numberofDays > 20) {
System.out.println("The number of days doesn’t meet the required criteria, enter it again");
System.out.print("Number of days in the period: ");
numberofDays = keyboard.nextInt();
}
System.out.println("Day " + " Share Points");
for (int i = 1; i <= numberofDays; i++) {
if (numberofDays % 2 == 0)
if (i <= numberofDays / 2) {
sharePoints = sharePoints + 50;
System.out.println(i + " " + sharePoints);
} else {
sharePoints = sharePoints - 25;
System.out.println(i + " " + sharePoints);
}
else {
if (i <= numberofDays / 2 + 1) {
sharePoints = sharePoints + 50;
System.out.println(i + " " + sharePoints);
} else {
sharePoints = sharePoints - 25;
System.out.println(i + " " + sharePoints);
}
}
}
}
}
This code should output to something like (as an example if the user were to enter the values 11 for the day and 550 for share price):
Day Share Points
1 550
2 600
3 650
4 700
5 750
6 800
7 775
8 750
9 725
10 700
11 675
however when I enter 11 for the day, and 550 for the share price, my code looks like:
Day Share Points
1 600
2 650
3 700
4 750
5 800
6 850
7 825
8 800
9 775
10 750
11 725
From what I can tell according to my code, I have coded it so that it adds 50 every time until the number six- whereas I want it to display the first number as the user enters it in, then to start adding and subtracting accordingly (note that everything is as I want it in my output except for the first number, and the proceeding numbers, as a result, being different). My wording may not be very accurate, but I hope the example outputs are enough to explain what I want as my output.
Sometimes it can be useful to process a base case before a for loop.
In your case that would look like printing the appropriate line for day 1 and then starting your loop at i=2 instead of i=1.

my guessing game counter keeps rising

so for class I'm supposed to make a guessing game that gives you clues as you get closer to the answer. My question is when i run it and i get one Number correct, I would obviously keep that number and keep going with the other 4 numbers, when I do that, the problem is my correct digits counter keeps rising even if I don't get other digits correct.. how would I remedy this? Would i be able to add breaks in each of the if statements or would that completely exit me out of my do while loop?
public class GuessingGame {
public static void main(String[] args) {
int guess,numDigitsCorrect=0,sumDigitsCorrect=0,attempts=0,answer;
Random rng = new Random();
Scanner consoleScanner = new Scanner(System.in);
answer = rng.nextInt(90000) + 10000;
System.out.println("I have randomly chosen a 5-digit code for you to guess.Each time you guess,\n"
+ "I will tell you how many digits are correct and the sum of the digits that are correct."
+ "For example, if the number is \"68420\" and you guess 12468, I will respond:\n"
+ "Number of Digits Correct: 1\n"
+ "Sum of Digits Correct: 4\n"
+ "From deduction, you will know the 4 was correct in the guess."
+ "\nNow its your turn..................................................................");
do{
System.out.print("Please enter a 5-digit code (your guess): ");
guess = consoleScanner.nextInt();
int g1 = guess/10000;
int g2 = guess%10000/1000;
int g3 = guess % 10000 % 1000 / 100;
int g4 = guess % 10000 % 100 /10;
int g5 = guess % 10000 % 10 / 1;
int a1 = answer/10000;
int a2 = answer%10000/1000;
int a3 = answer % 10000 % 1000 / 100;
int a4 = answer % 10000 / 100 / 10;
int a5 = answer % 10000 % 10 / 10;
if(g1 == a1)
{
numDigitsCorrect ++;
sumDigitsCorrect += a1;
System.out.println("\nNumber of digits correct: " + numDigitsCorrect) ;
System.out.println("Sum of digits correct: " + sumDigitsCorrect);
System.out.println();
}
if(g2 == a2)
{
numDigitsCorrect ++;
sumDigitsCorrect += a2;
System.out.println("Number of digits correct: " + numDigitsCorrect) ;
System.out.println("Sum of digits correct: " + sumDigitsCorrect);
System.out.println();
}
if (g3 == a3)
{
numDigitsCorrect ++;
sumDigitsCorrect += a3;
System.out.println("Number of digits correct: " + numDigitsCorrect) ;
System.out.println("Sum of digits correct: " + sumDigitsCorrect);
System.out.println();
}
if (g4 == a4)
{
numDigitsCorrect ++;
sumDigitsCorrect += a4;
System.out.println("Number of digits correct: " + numDigitsCorrect) ;
System.out.println("Sum of digits correct: " + sumDigitsCorrect);
System.out.println();
}
if (g5 == a5)
{
numDigitsCorrect ++;
sumDigitsCorrect += a5;
System.out.println("Number of digits correct: " + numDigitsCorrect) ;
System.out.println("Sum of digits correct: " + sumDigitsCorrect);
System.out.println();
}
if(guess == answer)
{
System.out.println("****HOORAY! You solved it. You are so smart****");
break;
}
}while (guess != answer);
}
}
Few things to fix -
Make sure your a4, a5 are correct
int a4 = answer % 10000 % 100 / 10; // note the modulus
int a5 = answer % 10000 % 10; // note divided by 1 or remove the redundant statement
Move your print statement out of your if block to the end of all if inside the do block as -
if (g1 == a1) {
numDigitsCorrect++;
sumDigitsCorrect += a1;
}
... //other if statements
if (guess == answer) {
System.out.println("****HOORAY! You solved it. You are so smart****");
break;
}
System.out.println("Number of digits correct: " + numDigitsCorrect);
System.out.println("Sum of digits correct: " + sumDigitsCorrect);
Also since you already do a check
if (guess == answer) {
System.out.println("****HOORAY! You solved it. You are so smart****");
break;
}
within your do you can change your while condition to true as -
do {
... your existing code
} while(true);
To answer
Would i be able to add breaks in each of the if statements
If you do so, for even a single digit match your loop will exit(break).
Importantly to fix the counter, initialize the counter within the do block as
do {
numDigitsCorrect = 0;
sumDigitsCorrect = 0;
.. // existing logic
}

why does it print twice? if -else [duplicate]

This question already has answers here:
Java - Looping 2d Array to find index of a value not working
(2 answers)
Closed 7 years ago.
I'm learning java atm , and had to write a code to calculate the monetary units, and only display the nonzero denominations using singular words for single units and plural words for plural units.
This is the code so far:
import java.util.Scanner;
public class ComputeChange {
public static void main(String[] args) {
Scanner input = new Scanner(System. in );
// receive amount
System.out.println("Enter an amount in double, for example 11.56: ");
double amount = input.nextDouble();
int remainingAmount = (int)(amount * 100);
// find the number of one dollars
int numberOfDollars = remainingAmount / 100;
remainingAmount = remainingAmount % 100;
// find the number of quarters in the remaing amount
int numberOfQuarters = remainingAmount / 25;
remainingAmount = remainingAmount % 25;
//find the number of dimes in the remaing amount
int numberOfDimes = remainingAmount / 10;
remainingAmount = remainingAmount % 10;
//find the number of nickels in the remaing amount
int numberOfNickles = remainingAmount / 5;
remainingAmount = remainingAmount % 5;
//find the number of pennies in the remaining amount
int numberOfPennies = remainingAmount;
//Display results
System.out.println("Your amount" + amount + "consists of");
if (numberOfDollars > 1) {
System.out.println(" " + numberOfDollars + "dollars");
} else if (numberOfDollars == 1); {
System.out.println(" " + numberOfDollars + "dollar");
}
The output is:
run:
Enter an amount in double, for example 11.56:
12,33
Your amount12.33consists of
12dollars
12dollar
1quarters
1quarter
0dimes
0dime
1nickles
1nickle
3pennies
3penny
Why is everything printed double? 3 == not 1 so why does it still say 3 penny?
Noob question maybe, but thats because i am one :) Thanks for help!
Because you added a random ; after the second if. Therefor your second System.out.println is not part of the if-statement. Remove it:
if (numberOfDollars > 1) {
System.out.println (" " + numberOfDollars + "dollars");
} else if (numberOfDollars == 1) {
System.out.println (" " + numberOfDollars + "dollar");
}
Remove the semicolon after if();
if (numberOfDollars == 1);
The second print statement is printing because it is not a part of if(); due to the semicolon that you have after if()
replace
else if (numberOfDollars == 1); { // with ;, condition terminates here itself
with
else if (numberOfDollars == 1) {
Semicolon at the end of If statememnt , finish the statement in single line. Means it ignores the result of condition and continue the execution from the next line.

Changing you own answer in Java

I am currently working on a program in Java. It's a cardgame where you have to guess the numbers which are randomly generated of three cards (4, 5 or 6). If you guessed the numbers in the right order, you win. If you do not guess these numbers in the right order the first time, you may retry only one card. So far all of this I got to work, however when I want to change my second or the third answer I have to type '2' two times or '3' three times to change these cards. Here is my code:
package cardgame;
import java.util.Scanner;
public class CardGame {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int[] guess = new int[3];
int[] card = new int[3];
System.out.println("Pick three cards with numbers ranging from 4 to 6!\n");
for (int i=0; i<3; i++){
System.out.print("Card number " + (i+1) + " (4, 5 or 6): ");
guess[i] = scan.nextInt();
}
System.out.println(" ");
System.out.println("Your hand of cards: " + "[" + guess[0] + "]" + "[" + guess[1] + "]" + "[" + guess[2] + "]");
for (int i=0; i<3; i++){
card[i] = (int) (Math.random() * 3 + 2 +2);
}
int count = 0;
for (int i=0; i<3; i++){
if (card[i] == guess[i])
count++;
}
if (count == 3){
System.out.println("My hand of cards: " + "[" + card[0] + "]" + "[" + card[1] + "]" + "[" + card[2] + "]\n");
System.out.println("Congratulations, you have won!\nType 'end' to end the game and I will show you my hand of cards.");
} else{
System.out.println("Not quite yet there!\n");
}
if (count !=3){
System.out.println("Would you like to change one of your guesses? yes/no");
}
if("yes".equals(scan.next())){
System.out.println("\nWhat card would you like to change? 1/2/3");
{
if(scan.nextInt() == 1 || scan.nextInt() == 2 || scan.nextInt() == 3){
System.out.println("\nWhat is your new guess?");
int secondGuess = scan.nextInt();
if (secondGuess == card[0] || secondGuess == card[1] || secondGuess == card[2]){
count++;
}
if (count == 3){
System.out.println("\nCongratulations, you have won!");
} else{
System.out.println("\nI'm sorry, you lost!");
}
}
}
}
// Print the 3 random numbers card[0], card[1] and card[2]
System.out.println("My hand of cards: " + "[" + card[0] + "]" + "[" + card[1] + "]" + "[" + card[2] + "]\n");
}
}
Output so far:
Pick three cards with numbers ranging from 4 to 6!
Card number 1 (4, 5 or 6): 4
Card number 2 (4, 5 or 6): 5
Card number 3 (4, 5 or 6): 6
Your hand of cards: [4][5][6]
Not quite yet there!
Would you like to change one of your guesses? yes/no
yes
What card would you like to change? 1/2/3
2
2
What is your new guess?
6
Congratulations, you have won!
My hand of cards: [4][4][6]
As you can see, I have to insert two twice. Also my new guess was 6 on the second spot and to win it should have been 4 on the second spot. Where have I gone wrong? I can't seem to fix it.
You're calling scan.nextInt up to 3 times in this line:
if(scan.nextInt() == 1 || scan.nextInt() == 2 || scan.nextInt() == 3){
which will read up to three numbers depending on what numbers you type in.
First number is 1: only one number read.
First number isn't 1 and second number is 2: two numbers read.
Else, 3 numbers read.
Grab the number once, then compare it:
int someNumber = scan.nextInt();
if(someNumber == 1 || someNumber == 2 || someNumber == 3){

How to make a Java guessing game program [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I am trying to make a guessing game program with Java and need help Here is what I have so far.
public class CodeGuessingGame {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int[] guess = {0, 1, 2, 3, 4};
int[] secretNumber = {0, 1, 2, 3, 4};
System.out.println("Let the game begin...");
System.out.println("Guess my secret code, consisting of 1 and 2");
System.out.println(" ");
for (int i=0; i<5; i++) {
System.out.print("Guess number " + (i+1) + " (1 or 2): ");
guess[i] = scan.nextInt();
}
System.out.println(" ");
System.out.println("Your guess: " + "[" + guess[0] + "]" +
"[" + guess[1] + "]" + "[" + guess[2] + "]" +
"[" + guess[3] + "]" + "[" + guess[4] + "]");
for (int i=0; i<5; i++) {
secretNumber[i] = (int) (Math.random() * 2 + 1);
}
System.out.print("Secret code: " + "[" + secretNumber[0] + "]" +
"[" + secretNumber[1] + "]" + "[" + secretNumber[2] + "]" +
"[" + secretNumber[3] + "]" + "[" + secretNumber[4] + "]");
}
The output of this code should be the following:
Let the game begin...
Guess my secret code, consisting of 1 and 2
Guess number 1 (1 or 2): 1
Guess number 2 (1 or 2): 2
Guess number 3 (1 or 2): 2
Guess number 4 (1 or 2): 1
Guess number 5 (1 or 2): 1
Your guess: [1][2][2][1][1]
Secret code: [2][1][2][1][2]
This code goes on forever. You must be able to win or lose the game. If you get 3 or more numbers of the secret code right, you win. If you don't get 3 or more numbers right, you lose. How should I do this?
Add this at the end of the main.
int count = 0;
for (int i=0; i<5; i++) {
if (secretNumber[i] == guess[i])
count++;
}
if (count >= 3)
System.out.print("You guessed " + count + " numbers correct, therefore you win");
else
System.out.print("You only guessed " + count + " number(s) correct, therefore you lose");
You should split up the behavior of your code into different methods. For example,
public int void recieveGuess(int guessNum, Scanner scan){
System.out.print("Guess number ") + guessNum + "(1 or 2): ");
return scan.nextInt(); //Assuming the user entered an int. May want to check for that.
}
public int compareGuess(int[] secret, int[] guesses){
int count = 0;
for(int i = 0; i < secret.length; i++){
if(secret[i] == guess[i]){
count++;
}
}
return count;
}
Then in your main you can just print the starting information, then loop through recieveGuess however many times you want, and then compare at the end.
if(compareGuess(secretNumber, guess) >= 3){
//they won
} else {
//they lost
}
Also you should just initialize secretNumber to new int[5]. This will create an array of length five with all zeros or whatever length you want. Then fill the secret number with random numbers. Like this:
int[] secretNumber = new int[5];
int[] guess = new int[5];
To do this, you can just define a variable a and increment it up one for each right answer. For example:
int a;
if (answer1 == true1){
a = a + 1;
}
if (answer2 == true2){
a = a + 1;
}
//check the rest
if (a > 2){
System.out.println("You win");
}
else{
System.out.println("You lose");
}

Categories

Resources