Java display does not show whole method - java

Having trouble with this the whole day. Please help me. I can't get the problem to display
The output shows
PROBLEM NUMBER 1
Answer:0
Correct....
PROBLEM NUMBER 2
Answer:1
Wrong....
It must show:
PROBLEM NUMBER 1
10 + 11 = ?
Answer: 21
Correct...*/
import java.util.Random;
import java.util.*;
import java.util.Scanner;
import javax.swing.JOptionPane;
import java.lang.Math;
public class MathIsSuperFun1{
Scanner input = new Scanner(System.in);
int correctAnswers;
int randomNum1;
int randomNum2;
int choice;
int corrrectAnswers, wrongAnswers;
String playerName ="";
int operation;
int userAnswer;
int correctAnswer = 0;
int userRemainder, correctRemainder;
int x = 0;
int temporaryNum1, temporaryNum2;
int range;
int randomNumber;
public static void main (String args[]){
MathIsSuperFun1 lab = new MathIsSuperFun1();
lab.init();
}
public void init(){
getName();
pickDifficulty();
pickOperation();
for(int x = 0; x < 10; x++)
{
System.out.println("\t\t\t~~~~~~~PROBLEM NUMBER" + (x + 1) + "~~~~~~~~");
assignNum();
getProblem();
checkAnswer();
}
}
//GET PLAYER NAME USING PANE
public static String getName(){
String playerName;
playerName = JOptionPane.showInputDialog(null, "Welcome!\nEnter your name and press OK.", "Math Is Super Fun!", JOptionPane.QUESTION_MESSAGE);
System.out.println("Do your best," + playerName + "!");
return playerName;
}
//GET PROBLEM BASED ON OPERATION
public void getProblem(){
switch(operation){
case 1:
System.out.println(randomNum1 + "+" + randomNum2 + "= ?\n");
correctAnswer = randomNum1 + randomNum2;
break;
case 2:
System.out.println(randomNum1 + "-" + randomNum2 + "= ?\n");
correctAnswer = randomNum1-randomNum2;
break;
case 3:
System.out.println(randomNum1 + "*" + randomNum2 + "= ?\n");
correctAnswer = randomNum1*randomNum2;
break;
case 4:
System.out.println(randomNum1 + "/" + randomNum2 + "= ?\n");
correctAnswer = randomNum1/randomNum2;
correctRemainder = randomNum1%randomNum2;
break;
}
System.out.print("Answer: ");
userAnswer = input.nextInt();
if(operation == 4){
System.out.print("Remainder: ");
userRemainder = input.nextInt();
}
return 0;
}
//PICK DIFFICULTY USING DIALOG
public void pickDifficulty(){
int choice = 0;
System.out.println("1 - Child's Play\n2 - No Sweat\n3 - Bitter\n4 - Cold-blooded\n5 - Brutal\n6 - Genius");
choice = input.nextInt();
}
//PICK OPERATIONS
public void pickOperation(){
int operation = 0;
System.out.println("1 - Addition\n2 - Subtraction\n3 - Multiplication\n4 - Division ");
operation = input.nextInt();
}
//GET NUMBER RANGE BASED ON DIFFICULTY
public int numberRange(){
int range = 0;
switch(choice){
case 1:
range = 100;
break;
case 2:
range = 1000;
break;
case 3:
range = 10000;
break;
case 4:
range = 100000;
break;
case 5:
range = 1000000;
break;
case 6:
range = 10000000;
break;
}
return range;
}
//GET CORRECT RANDOM RESPONSE USING CASE SWITCH BASED ON GETRANDOM METHOD
public void correctResponse(){
String responseCorrect = "";
switch (getRandom(5)){
case 1:
responseCorrect = "Correct. Keep up the good work!";
break;
case 2:
responseCorrect = "Correct. Keep aiming higher!";
break;
case 3:
responseCorrect = "Correct. Well done!";
break;
case 4:
responseCorrect = "Correct. Nice work!";
break;
case 5:
responseCorrect = "Correct. We're almost there!";
break;
}
System.out.println(responseCorrect);
correctAnswers += 1;
}
//GET WRONG RANDOM RESPONSE USING CASE SWITCH BASED ON GETRANDOM METHOD
public String wrongResponse(){
String responseWrong = "";
switch (getRandom(5)){
case 1:
responseWrong = "Wrong. Don't give up!";
break;
case 2:
responseWrong = "Wrong. You can do it!";
break;
case 3:
responseWrong = "Wrong. Try again puny human!";
break;
case 4:
responseWrong = "Wrong. You must be really weak at math!";
break;
case 5:
responseWrong = "Wrong. I pity you!";
break;
}
System.out.println(responseWrong);
System.out.println("The correct answer is:" + correctAnswer);
if(operation == 4)
System.out.println("Correct Remainder: " + correctRemainder);
return responseWrong;
}
public void checkAnswer(){
if(operation != 4 && userAnswer == correctAnswer){
correctResponse();
}
else if(operation == 4 && userAnswer == correctAnswer && userRemainder == correctRemainder){
correctResponse();
}
else{
wrongResponse();
}
}
public void assignNum(){
int temporaryNum1 = getRandom(numberRange());
int temporaryNum2 = getRandom(numberRange());
while(operation == 4 && temporaryNum1 == 0){
temporaryNum1 = getRandom(numberRange());
}
while(operation == 4 && temporaryNum2 == 0){
temporaryNum2 = getRandom(numberRange());
}
if(temporaryNum1 > temporaryNum2)
{
randomNum1 = temporaryNum1;
randomNum2 = temporaryNum2;
}
else
{
randomNum1 = temporaryNum2;
randomNum2 = temporaryNum1;
}
}
public int getRandom(int range){
randomNumber = (int)Math.floor((Math.random()*range)+1);
return randomNumber;
}
}

The reason your questions are not outputting is simple.
public void pickOperation(){
int operation = 0;
System.out.println("1 - Addition\n2 - Subtraction\n3 - Multiplication\n4 - Division ");
operation = input.nextInt();
}
You are creating a local variable, operation, and assigning the input value to it. This means that the field, operation, is never set, so when it comes to the switch statement in your getProblem method, it doesn't output anything because it doesn't match the switch statement.
To fix this, simply remove the int operation = 0; declaration.
Edit
Just noticed the same problem with your pickDifficulty method. I would strongly recommend you have a look at this tutorial on scope in Java.
Explanation of your Problem
Okay. So let's look at your code:
public void pickOperation(){
int operation = 0;
// Declare an int, called 'operation'.
System.out.println("1 - Addition\n2 - Subtraction\n3 - Multiplication\n4 - Division ");
// Set the newly declared value to an int from the keyboard.
operation = input.nextInt();
}
As soon as this method is finished, the value inside operation is destroyed. The reason why it isn't staying in your field int operation, is because you declared a more local operation variable. By removing the int operation = 0; at the start of this method, you force the JVM to look for the next available variable named operation in your class, which is in the field. That's why, when you remove the first assertion statement, your value for operation will stick around.

the problem is : int operation = 0; you need to take the value of the operation in operation variable which you create it in Main
Try this :
import java.util.Random;
import java.util.*;
import java.util.Scanner;
import javax.swing.JOptionPane;
import java.lang.Math;
public class Main {
Scanner input = new Scanner(System.in);
int correctAnswers;
int randomNum1;
int randomNum2;
int choice;
int corrrectAnswers, wrongAnswers;
String playerName = "";
int operation;
int userAnswer;
int correctAnswer = 0;
int userRemainder, correctRemainder;
int x = 0;
int temporaryNum1, temporaryNum2;
int range;
int randomNumber;
public static void main(String args[]) {
Main lab = new Main();
lab.init();
}
public void init() {
getName();
pickDifficulty();
pickOperation();
for (int x = 0; x < 10; x++) {
System.out.println("\t\t\t~~~~~~~PROBLEM NUMBER" + (x + 1) + "~~~~~~~~");
assignNum();
getProblem();
getAnswers();
checkAnswer();
}
}
//GET PLAYER NAME USING PANE
public static String getName() {
String playerName;
playerName = JOptionPane.showInputDialog(null, "Welcome!\nEnter your name and press OK.", "Math Is Super Fun!", JOptionPane.QUESTION_MESSAGE);
System.out.println("Do your best," + playerName + "!");
return playerName;
}
//GET PROBLEM BASED ON OPERATION
public void getProblem() {
switch (operation) {
case 1:
System.out.println(randomNum1 + "+" + randomNum2 + "= ?\n");
correctAnswer = randomNum1 + randomNum2;
break;
case 2:
System.out.println(randomNum1 + "-" + randomNum2 + "= ?\n");
correctAnswer = randomNum1 - randomNum2;
break;
case 3:
System.out.println(randomNum1 + "*" + randomNum2 + "= ?\n");
correctAnswer = randomNum1 * randomNum2;
break;
case 4:
System.out.println(randomNum1 + "/" + randomNum2 + "= ?\n");
correctAnswer = randomNum1 / randomNum2;
correctRemainder = randomNum1 % randomNum2;
break;
}
System.out.print("Answer: ");
userAnswer = input.nextInt();
if (operation == 4) {
System.out.print("Remainder: ");
userRemainder = input.nextInt();
}
// return 0;
}
//PICK DIFFICULTY USING DIALOG
public void pickDifficulty() {
System.out.println("1 - Child's Play\n2 - No Sweat\n3 - Bitter\n4 - Cold-blooded\n5 - Brutal\n6 - Genius");
choice = input.nextInt();
}
//PICK OPERATIONS
public void pickOperation() {
System.out.println("1 - Addition\n2 - Subtraction\n3 - Multiplication\n4 - Division ");
operation = input.nextInt();
}
//GET NUMBER RANGE BASED ON DIFFICULTY
public int numberRange() {
int range = 0;
switch (choice) {
case 1:
range = 100;
break;
case 2:
range = 1000;
break;
case 3:
range = 10000;
break;
case 4:
range = 100000;
break;
case 5:
range = 1000000;
break;
case 6:
range = 10000000;
break;
}
return range;
}
//GET CORRECT RANDOM RESPONSE USING CASE SWITCH BASED ON GETRANDOM METHOD
public void correctResponse() {
String responseCorrect = "";
switch (getRandom(5)) {
case 1:
responseCorrect = "Correct. Keep up the good work!";
break;
case 2:
responseCorrect = "Correct. Keep aiming higher!";
break;
case 3:
responseCorrect = "Correct. Well done!";
break;
case 4:
responseCorrect = "Correct. Nice work!";
break;
case 5:
responseCorrect = "Correct. We're almost there!";
break;
}
System.out.println(responseCorrect);
correctAnswers += 1;
}
//GET WRONG RANDOM RESPONSE USING CASE SWITCH BASED ON GETRANDOM METHOD
public String wrongResponse() {
String responseWrong = "";
switch (getRandom(5)) {
case 1:
responseWrong = "Wrong. Don't give up!";
break;
case 2:
responseWrong = "Wrong. You can do it!";
break;
case 3:
responseWrong = "Wrong. Try again puny human!";
break;
case 4:
responseWrong = "Wrong. You must be really weak at math!";
break;
case 5:
responseWrong = "Wrong. I pity you!";
break;
}
System.out.println(responseWrong);
System.out.println("The correct answer is:" + correctAnswer);
if (operation == 4) {
System.out.println("Correct Remainder: " + correctRemainder);
}
return responseWrong;
}
public void checkAnswer() {
if (operation != 4 && userAnswer == correctAnswer) {
correctResponse();
} else if (operation == 4 && userAnswer == correctAnswer && userRemainder == correctRemainder) {
correctResponse();
} else {
wrongResponse();
}
}
public void assignNum() {
int temporaryNum1 = getRandom(numberRange());
int temporaryNum2 = getRandom(numberRange());
while (operation == 4 && temporaryNum1 == 0) {
temporaryNum1 = getRandom(numberRange());
}
while (operation == 4 && temporaryNum2 == 0) {
temporaryNum2 = getRandom(numberRange());
}
if (temporaryNum1 > temporaryNum2) {
randomNum1 = temporaryNum1;
randomNum2 = temporaryNum2;
} else {
randomNum1 = temporaryNum2;
randomNum2 = temporaryNum1;
}
}
public int getRandom(int range) {
randomNumber = (int) Math.floor((Math.random() * range) + 1);
return randomNumber;
}
private void getAnswers() {
////////////////Not yet implemented";
}
}

Related

How do I store previous used questions from ArrayA in ArrayB so that they can't be used again?

Where and how do I take the already used questions and store them in a new array of 10 so the questions are not used again?
I also have the issue that it shoots out 11 questions before stopping.
I hope this enough code to give enough context. I have 359 lines of code, so not sure how much is needed to help.
public static void main(String[] args) {//Beginning MAIN method braces
String firstName;
String lastName;
String major;
String level;
int correctCounter = 0;
int incorrectCounter = 0;
Scanner input = new Scanner(System.in);
System.out.println("Please enter the following information:");
System.out.print("First name: ");
firstName = input.next();
System.out.print("Last name: ");
lastName = input.next();
System.out.print("Your Major: ");
major = input.next();
System.out.print("College Level(Freshman, Sophmore, Junior, Senior): ");
level = input.next();
System.out.println();
//A string Array of 20 questions to be passed to the method
String[] questions = new String[20];
questions[0] = "True/False: Cost is a potential disadvantage of teamwork?";
questions[1] = "Ability is NOT a major aspect of culture that affects. True or False"
+ " communication.";
questions[2] = "Which one is NOT a common technology used in meetings? \n"
+ "A. Workgroup messaging\n"
+ "B. Cellphones\n"
+ "C. Teleconferencing\n"
+ "D. Videoconferencing";
questions[3] = "What is the first step in the listening process?\n"
+ "A. Evaluating\n"
+ "B. Remembering\n"
+ "C. Responding\n"
+ "D. Receiving\n"
+ "E. Decoding";
questions[4] = "______ is the process of transferring information and "
+ "meaning betweem senders and receivers using one or more"
+ "written, oral, visual, or digital media. ";
questions[5] = "______ are the accepted principles of conduct that govern"
+ "behavior within a society. ";
questions[6] = "The listening process involves how many steps?";
questions[7] ="iTranslate translates more than __ languages and features "
+ "voice input and output.";
questions[8] = "What is 1/4 (one-fourth) in decimal form?";
questions[9] = "What is the normal temperature for an adult, in `F?";
questions[10] = "A kite is stuck in the branches of a tree. If the "
+ "kite's 90 foot string makes an angle of 22 degrees to the ground,"
+ "calculate the distance in feet between the kite and the ground.";
questions[11] = "If y=cos x, then what is the maximum value of y?";
questions[12] = "What is 6^3";
questions[13] = "What is 3^6?";
questions[14] = "Round 672.4 to the nearest whole number.";
questions[15] = " Round 14.6 to the nearest whole number.";
questions[16] = "What is the max value of 15 32 10 99 87";
questions[17] = "What is the min value of 15 32 10 99 87";
questions[18] = "Groupthink occurs when peer preasure causes individual "
+ "team members to withhold contrary _____ and to go along with "
+ "decisions they don't really believe in. ";
questions[19] = "Most people want to avoid letting others down, and "
+ "participating in teams creates a built-in sense of _______"
+ "to others. ";
returning(questions, correctCounter, incorrectCounter);
//Method call for TESTREPORT
report(firstName, lastName, major, level, correctCounter, incorrectCounter);
}//Main end
public static double returning(String[] questions, int correctCounter, int incorrectCounter){//Beginning RETURN method start
Scanner input = new Scanner(System.in);
//Answers to the 20 questions stored in variables
String answer0 = "True"; //Boolean answer
String answer1 = "False";//Boolean answer
char answer2 = 'B';//char answer
char answer3 = 'D';//char answer
String answer4 = "Communication";//fill in the answer
String answer5 = "Ethics";//fill in the answer
int answer6 = 5; //int answer
int answer7 = 80;//int answer
double answer8 = .25;//double answer
double answer9 = 98.6;//double answer
double answer10 = 33.71; //trigonometric question
double answer11 = 1; //trigonometric question
int answer12 = 216; //exponent question
int answer13 = 729; //exponent question
int answer14 = 672; //rounding question
int answer15 = 15; //rounding question
double answer16 = 99; //max value question
double answer17 = 10; //min value question
String answer18 = "opinions"; //free question
String answer19 = "accountability";//free question
int correctCount = 0;
int incorrectCount =0;
for(int i=0; i<10; i++){//Beginning FOR loop for switch statement
correctCount++;
incorrectCount++;
//Random Number generator
int randomNumber = 0 + (int)(Math.random() * 20);
//Switch statement
switch (randomNumber){
case 0 : System.out.println(questions[0]);
String q0 = input.nextLine();
if (q0.equalsIgnoreCase(answer0)){
correctCount++;
}
else {
incorrectCount++;
}
break;
case 1 : System.out.println(questions[1]);
String q1 = input.nextLine();
if (q1.equalsIgnoreCase(answer1)){
correctCount++;
}
else {
incorrectCount++;
}
break;
case 2 : System.out.println(questions[2]);
String q2 = input.nextLine();
if (q2.equals(answer2)){
correctCount++;
}
else {
incorrectCount++;
}
break;
case 3 : System.out.println(questions[3]);
String q3 = input.nextLine();
if (q3.equals(answer3)){
correctCount++;
}
else {
incorrectCount++;
}
break;
case 4 : System.out.println(questions[4]);
String q4 = input.nextLine();
if (q4.equalsIgnoreCase(answer4)){
correctCount++;
}
else {
incorrectCount++;
}
break;
case 5 : System.out.println(questions[5]);
String q5 = input.nextLine();
if (q5.equalsIgnoreCase(answer5)){
correctCount++;
}
else {
incorrectCount++;
}
break;
case 6 : System.out.println(questions[6]);
String q6 = input.nextLine();
if (q6.equals(answer6)) {
correctCount++;
}
else {
incorrectCount++;
}
break;
case 7 : System.out.println(questions[7]);
String q7 = input.nextLine();
if (q7.equals(answer7)) {
correctCount++;
}
else {
incorrectCount++;
}
break;
case 8 : System.out.println(questions[8]);
String q8 = input.nextLine();
if (q8.equals(answer8)) {
correctCount++;
}
else {
incorrectCount++;
}
break;
case 9 : System.out.println(questions[9]);
String q9 = input.nextLine();
if (q9.equals(answer9)) {
correctCount++;
}
else {
incorrectCount++;
}
break;
case 10: System.out.println(questions[10]);
String q10 = input.nextLine();
if (q10.equals(answer10)) {
correctCount++;
}
else {
incorrectCount++;
}
break;
case 11: System.out.println(questions[11]);
String q11 = input.nextLine();
if (q11.equals(answer11)) {
correctCount++;
}
else {
incorrectCount++;
}
break;
case 12: System.out.println(questions[12]);
String q12 = input.nextLine();
if (q12.equals(answer12)){
correctCount++;
}
else {
incorrectCount++;
}
break;
case 13: System.out.println(questions[13]);
String q13 = input.nextLine();
if (q13.equals(answer13)) {
correctCount++;
}
else {
incorrectCount++;
}
break;
case 14: System.out.println(questions[14]);
String q14 = input.nextLine();
if (q14.equals(answer14)){
correctCount++;
}
else {
incorrectCount++;
}
break;
case 15: System.out.println(questions[15]);
String q15 = input.nextLine();
if (q15.equals(answer15)) {
correctCount++;
}
else {
incorrectCount++;
}
break;
case 16: System.out.println(questions[16]);
String q16 = input.nextLine();
if (q16.equals(answer16)){
correctCount++;
}
else {
incorrectCount++;
}
break;
case 17: System.out.println(questions[17]);
String q17 = input.nextLine();
if (q17.equals(answer17)) {
correctCount++;
}
else {
incorrectCount++;
}
break;
case 18: System.out.println(questions[18]);
String q18 = input.nextLine();
if (q18.equalsIgnoreCase(answer18)){
correctCount++;
}
else {
incorrectCount++;
}
break;
case 19: System.out.println(questions[19]);
String q19 = input.nextLine();
if (q19.equalsIgnoreCase(answer19)) {
correctCount++;
}
else {
incorrectCount++;
}
break;
default : System.out.println("Error");
}//End SWITCH statment
}//End FOR loop for switch statement
return correctCount + incorrectCount;
}//End RETURN method braces
public static void report(String firstName, String lastName, String major,
String level, int correctCount, int incorrectCount){//Beginning TESTREPORT method braces
double percentCorrect = (correctCount/10);
//print students input information, number of correct and incorrect +
//questions and %correct
System.out.println("Name: "+ firstName + " " + lastName);
System.out.println("Major: " + major);
System.out.println("College Level: " + level);
System.out.println("Questions answered correctly: " + correctCount);
System.out.println("Questions answered incorrectly: " + incorrectCount);
System.out.println("Percentage correct: " + percentCorrect);
}//End TESTREPORT method braces
}//End CLASS method braces
If the intent is to display questions in a random order only once, then what you could do is shuffle the indexes to be presented in a queue structure.
The following method creates a list of the indexes from 0 to count - 1, shuffles them and returns a Queue that when poll() is called will return the next index to offer up. Keep calling this until null is returned for no more questions.
import java.util.ArrayDeque;
import java.util.Collections;
import java.util.List;
import java.util.stream.IntStream;
import static java.util.stream.Collectors.toList;
private Queue<Integer> questionOrder(int count) {
List<Integer> indexes = IntStream.range(0, count)
.mapToObj(n -> n)
.sorted()
.collect(toList());
Collections.shuffle(indexes);
return new ArrayDeque<>(indexes);
}
You could then use this as:
private void askQuestions(String[] questions) {
Queue<Integer> order = questionOrder(questions.length);
System.out.println(order);
Integer index;
while ((index = order.poll()) != null) {
String question = questions[index];
System.out.println(question);
// do your presentation logic.
}
}

How would I go about breaking down this code into a new method in this Java program?

I've got an assignment that requires me to have the user guess a random color generated by the program, then display the total results. My code works fine, but I'm wanting to break it down into another method. Specifically, the section that receives input from the user. I want that in its own method, then the main method only displaying results. I tried creating a new object for the user's color choice, but that didn't work. I'm not sure what to do next. Thank you for your time!
import java.util.Scanner;
import java.util.Random;
public class ESP
{
public static void main(String[] args)
{
String colorChoice;
int correct = 0, incorrect = 0;
Scanner keyboard = new Scanner(System.in);
for(int i = 1; i <= 10; i++)
{
System.out.print("Choose either red, green, blue, orange or yellow! ");
colorChoice = keyboard.nextLine();
System.out.println("You chose: " + colorChoice);
String computerChoice = computerColorChoice();
System.out.println("The computer chose: " + computerChoice);
if(colorChoice.equalsIgnoreCase(computerChoice))
{
correct++;
}
else
{
incorrect++;
}
}
System.out.println("Amount of times you guessed correctly: " + correct);
System.out.println("Amount of times you guess incorrectly: " + incorrect);
}
public static String computerColorChoice()
{
String randomColor;
int randomNumber;
Random random = new Random();
randomNumber = random.nextInt(4);
switch (randomNumber)
{
case 0:
randomColor = "Red";
break;
case 1:
randomColor = "Green";
break;
case 2:
randomColor = "Blue";
break;
case 3:
randomColor = "Orange";
break;
case 4:
randomColor = "Yellow";
break;
default:
randomColor = " ";
}
return randomColor;
}
}
You can add a method for the user choice:
public static String userColorChoice()
{
Scanner keyboard = new Scanner(System.in);
System.out.print("Choose either red, green, blue, orange or yellow! ");
String userColorChoice = keyboard.nextLine();
System.out.println("You chose: " + userColorChoice);
return userColorChoice;
}
Also you can update your computerColorChoice as follows:
public static String computerColorChoice()
{
String randomColor;
int randomNumber;
Random random = new Random();
randomNumber = random.nextInt(4);
switch (randomNumber)
{
case 0:
randomColor = "Red";
break;
case 1:
randomColor = "Green";
break;
case 2:
randomColor = "Blue";
break;
case 3:
randomColor = "Orange";
break;
case 4:
randomColor = "Yellow";
break;
default:
randomColor = " ";
}
System.out.println("The computer chose: " + randomColor);
return randomColor;
}
And finally update your main:
public static void main(String[] args)
{
int correct = 0, incorrect = 0;
for(int i = 1; i <= 10; i++)
{
if(userColorChoice().equalsIgnoreCase(computerColorChoice()))
correct++;
else
incorrect++;
}
System.out.println("Amount of times you guessed correctly: " + correct);
System.out.println("Amount of times you guess incorrectly: " + incorrect);
}
I hope this help you.

How to fix inputting the user's info twice?

The program ask for a month and it could be a string or int. In the isDigitsOrSpecial method, it works and it has the same format in my method isString. The difference is that when I want to enter the month in a string way (ex.january), it will ask me twice. So, I don't know what to do. I tried a lot of ways but it doesn't work. Do you have any suggestions?
Here's my full code. You can try to run it, and see the problem where you have to input twice the name of the month in a string way.
I would really appreciate any of your suggestions.
package Electronic_payment_process;
import java.util.InputMismatchException;
import java.util.Scanner;
public class practice {
static String s;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
float current = 0, recent = 0, difference, multiply;
String month, recents, currents = null;
System.out.println("The month could be a number or a name.");
System.out.println("Example: (01-12) or (JAN – dec)");
// for the validation of due month user’s input
do {
System.out.print("\nEnter a month: ");
month = scan.next();
if (isDigitsOrSpecial(month)) {
System.out.print("proceed");
break;
} else if (isString(month)) {
System.out.print("proceed");
break;
}
} while (true);
// for the validation of current meter reading
do {
System.out.print("\nEnter current reading: ");
try {
current = scan.nextFloat();
System.out.println("proceed");
currents = String.format("%.2f", current);
if (current <= 0) {
System.out.println("Invalid input");
}
} catch (InputMismatchException a) {
System.out.println("Must enter a number");
scan.next();
}
} while (current <= 0);
// for the validation of recent meter reading
do {
System.out.print("Enter recent reading: ");
try {
recent = scan.nextFloat();
if (recent < current) {
System.out.println("proceed");
recents = String.format("%.2f", recent);
break;
} else {
System.out.println("recent must be less than current");
}
} catch (InputMismatchException a) {
System.out.println("Must enter a number");
scan.next();
}
} while (true);
difference = current - recent;
multiply = difference * 50;
System.out.println("====================================================================================");
System.out.println("MONTH " + " RECENT " + "CURRENT " + "TOTAL USAGE " + "Price per unit " + "TOTAL AMOUNT ");
System.out.println((s + (" ") + recents + (" kW") + (" ") + currents + (" kW") + (" ") + difference + (" ") + ("50php") + (" ") + multiply));
}
public static boolean isDigitsOrSpecial(String month) {
Scanner scan = new Scanner(System.in);
if (month != null) {
for (char ch : month.toCharArray()) {
if (Character.isLetter(ch)) {
return false;
}
}
}
int we = Integer.parseInt(month);
s = Integer.toString(we);
if (null == month) {
s = scan.nextLine();
} else switch (we) {
case 01:
s = "January";
break;
case 02:
s = "February";
break;
case 03:
s = "March";
break;
case 04:
s = "April";
break;
case 05:
s = "May";
break;
case 06:
s = "June";
break;
case 07:
s = "July";
break;
case 8:
s = "August";
break;
case 9:
s = "September";
break;
case 10:
s = "October";
break;
case 11:
s = "November";
break;
case 12:
s = "December";
break;
default:
System.out.println("You have entered an invalid number of month");
}
return true;
}
public static boolean isString(String month) {
Scanner scan = new Scanner(System.in);
if (null != month) {
char[] chars = month.toCharArray();
s = scan.nextLine();
for (char c : chars) {
if (!Character.isLetter(c)) {
return false;
}
}
}
if (!(month.length() >= 3)) {
System.out.println("Name of month must be at least 3 letters.Please try again");
return false;
} else if (month.startsWith("jan") || month.startsWith("JAN") || month.startsWith("Jan")) {
s = "January";
}
return true;
}
}
I see we have added additional scanner statements inside isDigit or isString methods. I have removed them and it looks good to me.
public static boolean isDigitsOrSpecial(String month) {
if (month != null) {
for (char ch : month.toCharArray()) {
if (Character.isLetter(ch)) {
return false;
}
}
}
int we = Integer.parseInt(month);
switch (we) {
case 01:
s = "January";
break;
case 02:
s = "February";
break;
case 03:
s = "March";
break;
case 04:
s = "April";
break;
case 05:
s = "May";
break;
case 06:
s = "June";
break;
case 07:
s = "July";
break;
case 8:
s = "August";
break;
case 9:
s = "September";
break;
case 10:
s = "October";
break;
case 11:
s = "November";
break;
case 12:
s = "December";
break;
default:
System.out.println("You have entered an invalid number of month");
return false;
}
return true;
}
public static boolean isString(String month)
{
if (null != month) {
char[] chars = month.toCharArray();
for (char c : chars) {
if (!Character.isLetter(c)) {
return false;
}
}
}
if (!(month.length() >= 3)) {
System.out.println("Name of month must be at least 3 letters.Please try again");
return false;
}
return true;
}

Boolean won't initialize after an if statement and still coming as false when called from a different class in Java

I am trying to make a text based game. I am putting somethings I have learned to practice.
When you read about my problem you will probably be confused. My problem contains methods that have yet not been explained in what they do. This is so it does not get too confusing. Each piece of code will have a description of what methods it has and what they do.
My problem: I have a class named CharStartingPoint, this class is the main starting point to my game. Inside the class I call the choose(); method which is a method from class CharObe then the settingNPC(); and bbs(); methods are called, both of those methods are from CharWosna class. The bbs(); method just returns a boolean referenced, player1HasShieldBo, and prints out string player1HasShield. (player1HasShield and player1HasShieldBo are from class CharObe and player2HasShieldBo is from class CharWosna). When choose(); is called, and the player types yes to the question "Do you have a shield?", if the if statement sees if the user typed yes it will call a method named setPlayerShieldTrue(boolean HasSield); and pass player1HasShieldBo which sets player1HasShieldBo = true. If I type System.out.println(player1.player1HasShieldBo); and
System.out.println(player1.player1HasShield); from class CharStartingPoint, it prints out true and yes. Class CharStartingPoint has no problem accessing CharObe's variables. When CharWosna class tries accessing CharObe's variable, CharWosna can access them but they are not initialized, WHY????? for this problem to be seen, when method settingNPC(); is called, player2HasShieldBo is set to true if player2HasShieldBo is true. In this case player2HasShieldBo is set to false because class CharWosna accessed player1HasShieldBo from class CharObe, but it is not initialized although it had been initialized earlier. String player1HasShield prints out null when accessed from class CharWosna. WHY????
player1 is of type CharObe and has a constructor of CharObe.
player2 is of type CharWosna and has a constructor of CharWosna.
Here is my code by chunks and explained
Class CharObe:
The choose(); method: The choose method asks the user if they have a shield or not. If the user types no to the question, do you have a shield? the boolean player1HasShieldBo is set to false. If the user types yes, then inside the if statement the setPlayerShieldTrue(); method is called.
The setPlayerShieldTrue(boolean HasSield); method: this method takes in a boolean. Inside this boolean the local variable HasSield is set to true which then is assigned to player1HasShieldBo.
The returnIfHasShield(); method: this method just returns boolean player1HasShieldBo
import java.util.Scanner;
public class CharObe implements CharInterface {
String player1HasShield;
boolean player1HasShieldBo = false;
int player1ShieldLevel;
int player1ShieldHealth;
boolean valid = false;
Scanner keyBoard = new Scanner(System.in);
public void choose(){
do{
//asking the user if they have a shield or not
System.out.println("\ndo you have a shield? (if yes only type" +
"'yes' if no type 'no')");
System.out.print("Shield? yes or no? > ");
if(keyBoard.hasNext()){
player1HasShield = keyBoard.next();
if(player1HasShield.equalsIgnoreCase("yes")){
System.out.println("You have a SHIELD!!!");
setPlayerShieldTrue(player1HasShieldBo);
System.out.println("What is your shield Level? (Only" +
"numbers 1-5)");
do{
System.out.print("Shield level > ");
if(keyBoard.hasNextInt()){
player1ShieldLevel = keyBoard.nextInt();
if(player1ShieldLevel >= 1 && player1ShieldLevel <= 5){
valid = false;
}else{
System.out.println("PLEASE only numbers from 1-" +
" 5");
valid = true;
}
}else{
System.out.println("Only numbers are valid");
keyBoard.next();
valid = true;
}
}while(valid);
}else{
System.out.println("You did not type 'yes'"
+ " now you dont have a shield...");
player1ShieldLevel = 0;
valid = false;
}
}
}while(valid);
if(player1HasShieldBo){
switch(player1ShieldLevel){
case 1: player1ShieldHealth = 5; break;
case 2: player1ShieldHealth = 7; break;
case 3: player1ShieldHealth = 15; break;
case 4: player1ShieldHealth = 20; break;
case 5: player1ShieldHealth = 30; break;
}
}else{
player1ShieldHealth = 0;
}
if(player1HasShieldBo){
System.out.println(
"\nPlayer1's shield level: "+ player1ShieldLevel +
"\nplayer1's shield HP: " + player1ShieldHealth);
}else{
System.out.println(
"\nPlayer1's shield level: "+ player1ShieldLevel +
"\nplayer1's damage: " + player1Damage);
}
System.out.println("\nSetting player2's variables...");
}
public void setPlayerShieldTrue(boolean HasSield){
HasSield = true;
player1HasShieldBo = HasSield;
}
public boolean returnIfHasShield(){
return player1HasShieldBo;
}
}
Method settingNPC();, this method sets boolean player2HasShieldBo = true if what is returned from method returnIfHasShield(); is true. If what is returned is not true then player2HasShield will not be initialized and will stay false. That is the problem, although what is returned from returnIfHasShield(); is player1HasShieldBo equaled to true, it will always returns false when access by CharWosna class.
Method bbs();, this method prints out player1HasShieldBo and player1HasShield which come out to false and null because they are not initialized altough they had been earlier, why does this happen?
import java.util.Random;
public class CharWosna implements CharInterface{
//player2 variables
boolean player2HasShieldBo = true;
int player2ShieldLevel;
int player2ShieldHealth;
CharObe toGet = new CharObe();
public void settingNPC(){
if(toGet.returnIfHasShield()){
player2HasShieldBo = true;
player2ShieldLevel = toGet.player1ShieldLevel;
player2ShieldHealth = toGet.player1ShieldHealth;
System.out.println("Wosna's shield level: " + player2ShieldLevel +
"\nWosna's shield health: " + player2ShieldHealth
);
}else{
player2ShieldHealth = 0;
System.out.println("To have a fair fight, Wosna, like you, will"
+ "not have a shield.");
}
}
public void bbs(){
System.out.println(toGet.player1HasShieldBo + " " +
toGet.player1HasShield);
}
}
Class CharStarting point, this class calls all methods
I found out the reason that CharObe's variable are initialized and can be accessed nicely in this class, it's because this class calls the choose(); method.
public class CharStartingPoint {
public static void main(String[] args) {
System.out.println("Welcome! Fellow traveler.");
System.out.println("please input proper information in order to"
+ procceed to fight.\n");
CharObe player1 = new CharObe();
CharWosna player2 = new CharWosna();
player1.choose();
player2.settingNPC();
player2.bbs();
System.out.println(player1.player1HasShieldBo);
System.out.println(player1.player1HasShield);
}
}
Interface CharInterface, this is not yet used.
public interface CharInterface {
int hurt(int curHealth, int hurting);
int damage(int hitDamage);
int shield(int shieldHealth, int shielLevel);
}
*Another problem is when i create an object in class CharObe, it straight up gives me a java.lang.StackOverflowError, why is that. *
I dont know why I have all these problems. I may just have somethings that are very simple that have been messing up my program, I dont know.
Things I have tried
-directly accessing the boolean player1HasShieldBo from class CharWosna
-creating another boolean having it have the value of player1HasShieldBo(when player1HasShieldBo equaled to true)
-initializing player1HasShieldBo from class CharObe (did not turn out as wanted, it always equaled true)
if you want to see all my code here it is.
insterface
public interface CharInterface {
int hurt(int curHealth, int hurting);
int damage(int hitDamage);
int shield(int shieldHealth, int shielLevel);
}
class CharStartingPoint
public class CharStartingPoint {
public static void main(String[] args) {
System.out.println("Welcome! Fellow traveler.");
System.out.println("please input proper information in order to"
+ " procceed to fight.\n");
CharObe player1 = new CharObe();
CharWosna player2 = new CharWosna();
player1.choose();
player2.settingNPC();
player2.bbs();
System.out.println(player1.player1HasShieldBo);
System.out.println(player1.player1HasShield);
}
}
class CharObe
import java.util.Scanner;
public class CharObe implements CharInterface {
int player1Level;
int player1Damage;
int player1Health;
String player1HasShield;
boolean player1HasShieldBo = false;
int player1ShieldLevel;
int player1ShieldHealth;
boolean valid = false;
Scanner keyBoard = new Scanner(System.in);
CharObe f = new CharObe();
//Letting the user pick the players level and whether it has a shield or
not.
public void choose(){
System.out.println("what is Your player level? (number from 1-20)");
do{
//asking user for the level of their player
System.out.print("Enter level here > ");
if(keyBoard.hasNextInt()){
player1Level = keyBoard.nextInt();
if(player1Level >= 1 && player1Level <= 20){
valid = false;
}else{
System.out.println("Enter a number between 1 and 20!");
valid = true;
}
}else{
System.out.println("Only numbers are valid");
keyBoard.next();
valid = true;
}
}while(valid);
do{
//asking the user if they have a shield or not
System.out.println("\ndo you have a shield? (if yes only type" +
"'yes' if no type 'no')");
System.out.print("Shield? yes or no? > ");
if(keyBoard.hasNext()){
player1HasShield = keyBoard.next();
if(player1HasShield.equalsIgnoreCase("yes")){
System.out.println("You have a SHIELD!!!");
setPlayerShieldTrue(player1HasShieldBo);
System.out.println("What is your shield Level? (Only" +
"numbers 1-5)");
do{
System.out.print("Shield level > ");
if(keyBoard.hasNextInt()){
player1ShieldLevel = keyBoard.nextInt();
if(player1ShieldLevel >= 1 && player1ShieldLevel <= 5){
valid = false;
}else{
System.out.println("PLEASE only numbers from 1-5");
valid = true;
}
}else{
System.out.println("Only numbers are valid");
keyBoard.next();
valid = true;
}
}while(valid);
}else{
System.out.println("You did not type 'yes'"
+ " now you dont have a shield...");
player1ShieldLevel = 0;
valid = false;
}
}
}while(valid);
switch(player1Level){
case 1: player1Health = 100; player1Damage = 10; break;
case 2: player1Health = 105; player1Damage = 11; break;
case 3: player1Health = 110; player1Damage = 12; break;
case 4: player1Health = 80; player1Damage = 20; break;
case 5: player1Health = 100; player1Damage = 15; break;
case 6: player1Health = 150; player1Damage = 5; break;
case 7: player1Health = 115; player1Damage = 17; break;
case 8: player1Health = 130; player1Damage = 20; break;
case 9: player1Health = 135; player1Damage = 15; break;
case 10: player1Health = 140; player1Damage = 23; break;
case 11: player1Health = 160; player1Damage = 17; break;
case 12: player1Health = 150; player1Damage = 28; break;
case 13: player1Health = 180; player1Damage = 15; break;
case 14: player1Health = 155; player1Damage = 30; break;
case 15: player1Health = 115; player1Damage = 40; break;
case 16: player1Health = 200; player1Damage = 20; break;
case 17: player1Health = 250; player1Damage = 35; break;
case 18: player1Health = 1000; player1Damage = 67; break;
case 19: player1Health = 550; player1Damage = 130; break;
case 20: player1Health = 9999; player1Damage = 479; break;
}
if(player1HasShieldBo){
switch(player1ShieldLevel){
case 1: player1ShieldHealth = 5; break;
case 2: player1ShieldHealth = 7; break;
case 3: player1ShieldHealth = 15; break;
case 4: player1ShieldHealth = 20; break;
case 5: player1ShieldHealth = 30; break;
}
}else{
player1ShieldHealth = 0;
}
if(player1HasShieldBo){
System.out.println(
"\nPlayer1's level: " + player1Level +
"\nPlayer1's Health: " + player1Health +
"\nplayer1's damage: " + player1Damage +
"\nPlayer1's shield level: "+ player1ShieldLevel +
"\nplayer1's shield HP: " + player1ShieldHealth);
}else{
System.out.println(
"\nPlayer1's level: " + player1Level +
"\nPlayer1's Health: " + player1Health +
"\nPlayer1's shield level: "+ player1ShieldLevel +
"\nplayer1's damage: " + player1Damage);
}
System.out.println("\nSetting player2's variables...");
}
public void setPlayerShieldTrue(boolean HasSield){
HasSield = true;
player1HasShieldBo = HasSield;
}
public boolean returnIfHasShield(){
return player1HasShieldBo;
}
#Override
public int hurt(int curHealth, int hurting) {
return curHealth;
}
#Override
public int damage(int hitDamage) {
return hitDamage;
}
#Override
public int shield(int shieldHealth, int shielLevel) {
return 0;
}
}
class CharWosna
import java.util.Random;
public class CharWosna implements CharInterface{
//player2 variables
int player2Level;
int[] player2Damage = {15, 45, 67, 100, 5, 25, 1000};//array
int player2Health[] = {100, 50, 1000, 550, 250, 99, 600};//array
boolean player2HasShieldBo = true;
int player2ShieldLevel;
int player2ShieldHealth;
//CharObe object created for acquiring CharObe's variables in that class
CharObe toGet = new CharObe();
//ran is going to be used to access damage and health randomly
Random ran = new Random();
public void settingNPC(){
//LEVEL, HEALTH, and DAMAGE//
player2Level = ran.nextInt(6) + 1;
System.out.println("\n> Wosna's stats <");
System.out.println(
"\nWosna's level: " + player2Level +
"\nWosna's health: " + player2Health[player2Level] +
"\nWosna's damage: " + player2Damage[player2Level]
);
if(toGet.returnIfHasShield()){
player2HasShieldBo = true;
player2ShieldLevel = toGet.player1ShieldLevel;
player2ShieldHealth = toGet.player1ShieldHealth;
System.out.println("Wosna's shield level: " + player2ShieldLevel +
"\nWosna's shield health: " + player2ShieldHealth
);
}else{
player2ShieldHealth = 0;
System.out.println("To have a fair fight, Wosna, like you, will" +
"not have a shield.");
}
}
public void bbs(){
System.out.println(toGet.player1HasShieldBo + " " +
toGet.player1HasShield);
}
#Override
public int hurt(int curHealth, int hurting) {
return 0;
}
#Override
public int damage(int hitDamage) {
return 0;
}
#Override
public int shield(int shieldHealth, int shielLevel) {
return 0;
}
}
Thank you
First thing, Your code will work for setting the boolean. But you have some mistakes.
The stackOverflow is caused since you create a object of CharObe within the same class as a attribute. So for creating a CharObe object it needs to create a CharObe and so on...
the culprit line: on CharObe class
CharObe f = new CharObe();//remove this
Second thing, you cant just create an object of CharObe in CharWosna just to read the attributes.
This code is culprit too:
//CharObe object created for acquiring CharObe's variables in that class
CharObe toGet = new CharObe();
Instead try passing the player1 object when creating player2 in the constructor.
like this in CharWonsa:
//CharObe object created for acquiring CharObe's variables in that class
CharObe toGet;
public CharWosna(CharObe obe) {
toGet=obe;
}
And finally in the class CharStartingPoint, create objects like this:
CharObe player1 = new CharObe();
CharWosna player2 = new CharWosna(player1);
Another better way is that you maintain a GameContext class seperately and have all the necessary data like players there, and access from there.
You're welcome. Next time be precise with what you ask.

Keeping a total score in Java hangman game

import java.util.Scanner;
import javax.swing.JOptionPane;
public class Hangman {
public static void main(String[] args) {
String playAgainMsg = "Would you like to play again?";
String pickCategoryMsg = "You've tried all the words in this category!\nWould you like to choose another category?";
int winCounter = 0, loseCounter = 0, score = 0;
String[] words;
int attempts = 0;
String wordToGuess;
boolean playCategory = true, playGame = true;
int totalCounter = 0, counter;
while (playCategory && playGame)
{
while (playCategory && playGame) {
words = getWords();
counter = 0;
while (playGame && counter < words.length) {
wordToGuess = words[counter++];
if (playHangman(wordToGuess)) {
winCounter++;
System.out.println("You win! You have won " + winCounter + " game(s)." + " You have lost " + loseCounter + " game(s).");
} else {
loseCounter++;
System.out.println("You lose! You have lost " + loseCounter + " game(s)." + " You have won " + winCounter + " game(s).");
}
if (counter < words.length) playGame = askYesNoQuestion(playAgainMsg);
}
if (playGame) playCategory = askYesNoQuestion(pickCategoryMsg);
}
}
}
public static boolean playHangman(String wordToGuess) {
String[] computerWord = new String[wordToGuess.length()];
String[] wordWithDashes = new String[wordToGuess.length()];
for (int i = 0; i < computerWord.length; i++) {
computerWord[i] = wordToGuess.substring(i, i+1);
wordWithDashes[i] = "_";
}
Scanner in = new Scanner(System.in);
int attempts = 0, maxAttempts = 7;
boolean won = false;
int points = 0;
while (attempts < maxAttempts && !won) {
String displayWord = "";
for (String s : wordWithDashes) displayWord += " " + s;
System.out.println("\nWord is:" + displayWord);
System.out.print("\nEnter a letter or guess the whole word: ");
String guess = in.nextLine().toLowerCase();
if (guess.length() > 1 && guess.equals(wordToGuess)) {
won = true;
} else if (wordToGuess.indexOf(guess) != -1) {
boolean dashes = false;
for (int i = 0; i < computerWord.length; i++) {
if (computerWord[i].equals(guess)) wordWithDashes[i] = guess;
else if (wordWithDashes[i].equals("_")) dashes = true;
}
won = !dashes; // If there are no dashes left, the whole word has been guessed
} else {
drawHangmanDiagram(attempts);
System.out.println("You've used " + ++attempts + " out of " + maxAttempts + " attempts.");
}
}
int score = 0;
score = scoreGame(attempts);
System.out.println("Your score is: " + score);
return won;
}
//should take in a failure int from the main method that increments after every failed attempt
public static void drawHangmanDiagram(int failure)
{
if (failure == 0)
System.out.println("\t+--+\n\t| |\n\t|\n\t|\n\t|\n\t|\n\t|\n\t|\n\t+--");
else if (failure == 1)
System.out.println("\t+--+\n\t| |\n\t| #\n\t|\n\t|\n\t|\n\t|\n\t|\n\t+--");
else if (failure == 2)
System.out.println("\t+--+\n\t| |\n\t| #\n\t| /\n\t|\n\t|\n\t|\n\t|\n\t+--");
else if (failure == 3)
System.out.println("\t+--+\n\t| |\n\t| #\n\t| / \\\n\t|\n\t|\n\t|\n\t|\n\t+--");
else if (failure == 4)
System.out.println("\t+--+\n\t| |\n\t| #\n\t| /|\\\n\t| |\n\t|\n\t|\n\t|\n\t+--");
else if (failure == 5)
System.out.println("\t+--+\n\t| |\n\t| #\n\t| /|\\\n\t| |\n\t| /\n\t|\n\t|\n\t+--");
else if (failure == 6)
System.out.println("\t+--+\n\t| |\n\t| #\n\t| /|\\\n\t| |\n\t| / \\\n\t|\n\t|\n\t+--");
}
// Asks user a yes/no question, ensures valid input
public static boolean askYesNoQuestion(String message) {
Scanner in = new Scanner(System.in);
boolean validAnswer = false;
String answer;
do {
System.out.println(message + " (Y/N)");
answer = in.nextLine().toLowerCase();
if (answer.matches("[yn]")) validAnswer = true;
else System.out.println("Invalid input! Enter 'Y' or 'N'.");
} while (!validAnswer);
return answer.equals("y");
}
public static boolean askForCategory(int category) {
Scanner in = new Scanner(System.in);
boolean validAnswer = false;
String answer;
do {
System.out.println("\nWould you like to play again? (Y/N)");
answer = in.nextLine().toLowerCase();
if (answer.matches("[yn]")) validAnswer = true;
else System.out.println("Invalid input! Enter 'Y' or 'N'.");
} while (!validAnswer);
return answer.equals("y");
}
// Asks the user to pick a category
public static String[] getWords() {
String[] programming = {"java", "pascal", "python", "javascript", "fortran", "cobol"};
String[] sports = {"gymnastics", "badminton", "athletics", "soccer", "curling", "snooker", "hurling", "gaelic", "football", "darts"};
String[] result = {""};
Scanner in = new Scanner(System.in);
boolean validAnswer = false;
String answer;
do {
System.out.println("Pick a category:\n1. Programming\n2. Sports");
answer = in.nextLine().toLowerCase();
if (answer.matches("[1-2]")) validAnswer = true;
else System.out.println("Invalid input! Enter the number of the category you want.");
} while (!validAnswer);
int selection = Integer.parseInt(answer);
switch (selection) {
case 1: result = randomOrder(programming); break;
case 2: result = randomOrder(sports); break;
}
return result;
}
// Sorts a String array in random order
public static String[] randomOrder(String[] array) {
int[] order = uniqueRandoms(array.length);
String[] result = new String[array.length];
for (int i = 0; i < order.length; i++) {
result[i] = array[order[i]];
}
return result;
}
// Generates an array of n random numbers from 0 to n-1
public static int[] uniqueRandoms(int n) {
int[] array = new int[n];
int random, duplicateIndex;
for (int i = 0; i < n; ) {
random = (int) (Math.random() * n);
array[i] = random;
for (duplicateIndex = 0; array[duplicateIndex] != random; duplicateIndex++);
if (duplicateIndex == i) i++;
}
return array;
}
public static int scoreGame(int attempts)
{
int score = 0;
switch (attempts)
{
case 0: score = 70; break;
case 1: score = 60; break;
case 2: score = 50; break;
case 3: score = 40; break;
case 4: score = 30; break;
case 5: score = 20; break;
case 6: score = 10; break;
case 7: score = 0; break;
}
return score;
}
}
I have got it working so that it keeps count of the games won and lost, as well as assigning a score based on the amount of attempts/lives saved but I haven't been able to find a way to get it to keep a total score for all of the games played. Each game unfortunately has a seperate score. If anyone can advise me on a way of doing this, it would be greatly appreciated.
Create an int totalScore variable where winCounter, loseCounter and score are defined. Then increment it after each call to scoreGame()
score = scoreGame(attempts);
totalScore += score;
System.out.println("Your score is: " + score);
If you want to permanently save statistics between sessions then it's a whole nother story. You would need to write your scores to a file after each round and then start your program by reading this score file. It's hardly impossible, but requires a bit more code.

Categories