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;
}
Related
I have this program which can make some singular nouns plural (I know I'm missing a lot, but that's aside the point). When I enter in a word such as "man-of-war" it returns as "mans-of-war" instead of "men-of-war". How do I fix this? My code can already make man to men, just not in the case I mentioned. Also for this program every compound word will have the dash, it is simply for practice.
public class LanguageUtils {
static boolean checkException(String noun){
String[] exceptions = {"fish", "fox", "deer", "moose", "sheep", "cattle","pants","scissors"};
for(int i=0;i<exceptions.length;i++) {
if(exceptions[i].equals(noun))
return true;
}
return false;
}
static boolean EnglishConsonant(char ch) {
switch (Character.toLowerCase(ch)) {
case 'a': case 'e': case 'i': case 'o': case 'u':
return false;
default:
return true;
}
}
static String makePlural (String noun){
String pluralWord = "";
int length = noun.length();
String strippedWord = noun.substring(0, noun.length()-1);
char lastLetter = noun.charAt(noun.length()-1);
if(noun.contains("-")){
String nounsaver = noun.substring(noun.indexOf('-'), noun.length());
pluralWord = noun.substring(0,noun.indexOf('-')) + "s" + nounsaver;
}
else{
switch (lastLetter){
case 's':
case 'x':
case 'z':
if(noun.equals("ox")){
pluralWord = noun + "en";
break;
}
else{
pluralWord = noun + "es";
break;
}
case 'o':
if(EnglishConsonant(noun.charAt(noun.length()-2))){
pluralWord = strippedWord + "oes";
break;
}
case 'e':
char f = noun.charAt(noun.length()-2);
String prec = noun.substring(0, noun.length()-2);
if(f == 'f'){
pluralWord = prec + "ves";
break;
}
if(noun.equals("goose")){
pluralWord = "geese";
break;
}
else{
pluralWord = noun + "s";
break;
}
case 'h':
if ((noun.charAt(noun.length()-2)== 'c') || (noun.charAt(noun.length()-2)== 's')) {
pluralWord = noun + "es";
break;
}
case 'f':
if (EnglishConsonant(noun.charAt(noun.length()-2))) {
pluralWord = strippedWord + "ves";
break;
}
case 'y':
if (EnglishConsonant(noun.charAt(noun.length()-2))) {
pluralWord = strippedWord + "ies";
break;
}
default:
if(noun.equals("foot")){
pluralWord = "feet";
break;
}
if(noun.endsWith("man")){
pluralWord = noun.substring(0, noun.length()-3)+"men";
break;
}
else{
pluralWord = noun + "s";
break;
}
}
}
if (length == 1){
pluralWord = noun + "'s";
}
if(checkException(noun)){
pluralWord = noun;
}
return pluralWord;
}
}
When dealing with a compound word, if you need to pluralize a part, call a function designed to do just that: makePlural.
If you have - then break the words and call the makePlural for those words again.
You can use String#replace:
if (noun.contains("man")) {
pluralWord = noun.replace("man", "men");
break;
}
I'm new to Java and learning it. I've come across this question which I'm trying to understand.
How can I write a Java class that has 2 fields which hold the following info:
RoomNumber (A String)
MeetDays (A String)
The MeetDays considers Sunday to be day 1. A user should enter the day number for each day the class meets.
Example:
if classes are held Tues and Thurs, user will enter 35. If user enters an invalid number ranges such as '11' or '233' etc. An exception will be thrown.
I figure to do a switch statement here but I am just unsure how to proceed. I figure this might be an easy question for an experienced Java Developer. Any help or assistance would be much appreciated.
Edit:
public class SectionNumber {
private String roomNumber;
private String meetDays;
public SectionNumber() {}
public SectionNumber(String roomNumber, String meetDays) {
this.roomNumber = roomNumber;
this.meetDays = meetDays;
}
public String getRoomNumber() {
return roomNumber;
}
public void setRoomNumber(String roomNumber) {
this.roomNumber = roomNumber;
}
public String getMeetDays() {
return meetDays;
}
public void setMeetDays(String meetDays) {
this.meetDays = meetDays;
}
// not sure how to proceed here
public void classMeetDays(String userInput) {
switch (meetDays) {
case userInput:
break;
default:
break;
}
}
}
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> dayList = new ArrayList<String>();
int userInputNumber = 1234567;
String userInputAsString = String.valueOf(userInputNumber);
for (int i = 0; i < userInputAsString.length(); i++) {
char dayAsNumericChar = userInputAsString.charAt(i);
String day;
switch (dayAsNumericChar) {
case '1':
day = "Sunday";
break;
case '2':
day = "Monday";
break;
case '3':
day = "Tuesday";
break;
case '4':
day = "Wednesday";
break;
case '5':
day = "Thursday";
break;
case '6':
day = "Friday";
break;
case '7':
day = "Saturday";
break;
default:
throw new RuntimeException("Invalide number: " + dayAsNumericChar);
}
if (dayList.contains(day)) {
throw new RuntimeException("Day: " + day + " is picked twice");
}
dayList.add(day);
}
System.out.println(userInputAsString);
for (String s : dayList) {
System.out.println(" -> " + s);
}
}
}
You will want to declare meetDays as an instance variable in your class. This class should also contain a method that iterates over the days inputted and adds them to meetDays. For instance:
private void setDays(String input) {
for (int i=0; i<input.length(); i++) {
switch (input.charAt(i)) {
case '1':
meetDays += "Sunday ";
break;
case '2':
meetDays += "Monday ";
break;
// and so on for the remaining days
default:
//throw the exception here
}
}
meetDays = meetDays.trim();
}
Im trying to get my program to print out the day of any given date using functions that I have to write and declare, although for the early dates of the month the program doesnt seem to print the write day. The equation in the dayOfTheWeek function, w, was given to us to calculate for the day, although for the 'floor' code to be used i had to create another 'private static' function for reasons im not quite sure of, any reason as to why would be great as well as any reason for why my program isnt returning the right day for certain dates.
here's my code, any help would be greatly appreciated :)
import java.util.Scanner;
import javax.swing.JOptionPane;
public class DayOfTheWeek {
public static final int SEPTEMBER_APRIL_JUNE_NOVEMBER_DAYS = 30;
public static final int REST_OF_YEAR_DAYS = 31;
public static final int LEAP_YEAR_FEB = 29;
public static final int NORMAL_FEB = 28;
public static final int MONTHS = 12;
public static void main(String[] args) {
try
{
String input = JOptionPane.showInputDialog("Enter date (day/month/year):");
Scanner scanner = new Scanner( input );
scanner.useDelimiter("/");
int day = scanner.nextInt();
int month = scanner.nextInt();
int year = scanner.nextInt();
scanner.close();
String numberEnding = numberEnding (day);
String dayEnding = day + numberEnding;
String monthName = monthName (month);
String dayName = dayOfTheWeek (day, month, year);
if (validDate(day, month, year))
{
JOptionPane.showMessageDialog(null, dayName + " " + dayEnding + " " + monthName
+ " " + year + " is a valid date.");
}
else
{
JOptionPane.showMessageDialog(null, "" + dayEnding + " " + monthName
+ " " + year + " is not a valid date.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
catch (NullPointerException exception)
{
}
catch (java.util.NoSuchElementException exception)
{
JOptionPane.showMessageDialog(null, "No number entered. \nPlease restart and try again.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
public static boolean validDate( int day, int month, int year ) {
return ((year >= 0) && (month >= 1) && (month <= MONTHS) &&
(day >= 1) && (day <= daysInMonth( month, year )));
}
public static int daysInMonth( int month, int year ) {
int monthDays;
switch (month)
{
case 2:
monthDays = isLeapYear(year) ? LEAP_YEAR_FEB : NORMAL_FEB;
break;
case 4:
case 6:
case 9:
case 11:
monthDays = SEPTEMBER_APRIL_JUNE_NOVEMBER_DAYS;
break;
default:
monthDays = REST_OF_YEAR_DAYS;
}
return monthDays;
}
public static boolean isLeapYear( int year ) {
return (((year%4 == 0) && (year%100 != 0)) || (year%400 == 0));
}
public static String numberEnding( int day ) {
String dayEnding = "";
int remainder = day%10;
if (day >= 10 && day <= 20)
{
dayEnding = "th";
}
else
{
switch (remainder)
{
case 1:
dayEnding = "st";
break;
case 2:
dayEnding = "nd";
break;
case 3:
dayEnding = "rd";
break;
default:
dayEnding = "th";
break;
}
}
return dayEnding;
}
public static String monthName( int month ) {
String monthName = "";
switch (month)
{
case 1:
monthName = "January";
break;
case 2:
monthName = "February";
break;
case 3:
monthName = "March";
break;
case 4:
monthName = "April";
break;
case 5:
monthName = "May";
break;
case 6:
monthName = "June";
break;
case 7:
monthName = "July";
break;
case 8:
monthName = "August";
break;
case 9:
monthName = "September";
break;
case 10:
monthName = "October";
break;
case 11:
monthName = "November";
break;
case 12:
monthName = "December";
break;
default:
}
return monthName;
}
public static String dayOfTheWeek (int day, int month, int year){
String dayName = "";
int Y;
if (month == 1 || month == 2)
{
Y = (year-1);
}
else
{
Y = (year);
}
int y = Y%100;
int c = Y/100;
int w = (day + floor(2.6 * (((month+9) % 12)+ 1) -0.2)
+ y + floor(y/4) + floor(c/4) - (2*c));
w = (w%7);
if (w < 0)
{
w += 7;
}
switch (w)
{
case 0:
dayName = "Sunday";
break;
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
}
return dayName;
}
private static int floor(double d) {
return 0;
}
}
I believe you need to use the Math.floor() method. Simply call this in place of your floor method:
(day + Math.floor(2.6 * (((month+9) % 12)+ 1) -0.2)
+ y + Math.floor(y/4) + Math.floor(c/4) - (2*c));
You can also cast the equation directly using (int):
int w = (int) (day + 2.6 * ((month+9) % 12 + 1) - 0.2 + y + (y/4) + (c/4) - (2*c));
However, in your case I think that the values will be rounded improperly using casting, so you should probably use the floor method.
If you'd like some additional information on the differences between floor and casting here's a stackoverflow question that addresses it: Cast to int vs floor
I would use the Joda-Time library.
import org.joda.time.DateTime
final DateTime date = new DateTime();
final int dayOfWeek = date.getDayOfWeek();
See the Joda-Time User Guide for more info and examples..
I need to make a recursive method that converts a decimal into hexadecimal.
I can't use Integer.toHexString.
EDIT:I tried this code but it doesn't work properly
public static String Hexa(String s) {
String result = "";
int n = Integer.parseInt(s);
int remainder = n % 16;
if (n == 0) {
return Integer.toString(0);
} else {
switch (remainder) {
case 10:
result = "A" + result;
break;
case 11:
result = "B" + result;
break;
case 12:
result = "C" + result;
break;
case 13:
result = "D" + result;
break;
case 14:
result = "E" + result;
break;
case 15:
result = "F" + result;
break;
default: result = Integer.toString(n/16) + result; break;
}
System.out.println(result);
return Hexa(Integer.toString(n/16)) + result;
}
}
Edit:
Changed the default case and the if (n == 0) loop return statement and it works beautifully now.
new code:
public static String Hexa(String s) {
String result = "";
int n = Integer.parseInt(s);
int remainder = n % 16;
if (n == 0) {
return "";
} else {
switch (remainder) {
case 10:
result = "A";
break;
case 11:
result = "B";
break;
case 12:
result = "C";
break;
case 13:
result = "D";
break;
case 14:
result = "E";
break;
case 15:
result = "F";
break;
default:
result = remainder + result;
break;
}
return Hexa(Integer.toString(n / 16)) + result;
}
}
The problem is in your default clause:
default: result = Integer.toString(n/16) + result; break;
it should read:
default: result = Integer.toString(remainder) + result; break;
That will make your program return "04D2".
But there are several other corrections you can make:
Stop converting back and forth to String. For example that same line can be just:
default: result = remainder + result; break;
Also, change your parameters time to int. If you do need to receive a String, then make this an auxiliary function and make your main function receive a String.
You don't need that breakat the end of your default
You don't need a switch. Isn't 'F' = 'A' + (15 - 10) ? You can figure out how to make a formula that translates any number in the range [10,15] to its corresponding letter.
Instead of Integer.toString(0) you can use "0" ... but that isn't even necessary, you can use "" to avoid that leading 0 in your output. If your are worried for handling the special case where the whole number is "0" add a special clause.
The code below may help you to solve your problem:
public static String decimalToAnyBase(int num,int base) {
if(num<base) {
return num+"";
}
String result=null;
int rem=num%base;
String str=decimalToAnyBase(num/base, base);
result=str+((rem>=10)? (char)(rem-10+'A')+"":rem);
return result;
}
import java.util.Scanner;
public class Assign01_05
{
static String res;
public static void hex(int num) //125
{
if(num>=0 && num<10)
System.out.print(num);
else if(num>=10 && num<=15)
{
switch(num)
{
case 10:
System.out.print('A');
break;
case 11:
System.out.print('B');
break;
case 12:
System.out.print('C');
break;
case 13:
System.out.print('D');
break;
case 14:
System.out.print('E');
break;
case 15:
System.out.println('F');
break;
}
}
else
{
hex(num/16);
hex(num%16);
}
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the Demical number :");
int num=sc.nextInt();
hex(num);
}
}
import java.util.Scanner;
public class Assign01_05
{
static String res;
public static void hex(int num) //125
{
if(num>=0 && num<10)
System.out.print(num);
else if(num>=10 && num<=15)
{
switch(num)
{
case 10:
System.out.print('A');
break;
case 11:
System.out.print('B');
break;
case 12:
System.out.print('C');
break;
case 13:
System.out.print('D');
break;
case 14:
System.out.print('E');
break;
case 15:
System.out.println('F');
break;
}
}
else
{
hex(num/16);
hex(num%16);
}
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the Demical number :");
int num=sc.nextInt();
hex(num);
}
}
import java.util.Scanner;
public class Ques5 {
public static void hex(int n) {
if(n>9&&n<=15) {
System.out.printf("%c",'A'+(n-10));
}
else if(n>=0&&n<=9){
System.out.printf("%d",n);
}
else {
hex(n/16);
hex(n%16);
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the decimal number : ");
int i = sc.nextInt();
System.out.println("The hexadecimal number is : ");
hex(i);
sc.close();
}
}
const char hex_string[17] = "0123456789ABCDEF";
void dec_to_hex(long long x){
if(x == 0) return;
dec_to_hex(x/16);
printf("%c",hex_string[x%16]);
}
Same in 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";
}
}