Java decToHex in recursive - wrong output order - java

I tried to check other questions close to this one, but couldn't figure out one answer for mine, that's why sending it as a new post. Hope this won't cause any problem.
I am trying to write a simple JAVA code for number conversion- from decimal to octal or hex. With octal everything is fine, but with hex, the output is in wrong order. like if the answer is 613 - program gives out 316.
Here is my full code:
import java.util.Scanner;
public class Cem {
public static void octalconverter(int a) {
if (a == 0) { //our base
System.out.println(); //I first put here return a, but then it was adding zeros to the end
} else {
System.out.print(a % 8);// first remainder = last digit, and so on
octalconverter(a / 8); //recursively going till it is base
}
}
public static void hexconverter(int a) {
if (a == 0) {
System.out.println();
} else {
System.out.print(hexchart(a % 16));
hexconverter(a / 16);
}
}
public static String hexchart(int a) {
String result = "";
if (a <= 9) {
result = a + result;
} else {
if (a == 10)
result = result + "A";
// System.out.print("A");
if (a == 11)
result = result + "B";
// System.out.print("B");
if (a == 12)
result = result + "C";
// System.out.print("C");
if (a == 13)
result = result + "D";
//System.out.print("D");
if (a == 14)
result = result + "E";
//System.out.print("E");
if (a == 15)
result = result + "F";
// System.out.print("F");
}
return result;
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner oScan = new Scanner(System.in);
System.out.println("Please enter your decimal number : "); //getting input
int num = oScan.nextInt(); //assigning
System.out.println("Enter 1 for Octal Base Conversion #### Enter 2 for Hex Conversion");
int num2 = oScan.nextInt();
if (num2 == 1) {
System.out.print(num + " in Octal(base8) system is : ");
octalconverter(num); //conversion
} else if (num2 == 2) {
System.out.print(num + " in Hexadecimal(base16) system is : ");
hexconverter(num);
} else {
System.out.println("You entered a wrong choice for conversion type, please restart the program");
}
}
}
Can you please tell me where I messed up. I also must say I am looking for the mistake I did here, not another way of how to write this code. Thank you those who are willing to share another way of it, but again I need to learn my mistake here.
Thank you for your help

Change
public static void hexconverter(int a) {
if (a == 0) {
System.out.println();
} else {
System.out.print(hexchart(a % 16));
hexconverter(a / 16);
}
}
To
public static void hexconverter(int a) {
if (a == 0) {
System.out.println();
} else {
hexconverter(a / 16);
System.out.print(hexchart(a % 16));
}
}
Your octal conversion is also not working properly. It prints in reverse order. So just swapped those instructions also.

Bill Gates once said that he would always "hire a lazy person to do a difficult job" at Microsoft. ... "Because a lazy person will find an easy way to do it."
I know you said you aren't looking for another way of how to write this code but this is much easier way to get the job done.
public static String octalNumber = "";
public static void octalconverter(int a){
while(a!=0){
octalNumber = octalNumber + String.valueOf(a%8);
a = a/8;
}
System.out.println(new StringBuilder(octalNumber).reverse().toString());
}
Final number has to be reversed.That was a mistake.

Related

How would I loop my program back to the beginning after a question was answered correctly 3 times in a row/ and add variance

I'm creating a program to help with students solving y= m(x) + b. As of right now, I have the program to display the menu and evaluate if your response is correct to the answer. However, I need it to also count the number of correct answers in a row.
If 3 correct end program and output total correct out of attempts tried.
else if there were 3 attempts made the output a tip.
The main issue I'm having is the loop of the two (methods?). I apologize in advance if my code is atrocious, I'm having a hard time understanding methods and classes in this compared to how Python is. Anyone's suggestions or tips would be immensely helpful.
So far I've tried adding methods, and attempts at classes to certain parts of the program such as
public static void user_input(int point_of_line_cross, int slope, int y_intercept, int independent_variable) {}
and
public static test_input() {}
However, now I'm facing scoping problems as well as errors referencing certain variables.
package algebra_Tutor;
import java.util.Scanner;
class AlgebraTutor {
public static void main(String[] args){
System.out.println("Enter 1 if you would like to solve for Y?");
System.out.println("Enter 2 if you would like to solve for M?");
System.out.println("Enter 3 if you would like to solve for B?");
System.out.println("Enter 4 to Quit");
//Asks for user input
System.out.print("Enter your selection: ");
}
//Creates random # for values in formula
int y_ = point_of_line_cross;
int m_ = slope;
int b_ = y_intercept;
int x_ = independent_variable;
public static void user_input(int point_of_line_cross, int slope, int y_intercept, int independent_variable) {
// Creates scanner for input of menu Def as menu selector
Scanner user_Selection = new Scanner(System.in);
//Converts user input to an integer
int selection = user_Selection.nextInt();
user_Selection.close();
y_intercept = (int) (Math.floor(Math.random() * 201) - 100);
slope = (int) Math.floor(Math.random() * 201) - 100;
point_of_line_cross = (int) Math.floor(Math.random() * 201) - 100;
independent_variable = (int) Math.floor(Math.random() * 201) - 100;
//Tests what user input was, with expected output
if (selection == (1)) {
System.out.println("You chose to solve for Y: ");
System.out.println("Y = " +slope +"("+independent_variable+")"+" + "+y_intercept);
System.out.println("Input your answer: ");
}
else if (selection == (2)) {
System.out.println("You chose to solve for M: ");
System.out.println("M = "+"("+point_of_line_cross+" - "+y_intercept+")"+" / "+independent_variable);
System.out.println("Input your answer: ");
}
else if (selection == (3)) {
System.out.println("You chose to solve for B: ");
System.out.println("B = "+point_of_line_cross+" - "+slope+"("+independent_variable+")");
System.out.println("Input your answer: ");
}
else if (selection == (4)) {
System.out.println("You chose to quit the program. ");
return;
}
}
//Solves the problem in order to compare to User input
int answer_y = ((m_) * (x_)) + (b_);
int answer_m =(y_) - ((b_) / (x_));
int answer_b =(y_) - ((m_)* (x_));
public static test_input() {
//Problem solver defined
Scanner answer_input = new Scanner(System.in);
int answer = answer_input.nextInt();
//Creates loop for program
var counter = 0;
int correct = 0;
var answers_correct = false;
while (!answers_correct && correct < 3) {
if (answer == answer_y){
counter++;
correct++;
System.out.println("You answered correctly");
return;
}
else if (counter >= 3 && correct < 3) {
System.out.println("Youve been missing the questions lately, let me help! ");
}
else
{
System.out.println("Try again");
counter++;
correct = 0;
break;
}
}
}
}
I expect the program to output correct answers out of attempts after the user completes 3 problems in a row. In addition, it needs to output a tip after 3 attempts. And then after 3 correct, it should loop back to the beginning of program.
well I figured I would let you figure out how to make it loop on your own but I solved your other problems and put comments where I changed things. Hope this helps
//declared variables here. global variables must be declared static when accessed in a static method (ex: user_input())
static int y_;
static int m_;
static int b_;
static int x_;
public static void main(String[] args) {
// Creates scanner for input of menu Def as menu selector
Scanner user_Selection = new Scanner(System.in);
System.out.println("Enter 1 if you would like to solve for Y?");
System.out.println("Enter 2 if you would like to solve for M?");
System.out.println("Enter 3 if you would like to solve for B?");
System.out.println("Enter 4 to Quit");
//Converts user input to an integer
int selection = user_Selection.nextInt();
//call user_input()
user_input(selection);
}
public static void user_input(int selection) {
Scanner user_Selection = new Scanner(System.in);
int userAnswer;
int y_intercept = (int) (Math.floor(Math.random() * 201) - 100);
int slope = (int) Math.floor(Math.random() * 201) - 100;
int point_of_line_cross = (int) Math.floor(Math.random() * 201) - 100;
int independent_variable = (int) Math.floor(Math.random() * 201) - 100;
y_ = point_of_line_cross;
m_ = slope;
b_ = y_intercept;
x_ = independent_variable;
//Tests what user input was, with expected output
if (selection == (1)) {
System.out.println("You chose to solve for Y: ");
System.out.println("Y = " + slope + "(" + independent_variable + ")" + " + " + y_intercept);
System.out.println("Input your answer: ");
userAnswer = user_Selection.nextInt();
/*After user enters answer we test the answer by calling test_input
* */
test_input(userAnswer);
} else if (selection == (2)) {
System.out.println("You chose to solve for M: ");
System.out.println("M = " + "(" + point_of_line_cross + " - " + y_intercept + ")" + " / " + independent_variable);
System.out.println("Input your answer: ");
userAnswer = user_Selection.nextInt();
/*After user enters answer we test the answer by calling test_input
* */
test_input(userAnswer);
} else if (selection == (3)) {
System.out.println("You chose to solve for B: ");
System.out.println("B = " + point_of_line_cross + " - " + slope + "(" + independent_variable + ")");
System.out.println("Input your answer: ");
userAnswer = user_Selection.nextInt();
/*After user enters answer we test the answer by calling test_input
* */
test_input(userAnswer);
} else if (selection == (4)) {
System.out.println("You chose to quit the program. ");
}
}
// you forgot to include return type ex: void, int, String, double, float, etc
public static void test_input(int entered_answer) {
//Solves the problem in order to compare to User input
int answer_y = ((m_) * (x_)) + (b_);
int answer_m = (y_) - ((b_) / (x_));
int answer_b = (y_) - ((m_) * (x_));
//Problem solver defined
int answer = entered_answer;
//Creates loop for program
int counter = 0;
int correct = 0;
boolean answers_correct = false;
while (!answers_correct && correct < 3) {
if (answer == answer_y) {
counter++;
correct++;
System.out.println("You answered correctly");
return;
} else if (counter >= 3 && correct < 3) {
System.out.println("You've been missing the questions lately, let me help! ");
} else {
System.out.println("Try again");
counter++;
correct = 0;
break;
}
}
}
`
public static void user_input(int point_of_line_cross, int slope, int y_intercept, int independent_variable)
If you give a method parameters, then when the method is called you will have to enter the values into the parameter yourself. I don't think this is what you intended because you defined what you wanted those parameter values to be here:
y_intercept = (int) (Math.floor(Math.random() * 201) - 100);
slope = (int) Math.floor(Math.random() * 201) - 100;
point_of_line_cross = (int) Math.floor(Math.random() * 201) - 100;
independent_variable = (int) Math.floor(Math.random() * 201) - 100;
In your test_input() method you wrote:
Scanner answer_input = new Scanner(System.in);
int answer = answer_input.nextInt();
.nextInt() will make the program halt and wait for user input so you don't want to use it until you are ready to get the input.
I don't really know much about the var keyword in java but rather than using var I figured you should just declare the variable type so from this:
var counter = 0;
to this:
int counter = 0;
and to get a better understanding on how methods work I recommend these two videos:
Intro to java methods
Java method parameters and return types
For an in depth explanation of the fundamentals of java in general then I recommend this whole playlist
Java Beginner Programming
It's quite late on a saturday for me to do algebra, so I will stick to suggesting changes to the structure of your program. First, you can accomplish everything with a single class to contain the questions, and score for the user. The methods in that class can be chosen via a menu in the main.
I wrote a sample of how I would structure this based on standard Java OOP methodology. In my program, the main needs no static class, it loops a menu, and the choice of a question is made there. My methods hava single question, you can add as many as you like in the menu, the important thing is the structure.
import java.util.Scanner;
//This class contains the two methods and over-all score
class Material {
private int score;
//The user chooses this or the earth method
public void sky() {
String answer = "null";
int count = 0;
Scanner input = new Scanner(System.in);
//within the method, is this while loop which gives a hint after 3 attempts.
while (!answer.equals("blue") && (!answer.equals("exit"))) {
System.out.println("What color is the sky? 'exit' to exit");
answer = input.nextLine();
count++;
if (count == 3)
System.out.println("Hint: It starts with a 'b'");
}
if (answer.equals("blue"))
score += 1;//The score will increment if the choice is correct,
else//or else leave with nothing...
return;
}
//This method is the same as the sky() method, just different question and answer.
public void earth() {
String answer = "null";
int count = 0;
Scanner input = new Scanner(System.in);
while (!answer.equals("iron") && (!answer.equals("exit"))) {
System.out.println("What is the core made of? 'exit' to exit");
answer = input.nextLine();
count++;
if (count == 3)
System.out.println("Hint: It starts with a 'i'");
}
if (answer.equals("iron"))
score += 1;
else
return;
}
public int getScore() {
return score;
}
}
public class Questions {
public static void main(String[] args) {
//No static methods needed, here is an instance of our test materia class.
Material material = new Material();
//The choice and scanner are instantiated here.
int choice = 0;
Scanner input = new Scanner(System.in);
//This while loop uses a switch statement to choose the methods for the questions
while (choice != 3) {
if (material.getScore() == 3) {
System.out.println("Good job, you scored three right.");
return;
}
System.out.println("SCORE: " + material.getScore());
System.out.println("Anwer questions about the sky: 1");
System.out.println("Answer quetions about the earth: 2");
System.out.println("Exit: 3");
choice = input.nextInt();
//choices are 1 , 2 for questions, and 3 to leave.
switch (choice) {
case 1:
material.sky();
break;
case 2:
material.earth();
break;
case 3:
System.out.println("Exiting...");
break;
default:
System.out.println("not a valid number choice...");
}
}
}// main
}// class
Side note: instead of asking the user for 1, 2, 3 or 4, you should directly ask them to enter the variable they want to solve:
Solve the equation y = m * x + b for which variable (y, m, b, quit)?
This makes the users of the program think more in the problem domain instead of some technically useless indirection.
As you have a Python background you should know that the indentation of the lines is important and has meaning. It's the same for Java programs. The only difference is that the Java compiler ignores the indentation completely. But Java programs are also read by humans, and for them the indentation is viable for understanding the structure of the program. The code you posted has inconsistent indentation, and you should let your IDE fix that.
Your program should be structured like this:
public class AlgebraTutor {
private final Scanner in = new Scanner(System.in);
private final PrintStream out = System.out;
private int attempts = 0;
void solveForY() {
...
}
void solveForM() {
...
}
void solveForB() {
...
}
void mainMenu() {
while (true) {
out.println("Solve the equation y = m * x + b for which variable (y, m, b), or quit?");
if (!in.hasNextLine()) {
return;
}
switch (in.nextLine()) {
case "y":
solveForY();
break;
case "m":
solveForX();
break;
case "b":
solveForB();
break;
case "q":
case "quit":
return;
}
}
}
public static void main(String[] args) {
new AlgebraTutor().mainLoop();
}
}

Logical operators in 'else if' statement

I am trying to learn "if else" statements and I am having trouble with the middle 'if else' part of the script.
package practice;
import java.util.Scanner;
public class Practice {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
System.out.println("enter a number between 1 and 10 ");
if (!in.hasNextDouble()) {
String word = in.next();
System.err.println(word + " is not a number");
} else if (!(in.nextDouble() > 0) || !(in.nextDouble() <= 10)) {
Double wrongnumber = in.nextDouble();
System.err.println(wrongnumber + " is not between 1 and 10");
} else {
System.out.println("It works!");
}
return;
}
}
There are no errors but in the 'else if' block I can't get it to print the err "..... not between 1 and 10", whether or not I put a number between 1 and 10 or higher. It also wont print the "it works!" line anymore when I add the 'else if' block.
any suggestions would be much appreciated.
You are caling in.nextDouble() several times in your if else block, so you get something else every time.
if (!(in.nextDouble() > 0) || !(in.nextDouble() <= 10)) {
Double wrongnumber = in.nextDouble();
System.err.println(wrongnumber + " is not between 1 and 10");
}
convert it to something like
double next = in.nextDouble();
if (!(next > 0) || !(next <= 10)) {
Double wrongnumber = next;
System.err.println(wrongnumber + " is not between 1 and 10");
}
To be logically correct you might switch to Integer instead of Double values.
You call in.hasNextDouble() several times. Each time it scans new number from input so it may cause your issue. You should also consider how you write conditions. I am aware you may just try what's happening there but this kind of condition is hard to read. You can use
(number <= 1) || (number > 10) (remove negations by inverting operators) for example.
else if (!(in.nextDouble() > 0) || !(in.nextDouble() <= 10)) {
Double wrongnumber = in.nextDouble();
I'm not sure but here you operate on 3 different numbers. Before condition, write it to a variable.
Don't compare int with double
#RevCarl, According what i understand by your code and the description provided, what you want to do is to check whether the input is a number and whether its between 1 to 10. Also you have not clearly said the type of the input you are expecting. I assume it as integer, and the code below will do the task.
import java.util.Scanner;
public class Demo {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a No between 1 to 10");
String next = input.next();
Integer i = Integer.parseInt(next);
if (null == i) {
System.out.println("Input is not a number");
} else {
if (i > 0 && i < 10) {
System.out.println("It works");
} else {
System.out.println("Not Between 1 to 10");
}
}
}
}
Otherwise u can replace the statement String next = input.next(); with Integer i = input.nextInt(); which takes the integer numbers input from the console.

Number identifying program

Very amateur coder here,
I'm in the process of making a simple program to tell whether a number is positive, negative, odd or even. So far everything works apart from positive odd numbers, but cant figure out why ?
Also, how would i loop it ? would i use a for or while loop ?
Thanks
package weekeleven;
import java.util.Scanner;
public class week111 {
static int number;
static String pE;
static String pO;
static String nE;
static String nO;
static String eR;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
number = -input.nextInt();
pE = ("Positive Even");
pO = ("Positive Odd");
nE = ("Negative Even");
nO = ("Negative Odd");
eR = ("Error");
Object x = null;
x=getSignAndParity(x);
System.out.println(x);
}
public static String getSignAndParity(Object x) {
if ((number > 0) && (number % 2 == 0)) { //negative and even
return nE;
} else if((number < 0) && (number % 2 == 1)) { // positive and odd
return pO;
} else if((number < 0) && (number % 2 == 0)) { // positive and even
return pE;
} else if((number > 0) && (number % 2 == 1)) { // negative and odd
return nO;
} else { // other cases
return eR;
}
}
}
There are multiple issues with your code causing it not to work as expected.
1) You are using mod 2 on negative numbers to check if a negative number is even or odd. But that will not work. For e.g., -7 mod 2 = -1 (which is neither 1 nor 0)
2) You are negating the user's input :
number = -input.nextInt();
and you flipped the signs >, < which is unnecessary
3) You should not be passing the int input as Object. You could just simply:
public static String getSignAndParity(int x)
Removing all the superfluous and unnecessary declarations and code, you can have this:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int number = input.nextInt();
System.out.println(getSignAndParity(number));
}
public static String getSignAndParity(int num) {
if(num == 0)
return "Error";
String sign = num>0?"Positive":"Negative";
String parity = Math.abs(num)%2==0?"Even":"Odd";
return sign + " " + parity;
}
Change with this
else if((number > 0) && (number % 2 == 1)) { // positive and odd
return pO;
}
For positive odd numbers and for looping you need either existing the code or have a condition that is taken from scanner and then close the scanner.
scanner : https://www.javatpoint.com/Scanner-class
You have to change positive odd like this:
else if((number < 0) && (number % 2 == -1)) { // positive and odd}

How to pass value from one method into main method?

I'm creating a math program that asks the user how many digits they'd like to use, then asks them what kind of math they want to do. It then asks the user 10 math questions based on their answers. It then decides if they're right or wrong and displays an appropriate message. It then calculates their percentage of correct answers and displays a message based on the percentage.
The problem is that the program never stops after 10 questions and never calculates the percentage or displays the final message. I believe this is at least partially occurring because I'm not passing the new "answeredTyped" value from the "askQuestion" method. Can someone explain how I can easily pass this new value back to the main method so that it'll stop at 10? Or perhaps tell me what else is keeping this from working correctly?
I've asked quite a few questions about this program already, so I appreciate everyone's patience with me learning Java and having very little knowledge of the language.
Thank you for any help! (also I apologize for any bad formatting here! After changing about a million things, it got ugly)
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Assignment2 {
public static int answeredTyped = 0;
public static int correctAnswers = 0;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int difficulty = 1;
String[] operators = { "plus", "minus", "times", "divided by" };
int selectedOperator = 1;
int difficultyInput = Integer
.parseInt(JOptionPane
.showInputDialog("Please choose the difficulty. Enter the number of digits to use in each problem."));
if (difficultyInput > 0) {
difficulty = difficultyInput;
}
int arithmeticMethod = Integer
.parseInt(JOptionPane
.showInputDialog("Choose an arithmetic problem to study: 1 = Addition Only, 2 = Subtraction Only, 3 = Multiplication Only, 4 = Division Only, 5 = Random Problems"));
selectedOperator = arithmeticMethod;
new Assignment2().askQuestion(difficulty, null, selectedOperator,
answeredTyped, operators, correctAnswers);
while (answeredTyped < 10) {
askQuestion(difficulty, null, selectedOperator, answeredTyped,
operators, correctAnswers);
answeredTyped++;
if (answeredTyped>= 10) {
if (((float) correctAnswers / answeredTyped) >= 0.75) {
JOptionPane
.showMessageDialog(null,
"Congratulations, you are ready to go on to the next level!");
} else {
JOptionPane.showMessageDialog(null,
"Please ask your teacher for extra help.");
}
}
}
}
public static boolean checkResponse(double primaryInt, double secondaryInt,
String operatorText, double response) {
if (operatorText.equals("plus")) {
return (primaryInt + secondaryInt) == response;
} else if (operatorText.equals("minus")) {
return (primaryInt - secondaryInt) == response;
} else if (operatorText.equals("times")) {
return (primaryInt * secondaryInt) == response;
} else if (operatorText.equals("divided by")) {
return (primaryInt / secondaryInt) == response;
}
return false;
}
public static String displayResponse(boolean isCorrect) {
int randomIndex = (int) (Math.floor(Math.random() * (4 - 1 + 1)) + 1);
switch (randomIndex) {
case 1:
return isCorrect ? "Very Good!" : "No. Please try again.";
case 2:
return isCorrect ? "Excellent!" : "Wrong. Try once more.";
case 3:
return isCorrect ? "Nice Work!" : "Don\'t give up!";
case 4:
return isCorrect ? "Keep up the good work!" : "No. Keep trying.";
}
return "Oops...";
}
public static void askQuestion(int difficulty, String operatorText,
int selectedOperator, int answeredTyped, String[] operators,
int correctAnswers) {
boolean correctAnswer = false;
double primaryInt = Math.floor(Math.pow(10, difficulty - 1)
+ Math.random() * 9 * Math.pow(10, difficulty - 1));
double secondaryInt = Math.floor(Math.pow(10, difficulty - 1)
+ Math.random() * 9 * Math.pow(10, difficulty - 1));
operatorText = (selectedOperator == 5) ? operators[(int) Math
.floor(Math.random() * operators.length)]
: operators[selectedOperator - 1];
double response = Double.parseDouble(JOptionPane
.showInputDialog("How much is " + primaryInt + " "
+ operatorText + " " + secondaryInt + "?"));
correctAnswer = checkResponse(primaryInt, secondaryInt,
operatorText, response);
JOptionPane.showMessageDialog(null, displayResponse(correctAnswer));
if (correctAnswer)
correctAnswers++;
}
}
You have two while loops, so it will call askQuestion() ten times, and then there is askQuestion's own while loop:
main()
while (answeredTyped < 10) {
askQuestion()
while (!correctAnswer && answeredTyped < 10) {
Try using only a single while loop, and putting the evaluation of the answers in total outside of the askQuestion() method
You have to increment answeredType in the while loop of the main method,not within another method,since you have not declared the variable as global

How to assign a random number a string value in my program

as the title suggests I am doing a program for homework that is a slot machine. I have searched around and I am pretty satisfied that the program works correctly enough for me. The problem Im having is on top of generating the random numbers, I am supposed to assign values for the numbers 1-5 (Cherries, Oranges, Plums, Bells, Melons, Bars). Then I am to display the output instead of the number when my program runs. Can anyone get me pointed in the right direction on how to do this please?
import java.util.Random;
import java.util.Scanner;
public class SlotMachineClass {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int Coins = 1000;
int Wager = 0;
System.out.println("Steve's Slot Machine");
System.out.println("You have " + Coins + " coins.");
System.out.println("Enter your bet and press Enter to play");
while (Coins > 0)
{
int first = new Random().nextInt(5)+1;
int second = new Random().nextInt(5)+1;
int third = new Random().nextInt(5)+1;
Wager = input.nextInt();
if(Wager > Coins)
Wager = Coins;
System.out.println(first + " " + second + " " + third);
if(first == second && second == third)
{ Coins = Coins + (Wager * 3);
System.out.println("You won " + (Wager * 3) + "!!!!" + " You now have " + Coins + " coins.");
System.out.println("Enter another bet or close program to exit");}
else if((first == second && first != third) || (first != second && first == third) || (first != second && second == third))
{ Coins = Coins + (Wager * 2);
System.out.println("You won " + (Wager * 2) + "!!!" + " You now have " + Coins + " coins.");
System.out.println("Enter another bet or close program to exit");}
else {Coins = Coins - Wager;
System.out.println("You Lost!" + "\nPlay Again? if so Enter your bet.");}
}
while (Wager == 0)
{
System.out.println("You ran out of coins. Thanks for playing.");
}
}
}
If you have an int and want to have some String associated with that, there are a couple of ways to do that.
The first one is to have an array of Strings and look them up.
public static String[] text = new String[] {"Cherry", "Bell", "Lemon", "Bar", "Seven"};
public String getNameForReel(int reelValue) {
return text[reelValue];
}
// And to call it...
System.out.println(getNameForReel(first)); //etc...
Or, you can do it in a switch statement (I don't prefer this, but you might):
public String getNameForReel(int reelValue) {
switch(reelValue) {
case 0: return "Cherry";
case 1: return "Bell";
case 2: return "Lemon";
case 3: return "Bar";
case 4: return "Seven";
}
}
You need a lookup table:
String[] text = new String[] {"Cherry", "Bell", "Lemon", "Bar", "Seven"};
Then you can just do
System.out.println(text[first] + " " + text[second] + " " + text[third]);
without creating more methods.
The non-array solution most likely to be used a by new programmer in an intro course would be a nested if-else:
String fruitToPrint = "";
if (num == 0)
fruitToPrint = "Cherries";
else if (num == 1)
fruitToPrint = "Oranges";
else if (num == 2)
fruitToPrint = "Plums";
else if (num == 3)
fruitToPrint = "Bells";
else if (num == 4)
fruitToPrint = "Melons";
else if (num == 5)
fruitToPrint = "Bars";
else
System.out.println("Couldn't assign fruit from num=" + num);
System.out.println("The corresponding fruit was " + fruitToPrint);
Create an array:
String[] s = {Cherries, Oranges, Plums, Bells, Melons, Bars};
Then you can print s[num-1] instead of num (where num is the random int). E.g. if your random int came out to be 2, print s[2-1] i.e. s[1] which will be Orange.
Here's an alternative solution to the question which I think follows best programming practices. This is probably even less allowed for your assignment than an array, and will be a dead giveaway that you got your answer on StackOverflow, but the problem would lend itself to using an enum type with an int->enum mapping:
enum Fruit {
Cherries(1),
Oranges(2),
Plums(3),
Melons(4),
Bars(5);
private static final Map<Integer, Fruit> lookupMap = new HashMap<Integer, Fruit>();
static {
for (Fruit fruit : Fruit.values()) {
lookupMap.put(fruit.getLookup());
}
}
static Fruit fromLookup(int lookup) {
return lookupMap.get(lookup);
}
private final int lookup;
private Fruit(int lookup) {
this.lookup = lookup;
}
int getLookup() {
return lookup;
}
}
void printEnumExample() {
int fruitToPrint = 4;
System.out.println(Fruit.fromLookup(fruitToPrint)); // <- This will print "Melons"
}

Categories