Having trouble counting down and printing loops - java

So I need my code to print out in increments on 3 user inputs, I have a 2nd java file to use dot notation to execute methods from. So it's supposed to run kinda like this.
Pick > Starting Value - Pick Increment value - Pick > Ending Value
All these are user input and I need to have it if the starting value > then the ending then count up from starting value with user input increments. But if end
import java.util.Scanner;
public class logic {
public static void main(String [] args) {
//new scanner
Scanner input = new Scanner(System.in);
//Data
char ch = 0;
int start = 0;
int end = 0;
int inc = 0;
String printStr = "";
final int SENTINEL = -1;
String menu ="Looping (Demo)" +
"\nStart Value\t [S]" +
"\nIncrement value [I]" +
"\nEnd Value\t [E]" +
"\nFor Looping\t [F]" +
"\nQuit\t\t [Q]" +
"\nEnter Option > ";
while(ch != SENTINEL) {
switch(ch) {
case 'S':
case 's':
start = UtilsDM.readInt("Enter loop start value: ", false);
break;
case 'I':
case 'i':
inc = UtilsDM.readInt("Enter loop increment value: ", false);
break;
case 'E':
case 'e':
end = UtilsDM.readInt("Enter loops end value: ", false);
break;
case 'F':
case 'f':
if(start <= end){
for (int i=start; i<=end; i+=inc) {
System.out.print(i + " ");
}//end loop +
}//end if
else if(start >= end){
for (int i=end; i<=start; i-=inc) {
System.out.print(i + " ");
}//end loop -
}//end else if
System.out.println("\n");
break;
case 'Q':
case 'q':
System.out.println("Terminating upon user command.");
System.exit(0);
break;
default:
System.out.println("Unrecognized character");
break;
}//end switch
ch = UtilsDM.readChar(menu, false);
}//end loop
//computations, algorithms
//outputs, formatting, display
} //end main
}//end class

Change the case 'F' to as follows, i have commented the changes :-
case 'F':
case 'f':
if(start < end || (start < 0 && end < 0 && end > start)) // start < end or start = -3 and end = -7
{
for (int i=start; i<=end; i+=inc)
{
System.out.print(i + " ");
}
}
else if(start > end || (start < 0 && end < 0 && start > end)) // if start = - 7 and end = -3
{
for (int i=end; i>=start; i-=inc) // should be greater than
{
System.out.print(i + " ");
}
}
else if(start == end)
{
System.out.println(end);
}

Related

Simple Seat Reservation in Java

package Demo;
import java.util.Scanner;
public class seat_reservation{
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
// Initialization
final int ROWS = 2;
final int COLS = 3;
char [][] seats = new char [ROWS][COLS];
int i, j, seatNum, counter = 0;
char seatLetter = 'A';
int choice = 0;
String seatEnter;
boolean cont = true; // loops of running the program
while( choice != 4 ){
System.out.print( "1. Assign Seats" );
System.out.print( "2. Exit" );
System.out.print( "Select your choice: " );
choice = read.nextInt();
switch( choice ){
case 1:
//Set the value.
for (i=0; i < seats.length; i++) {
for (j=0; j < seats[i].length; j++)
seats[i][j] = seatLetter++;
seatLetter = 'A'; // to reset the value to A for the new loop
}
//To display the list of seats
for (i=0; i < seats.length; i++) {
System.out.print((i+1)+" ");
for (j=0; j < seats[i].length; j++)
System.out.print(seats[i][j]+" ");
System.out.println();
}
//condition
while (counter < 6 && cont) {
do {
System.out.print("Please type the chosen seat(starts with row and column,e.g:2A):" + "");
seatEnter = (read.nextLine()).toUpperCase(); //covert to Upper case
seatNum = Integer.parseInt(seatEnter.charAt(0)+"");
if (seatNum != 0)
seatLetter = seatEnter.charAt(1);
i++;
//if user enters wrong input, error message will appear.
if (seatLetter!='A'){
if (seatLetter!='B'){
if(seatLetter!='C'){
if(seatLetter!='D')
System.out.println ("Invalid! Please enter the correct seat:");
}
}
}
}
//continue to loop until the condition true
while (seatNum < 0 || seatNum > 7 || seatLetter < 'A' || seatLetter > 'D');
if (seatNum == 0) {
cont = false;
} else {
if (seats[seatNum-1][seatLetter-65] == 'X')
System.out.println("Seat have been taken.Please choose another seat:");
else {
seats[seatNum -1][seatLetter-65] = 'X';
counter++;
}
// To display updated lists of seats
for (i=0; i < seats.length; i++) {
System.out.print((i+1)+" ");
for (j=0; j < seats[i].length; j++)
System.out.print(seats[i][j] + " ");
System.out.println();
}
System.out.println(" ") ;
//}
//}
// displays fully booked message
if (counter == 6)
System.out.println("All seats are now fully-booked.");
break;
}
}
case 2://syntax error here
if (counter == 6)
System.out.println( "All seats are now fully-booked." );
System.out.println( "End of Program" );
System.exit(0);
break;
default:
System.out.println("Error input");
break;//syntax error here as well.
}
}
}
}
The problem is caused due to:
choice = read.nextInt();
The scanner.nextInt() only takes the next token from the input. Rest are ignored by it.
So when you're trying to take the next input from this line and process it, the error occurs:
seatEnter = (read.nextLine()).toUpperCase(); //covert to Upper case
seatNum = Integer.parseInt(seatEnter.charAt(0) + "");
As the previous read.nextInt() left the rest except first token, when you hit enter after giving 1 as input, it took only the 1 and the enter or newline token was captured by the read.nextLine(). That is why it got no charAt(0) and thus thrown StringIndexOutOfBoundException.
Try:
choice = Integer.parseInt(read.nextLine());
or,
choice = read.nextInt();
read.nextLine(); // this will capture the residue

Java Slot Machine Slot Comparison Trouble

I've been working on a slot machine program for class and have been having trouble figuring out how to compare the different "slots" on the machine to determine whether or not there are matches and tell the program how to proceed with calculate winnings. I originally thought of storing each result of my random number generator in a variable and then comparing them but am unsure of how to do this. I am unable to use arrays or lists or anything like that unfortunately. Thanks in advance and sorry if my code looks sloppy.
import java.util.*;
//Start Program
public class Slots
{
public static void main(String[] args)
{ //Start Main
//=====Declare Variables=====
int pool = 0,
won = 0,
slot_disp = 0,
slot0 = 0,
slot1 = 0,
slot2 = 0,
slot3 = 0,
slot4 = 0,
matches = 0,
bet = 0;
boolean again = true;
String msg = "",
ans = "";
Scanner key = new Scanner(System.in);
//=====Welcome and Start=====
System.out.println("\t* * * Welcome to SLOTS * * *");
System.out.print("\nEnter amount of money to play: ");
pool = key.nextInt();
while(again)
{
System.out.print("\nEnter your bet: ");
bet = key.nextInt();
while(bet < 0 || bet > pool)//-----Bet Validation-----
{
System.out.println("\tInvalid bet of : " + (double)bet);
System.out.println("\tFunds available: " + (double)pool);
System.out.print("\tRe-Enter bet : ");
bet = key.nextInt();
}
System.out.print(" ");
for(int cntSlot = 0; cntSlot < 5; cntSlot++)
{
Random rand = new Random();
slot_disp = rand.nextInt(5);
//=====Converting Random Number into Slot Display=====
switch(slot)
{
case 0:
msg = "Cherries";
break;
case 1:
msg = "Oranges";
break;
case 2:
msg = "Plums";
break;
case 3:
msg = "Melons";
break;
case 4:
msg = "Bars";
break;
}
System.out.print(msg + " ");
}//-----End Slot Conversion Loop-----
//=====Comparing Slot Output to Determine Winnings=====
switch(matches)
{
case 2:
won = 0;
break;
case 3:
won = bet * 2;
break;
case 4:
won = bet * 3;
break;
case 5:
won = bet * 4;
break;
default:
won = 0;
}
(double)(pool = (pool - bet) + won);
//=====Displaying the Results=====
if(matches == 5)//-----Jackpot-----
{
System.out.println("\n\n * * * You hit the JACKPOT * * *");
System.out.println("You Won: " + won);
}
if(matches > 2 && match < 5)//-----Winner-----
System.out.println("\n\nYou WIN: " + won);
else
System.out.println("\n\n\nNo matches, sorry you lost.");
if(pool <= 0)//-----Game Over-----
{
System.out.println("\n> > > You ran out of money. < < < ");
System.out.println("\nRestart the game to play again");
again = false;
break;
}
else
System.out.println("\nAvailable money: " + (double)pool);
//=====Asking User if they want to Continue=====
if(pool > 0)
{
System.out.print("\nWould you like to play again (y/n): ");
ans = key.next();
}
if(ans.equalsIgnoreCase("y"))
again = true;
else
again = false;
}
System.out.println("Game over, cash out: " + (double)pool);
System.out.println("\nThanks for playing the Slots!");
} //End Main
}
Use an int[] hits = new int[5]; array to store for each value how often it was selected. in the loop increment hits(slot) += 1;. Later, loop over the array to find the maximum.

'Error: Expected' when creating switch

import java.util.Scanner;
public class lab05a
{
public static void main (String[] args)
{
String statement;
Scanner scan = new Scanner(System.in);
int vowela;
int vowele;
int voweli;
int vowelo;
int vowelu;
int nonvowel;
int vowela = 0;
int vowele = 0;
int voweli = 0;
int vowelo = 0;
int vowelu = 0;
statement = scan.nextString();
statement = statement.toLowerCase();
for (int i = 0; i <= statement.length(); count++)
{
char c = examplestring.charAt(i);
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
switch (c)
{
case 'a':
vowela += 1;
break;
case 'e':
vowele += 1;
break;
case 'i';
voweli += 1;
break;
case 'o';
vowelo += 1;
break;
case 'u';
vowelu += 1;
break;
}
else
nonvowel +=1;
}
System.out.prinln("a: " + vowela);
System.out.prinln("e: " + vowele);
System.out.prinln("i: " + voweli);
System.out.prinln("o: " + vowelo);
System.out.prinln("u: " + vowelu);
System.out.prinln("nonvowel: " + novowel);
}
}
I thought of doing it this way:
First I create a for loop to iterate through every character of String statement.
Then I put an if statement in the for loop that checks if c(declared as statement.charAt(i)) is a vowel.
If c is a vowel I use a switch to increase the count for that particular vowel by one and then break.
If c is not a vowel, it gets added to the count of consonants.
After the for loop is done it prints the count of each character.
The switch is where I am having problems. Case 'a' and case 'e' have cause no errors, but cases 'i' through 'u' cause an error('Error: : Expected').
I don't understand what this means or why, as cases 'i' through 'u' are written the same way as cases 'a' and 'e'. Can someone help me out?
3 errors found:
[line: 38] Error: : expected
[line: 41] Error: : expected
[line: 44] Error: : expected
Sorry if this post is poorly formatted I am new to Stack Overflow.
There are many errors in your code, I have modified it (posted at the bottom) and pointed out some of your mistakes:
Change statement = scan.nextString().toLowerCase(); to statement = scan.nextLine().toLowerCase();
I don't understand what this means or why, as cases 'i' through 'u' are written the same way as cases 'a' and 'e'.
Your switch is wrong because cases i, o, and u have a semi-colon(;) instead of a colon(:). Just that small difference is causing the error there. Change your switch statement to this:
switch(c) {
case 'a':
vowela++;
break;
case 'e':
vowele++
break;
case 'i':
voweli++
break;
case 'o':
vowelo++
break;
case 'u':
vowelu++;
break;
}
Here's your modified code. Now it is correct, and it works:
import java.util.Scanner;
public class lab05a {
public static void main (String[] args) {
String statement;
Scanner scan = new Scanner(System.in);
int vowela = 0;
int vowele = 0;
int voweli = 0;
int vowelo = 0;
int vowelu = 0;
int nonvowel = 0;
statement = scan.nextLine().toLowerCase();
for (int i = 0; i < statement.length(); i++) {
char c = statement.charAt(i);
switch (c) {
case 'a':
vowela++;
break;
case 'e':
vowele++;
break;
case 'i':
voweli++;
break;
case 'o':
vowelo++;
break;
case 'u':
vowelu++;
break;
default:
nonvowel++;
break;
}
}
System.out.println("a: " + vowela);
System.out.println("e: " + vowele);
System.out.println("i: " + voweli);
System.out.println("o: " + vowelo);
System.out.println("u: " + vowelu);
System.out.println("nonvowel: " + nonvowel);
}
}
You may have noticed some changes such as removing the if statement that checks for a vowel. Rather than doing all of that, I just added a default case. If none of the other conditions are true, than whatever is in the default case is executed. I also initialized your variables vowela, vowele, voweli, etc., and rather than doing vowela += 1 I just changed it to vowela++, which produces the same effect(same with the other letters).

In my Java program why does my switch statement not execute when I hit '1' after hitting a different value prior to it

I am fairly new to Programming and I could really use some help. My problem is as follows. When I run my program it compiles and operates normally if I press 1 on my menu to begin with. The problem I run into is when I press for example option 3 from the menu and it re prompts for option 1. After it re prompts and I press 1 the menu just re prompts for two times and then it will execute the switch (iMenuOption) case '1':. I could really use some assistance, thanks here's my code.
public class Project3
{
public static void main(String[] args)
{
//------------------------------variables--------------------------------
int iMenuOption;
double dAverage;
char cLetterGrade;
String strName;
String strEndingMessage;
String strWelcomeMessage;
int i1 = -1;
int i2 = -1;
int i3 = -1;
dAverage = Utility.calcAverage(i1, i2, i3);
cLetterGrade = Utility.letterGrade(dAverage);
Scanner kb = new Scanner(System.in);
Utility.myInfo();
System.out.print("\n\nWhat's your user name? ");
strName = kb.nextLine();
System.out.print((Utility.createWelcomeMessage(strName)));
System.out.print("\n\n");
Utility.pressEnterToContinue();
System.out.print("\n");
Utility.clearScreen();
iMenuOption = Utility.menuOption();
while (iMenuOption != '6')
{
switch (iMenuOption)
{
case '1':
i1 = Utility.testScore();
i2 = Utility.testScore();
i3 = Utility.testScore();
System.out.println("\n");
Utility.pressEnterToContinue();
Utility.clearScreen();
iMenuOption = Utility.menuOption();
break;
case '2':
if (i1 == -1)
{
System.out.println("\nUser option 1 to enter test score\n");
Utility.pressEnterToContinue();
Utility.clearScreen();
iMenuOption = Utility.menuOption();
}
else
{
System.out.println("Score 1: " + i1);
System.out.println("Score 2: " + i2);
System.out.println("Score 3: " + i3);
System.out.println("\n");
Utility.pressEnterToContinue();
Utility.clearScreen();
iMenuOption = Utility.menuOption();
break;
}
case '3':
if (i1 == -1)
{
System.out.println("\nUser option 1 to enter test score\n");
Utility.pressEnterToContinue();
Utility.clearScreen();
iMenuOption = Utility.menuOption();
}
else
{
dAverage = Utility.calcAverage(i1, i2, i3);
System.out.println("Average: " + dAverage);
System.out.println("\n");
Utility.pressEnterToContinue();
Utility.clearScreen();
iMenuOption = Utility.menuOption();
break;
}
case '4':
if (i1 == -1)
{
System.out.println("\nUser option 1 to enter test score\n");
Utility.pressEnterToContinue();
Utility.clearScreen();
iMenuOption = Utility.menuOption();
}
else
{
dAverage = Utility.calcAverage(i1, i2, i3);
cLetterGrade = Utility.letterGrade(dAverage);
System.out.print("Letter grade: " + cLetterGrade);
System.out.println("\n");
Utility.pressEnterToContinue();
Utility.clearScreen();
iMenuOption = Utility.menuOption();
break;
}
case '5':
if (i1 == -1)
{
System.out.println("\nUser option 1 to enter test score\n");
Utility.pressEnterToContinue();
Utility.clearScreen();
iMenuOption = Utility.menuOption();
}
else
{
System.out.print("\n");
Utility.calcGPA(cLetterGrade);
System.out.print("\n");
Utility.pressEnterToContinue();
Utility.clearScreen();
iMenuOption = Utility.menuOption();
break;
}
} //end switch (iMenuOption)
} //end while (iMenuOption !=6)
Utility.clearScreen();
System.out.print(Utility.createEndingMessage(strName));
System.out.print("\n\n");
Utility.pressEnterToContinue();
} //end main()
}
class Utility
{
public static double calcAverage(int i1, int i2, int i3)
{
double dAverage;
final double dTotalTests = 3.0; //
dAverage = ((i1 + i2 + i3)/dTotalTests);
return dAverage;
} //end calcAverage(int, int, int)
public static String createEndingMessage(String strName)
{
String strEndMessage;
strEndMessage = "\t " + strName + " Thank you for using this program";
return strEndMessage;
} //end createEndingMessage(String)
public static String createWelcomeMessage(String strName)
{
String strWelcomeMessage;
strWelcomeMessage = "\n\tHello, " + strName + " this program is made to calculate the" +
" averages of given test scores, display your letter grade, and the "
+ "GPA of the scores. By Cody Buchanan";
return strWelcomeMessage;
} //end createWelcomeMessage(String)
public static double calcGPA(char cLetterGrade)
{
double dGPA;
switch (cLetterGrade)
{
case 'A':
dGPA = 4.0;
System.out.print("GPA: " + dGPA);
break;
case 'B':
dGPA = 3.0;
System.out.print("GPA: " + dGPA);
break;
case 'C':
dGPA = 2.0;
System.out.print("GPA: " + dGPA);
break;
case 'D':
dGPA = 1.0;
System.out.print("GPA: " + dGPA);
break;
case 'F':
dGPA = 0.0;
System.out.print("GPA: " + dGPA);
break;
default:
dGPA = 0.0;
break;
}
return dGPA;
} //end calcGPA(char)
public static void pressEnterToContinue()
{
Scanner keyboard = new Scanner(System.in);
System.out.print("\t Press enter to continue ");
keyboard.nextLine();
} //end pressEnterToContinue
public static void clearScreen()
{
System.out.print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
} //end clearScreen
public static int testScore()
{
int iTestScore;
Scanner kb = new Scanner(System.in);
System.out.print("Enter a test score: ");
iTestScore = kb.nextInt();
return (iTestScore);
}
public static int menuOption()
{
Scanner kb = new Scanner(System.in);
String strInput;
int iMenuOption;
System.out.println("\n Menu Options");
System.out.println("\t----------------------");
System.out.println("\t1. Enter Test Scores");
System.out.println("\t2. Display Test Scores");
System.out.println("\t3. Display Average");
System.out.println("\t4. Display Letter Grade");
System.out.println("\t5. Display GPA");
System.out.println("\t6. Exit Program");
System.out.println("\t----------------------");
System.out.print("Select one of the options: ");
strInput = kb.nextLine();
iMenuOption = strInput.charAt(0);
while (!(iMenuOption == '1' || iMenuOption == '2' || iMenuOption == '3' || iMenuOption == '4' || iMenuOption == '5' || iMenuOption == '6'))
{
System.out.print("\n");
Utility.pressEnterToContinue();
Utility.clearScreen();
System.out.println("\n Menu Options");
System.out.println("\t----------------------");
System.out.println("\t1. Enter Test Scores");
System.out.println("\t2. Display Test Scores");
System.out.println("\t3. Display Average");
System.out.println("\t4. Display Letter Grade");
System.out.println("\t5. Display GPA");
System.out.println("\t6. Exit Program");
System.out.println("\t----------------------");
System.out.print("Select one of the options: ");
strInput = kb.nextLine();
iMenuOption = strInput.charAt(0);
} //end while loop
return iMenuOption;
} //end menuOption()
public static void myInfo()
{
String strName = "\t\tDerek"; //My name
String strClass = "\t\tCSCI"; //The class info
String strDate = "\t\t10/22/13"; //The program's date
String strAssignment = "\tProject"; //The assignment name
System.out.println("Author:\t\t" + strName);
System.out.println("Class:\t\t" + strClass);
System.out.println("Date:\t\t" + strDate);
System.out.println("Assignment:\t\t" + strAssignment);
}
public static char letterGrade(double dAverage)
{
char cLetterGrade; //To hold the letter grade character value
if (dAverage >= 90 && dAverage <= 100)
{
cLetterGrade = 'A';
}
else if (dAverage >= 80 && dAverage < 90)
{
cLetterGrade = 'B';
}
else if (dAverage >= 70 && dAverage < 80)
{
cLetterGrade = 'C';
}
else if (dAverage >= 60 && dAverage < 70)
{
cLetterGrade = 'D';
}
else
{
cLetterGrade = 'F';
}
return cLetterGrade;
} //end letterGrade(double)
} //end Utility class
In menuOption:
iMenuOption = strInput.charAt(0)
which you are saying to return you the first character of the string. Then you are assigning it to an int. So Char '1' does != integer 1.
Fix that and you are good =)
Could just do:
iMenuOption = Integer.valueOf(strInput.charAt(0));
should be right as rain.
Since the iMenuOption is declared as an int,in the switch - cases- we will have to specify n integer value, rather than a char (displayed in ' ' ).
What happens is, when a char value is being compare against, it actually compares against its ascii value.
while (iMenuOption != '6')
{
switch (iMenuOption)
{
case '1': (change to case 1: ) (not case '1')
....
break;
case '2': (This should be case 2:)
....
break;
case '3': (This should be case 3:)
....
break;
case '4': (This should be case 4:)
....
break;
case '5': (This should be case 5:)
....
break;
}
} //end switch (iMenuOption)
Also try including a default case for the switch statement, which will execute incase an invalid value that reaches the switch.
replace
iMenuOption = Utility.menuOption();
while (iMenuOption != '6')
with
while ((iMenuOption = Utility.menuOption()) != '6')

Java display does not show whole method

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";
}
}

Categories