One of my results are messed up - java

I am working on a project that has the user input the current date as well as their birthday. The whole code calculates their age as well as printing the date. For the current date it should show 11/14/2016, but instead shows 0/14/2016 and I cannot figure out where I went wrong.
Here's the code:
public class BroDoYouEvenAge {
// add in try-catch statements x
// only numeric values x
// leap year
// loop if invalid
// loop if day is invalid
// less than 1 or greater than max day x
// add in no spaces or letters x
// VALIDATION FOR MONTHS x
// loop if invalid
// same year x
// try again x
// loop if invalid
static int cDay;
static int cMonth;
static int bYear;
static int bMonth;
static int bDay;
public static void run() {
prompt();
retry();
}
public static void prompt() {
BufferedReader delta = new BufferedReader(new InputStreamReader(System.in));
try {
System.out.println("Please enter the current year");
String Year = delta.readLine();
int cYear = Integer.parseInt(Year);
// prompts the user for the current month as a numeric value
boolean validmonth = false;
while(!validmonth){
System.out.println("Please enter the current month as a numeric value");
String Month = delta.readLine();
int cMonth = Integer.parseInt(Month);
if (cMonth < 1 || cMonth > 12) {
System.out.println("Your input was invalid");
}else{
validmonth = true;
}
}
// prompts the user for the current day as a numeric value
boolean validday = false;
while (!validday) {
System.out.println("Please enter the current day as a numeric value");
String Day = delta.readLine();
cDay = Integer.parseInt(Day);
if (cDay < 1) {
System.out.println("Your input was invalid");
}else if (cDay > 31) {
System.out.println("Your input was invalid");
}else if (cMonth == 4 && cDay > 30) {
System.out.println("Your answer is invalid");
}else if (cMonth == 6 && cDay > 30) {
System.out.println("Your answer is invalid");
}else if (cMonth == 9 && cDay > 30) {
System.out.println("Your answer is invalid");
}else if (cMonth == 11 && cDay > 30) {
System.out.println("Your answer is invalid");
}else{
validday = true;
}
}
// prompts the user for their birth year
boolean validYear = false;
while(!validYear){
System.out.println("Please enter your birth year");
String Year2 = delta.readLine();
bYear = Integer.parseInt(Year2);
if (bYear > cYear) {
System.out.println("Your answer was invalid");
}else{
validYear = true;
}
}
// does not allow user to input a value greater than their current
// year
// loops if invalid
// prompts the user for their birth month
boolean _validmonth = false;
while(!_validmonth){
System.out.println("Please enter your birth month as a numeric value");
String Month2 = delta.readLine();
bMonth = Integer.parseInt(Month2);
if(bMonth < 1 || bMonth> 12){
System.out.println("Your answer was invalid");
}else{
_validmonth = true;
}
}
// prompts the user for their birth day
boolean _validday = false;
while(!_validday){
System.out.println("Please enter the day you were born as a numeric value");
String Day2 = delta.readLine();
bDay = Integer.parseInt(Day2);
// prints out collected data
if (bMonth == 4 && bDay > 30) {
System.out.println("Your answer is invalid");
}else if (bMonth == 6 && bDay > 30) {
System.out.println("Your answer is invalid");
}else if (bMonth == 9 && bDay > 30) {
System.out.println("Your answer is invalid");
}else if (bMonth == 11 && bDay > 30) {
System.out.println("Your answer is invalid");
}else{
_validday= true;
}
}
System.out.println("The current date is " + cMonth + "/" + cDay + "/" + cYear);
System.out.println("Your birthday is " + bMonth + "/" + bDay + "/" + bYear);
// calculates and prints age
if (cMonth > bMonth) {
int age = cYear - bYear;
System.out.println("You are " + age + " years old ");
} else if (cMonth < bMonth) {
int age = (cYear - bYear);
System.out.println("You are " + age + " years old ");
} else if (cMonth == bMonth && cDay > bDay) {
int age = cYear - bYear;
System.out.println("You are " + age + " years old.");
} else if (cMonth == bMonth && cDay < bDay) {
int age = (cYear - bYear) - 1;
System.out.println("You are " + age + " years old. ");
} else if (cYear == bYear) {
System.out.println("You are not even a year old.");
} else {
System.out.println("Your input was invalid");
}
} catch (IOException IOE) {
} catch (NumberFormatException NFE) {
System.out.println("Please enter a numeric value without spaces, letters, or special characters");
}
}
public static void retry() {
BufferedReader delta = new BufferedReader(new InputStreamReader(System.in));
try {
boolean valid = false;
while (!valid) {
System.out.println("Would you like to try again? 1) Yes or 2) No");
System.out.println("Please enter a number");
String retry = delta.readLine();
int trynum = Integer.parseInt(retry);
if (trynum < 1 || trynum > 2) {
System.out.println("Your input was invalid. Please enter 1 or 2.");
continue;
} else if (trynum == 1) {
prompt();
} else if (trynum == 2) {
System.out.println("Okay then.");
System.exit(0);
} else {
System.out.println("Invalid");
continue;
}
}
} catch (IOException IOE) {
} catch (NumberFormatException NFE) {
System.out.println("Please enter a number");
}
}
}

You are initializing a new cMonth variable when reading the months value on the line
System.out.println("Please enter the current month as a numeric value");
String Month = delta.readLine();
int cMonth = Integer.parseInt(Month);
Just remove the initialisation of the cMonth local variable as you want to refer to a global variable.
System.out.println("Please enter the current month as a numeric value");
String Month = delta.readLine();
cMonth = Integer.parseInt(Month);
Just to provide you the working source code I am pasting working solution:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class BroDoYouEvenAge {
// add in try-catch statements x
// only numeric values x
// leap year
// loop if invalid
// loop if day is invalid
// less than 1 or greater than max day x
// add in no spaces or letters x
// VALIDATION FOR MONTHS x
// loop if invalid
// same year x
// try again x
// loop if invalid
static int cDay;
static int cMonth;
static int bYear;
static int bMonth;
static int bDay;
public static void main(String[] args) {
run();
}
public static void run() {
prompt();
retry();
}
public static void prompt() {
BufferedReader delta = new BufferedReader(new InputStreamReader(System.in));
try {
System.out.println("Please enter the current year");
String Year = delta.readLine();
int cYear = Integer.parseInt(Year);
// prompts the user for the current month as a numeric value
boolean validmonth = false;
while(!validmonth) {
System.out.println("Please enter the current month as a numeric value");
String Month = delta.readLine();
cMonth = Integer.parseInt(Month);
if(cMonth < 1 || cMonth > 12) {
System.out.println("Your input was invalid");
} else {
validmonth = true;
}
}
// prompts the user for the current day as a numeric value
boolean validday = false;
while(!validday) {
System.out.println("Please enter the current day as a numeric value");
String Day = delta.readLine();
cDay = Integer.parseInt(Day);
if(cDay < 1) {
System.out.println("Your input was invalid");
} else if(cDay > 31) {
System.out.println("Your input was invalid");
} else if(cMonth == 4 && cDay > 30) {
System.out.println("Your answer is invalid");
} else if(cMonth == 6 && cDay > 30) {
System.out.println("Your answer is invalid");
} else if(cMonth == 9 && cDay > 30) {
System.out.println("Your answer is invalid");
} else if(cMonth == 11 && cDay > 30) {
System.out.println("Your answer is invalid");
} else {
validday = true;
}
}
// prompts the user for their birth year
boolean validYear = false;
while(!validYear) {
System.out.println("Please enter your birth year");
String Year2 = delta.readLine();
bYear = Integer.parseInt(Year2);
if(bYear > cYear) {
System.out.println("Your answer was invalid");
} else {
validYear = true;
}
}
// does not allow user to input a value greater than their current
// year
// loops if invalid
// prompts the user for their birth month
boolean _validmonth = false;
while(!_validmonth) {
System.out.println("Please enter your birth month as a numeric value");
String Month2 = delta.readLine();
bMonth = Integer.parseInt(Month2);
if(bMonth < 1 || bMonth > 12) {
System.out.println("Your answer was invalid");
} else {
_validmonth = true;
}
}
// prompts the user for their birth day
boolean _validday = false;
while(!_validday) {
System.out.println("Please enter the day you were born as a numeric value");
String Day2 = delta.readLine();
bDay = Integer.parseInt(Day2);
// prints out collected data
if(bMonth == 4 && bDay > 30) {
System.out.println("Your answer is invalid");
} else if(bMonth == 6 && bDay > 30) {
System.out.println("Your answer is invalid");
} else if(bMonth == 9 && bDay > 30) {
System.out.println("Your answer is invalid");
} else if(bMonth == 11 && bDay > 30) {
System.out.println("Your answer is invalid");
} else {
_validday = true;
}
}
System.out.println("The current date is " + cMonth + "/" + cDay + "/" + cYear);
System.out.println("Your birthday is " + bMonth + "/" + bDay + "/" + bYear);
// calculates and prints age
if(cMonth > bMonth) {
int age = cYear - bYear;
System.out.println("You are " + age + " years old ");
} else if(cMonth < bMonth) {
int age = cYear - bYear;
System.out.println("You are " + age + " years old ");
} else if(cMonth == bMonth && cDay > bDay) {
int age = cYear - bYear;
System.out.println("You are " + age + " years old.");
} else if(cMonth == bMonth && cDay < bDay) {
int age = cYear - bYear - 1;
System.out.println("You are " + age + " years old. ");
} else if(cYear == bYear) {
System.out.println("You are not even a year old.");
} else {
System.out.println("Your input was invalid");
}
} catch(IOException IOE) {
} catch(NumberFormatException NFE) {
System.out.println("Please enter a numeric value without spaces, letters, or special characters");
}
}
public static void retry() {
BufferedReader delta = new BufferedReader(new InputStreamReader(System.in));
try {
boolean valid = false;
while(!valid) {
System.out.println("Would you like to try again? 1) Yes or 2) No");
System.out.println("Please enter a number");
String retry = delta.readLine();
int trynum = Integer.parseInt(retry);
if(trynum < 1 || trynum > 2) {
System.out.println("Your input was invalid. Please enter 1 or 2.");
continue;
} else if(trynum == 1) {
prompt();
} else if(trynum == 2) {
System.out.println("Okay then.");
System.exit(0);
} else {
System.out.println("Invalid");
continue;
}
}
} catch(IOException IOE) {
} catch(NumberFormatException NFE) {
System.out.println("Please enter a number");
}
}
}

Related

Program is running but when I enter 9 digit error starting with 0, its giving me error that its invalid but I want print it as not used character

The program is running but when I enter 9 digit error starting with 0, it's giving me an error that its invalid but I want print it as not used character. Its java basic learning, thanks for helping in advance. My whole code is running perfect and if I enter 9 digit starting with 8 then its working properly for 0, its giving me error.
import java.util.Scanner;
public class FirstDigitSIN
{
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
System.out.print("Enter a SIN number :" );
if(kb.hasNextInt()){
// code that you want executed if the input is an integer goes in here
int num = kb.nextInt();
int numCopy = num;
int digit =0;
int count = 0;
while(num != 0 ){
num = num/10;
count++;}
if(count != 9){
System.out.println("Invalid Entry"); }
else{
System.out.println( num );
while(numCopy>0){
digit = numCopy %10;
numCopy = numCopy/10;
}if (digit == 1){
System.out.println(" Registered in Atlantic Canada ");
}else if(digit == 2){
System.out.println(" Registered in Quebec ") ;
}else if (digit == 3){
System.out.println(" Registered in Quebec ");}
else if (digit == 4){
System.out.println(" Registered in Ontario ");}
else if (digit == 5){
System.out.println(" Registered in Ontario ");}
else if (digit == 6){
System.out.println(" Registered in Prairie Provinces, NWT, Nunavut, Northwest Ontario ");}
else if (digit == 7){
System.out.println(" Registered in Pacific region ");}
else if (digit == 9){
System.out.println(" A temporary SIN ");}
else if (digit ==8 && digit ==0) {
System.out.println( "Not used");
}}
System.out.println(" *** End of program *** ");
}
else
{
System.out.println ("Error message goes here. Here you can tell them that you want them to enter an integer and not a string.");
}
}
}
Your problem is that Java is treating your Integer as 8 integers long. This is causing it to not be a valid input.
I made an if statement to check if it is treated as 8 characters long and if its 8 long and the first character is a 0 it prints not used since phone numbers don't start with 0.
if(count != 9 && (String.valueOf(Math.abs((long)num)).charAt(0) == '0')){
System.out.println( "Not used");
}
Full Code
import java.util.Scanner;
public class FirstDigitSIN
{
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
System.out.print("Enter a SIN number :" );
if(kb.hasNextInt()){
// code that you want executed if the input is an integer goes in here
int num = kb.nextInt();
int numCopy = num;
int digit =0;
int count = 0;
while(num != 0 ){
num = num/10;
count++;}
if(count != 9 && (String.valueOf(Math.abs((long)num)).charAt(0) == '0')){
System.out.println( "Not used");
}
else if(count != 9){
System.out.println("Invalid Entry"); }
else{
System.out.println( num );
while(numCopy>0){
digit = numCopy %10;
numCopy = numCopy/10;
}if (digit == 1){
System.out.println(" Registered in Atlantic Canada ");
}else if(digit == 2){
System.out.println(" Registered in Quebec ") ;
}else if (digit == 3){
System.out.println(" Registered in Quebec ");}
else if (digit == 4){
System.out.println(" Registered in Ontario ");}
else if (digit == 5){
System.out.println(" Registered in Ontario ");}
else if (digit == 6){
System.out.println(" Registered in Prairie Provinces, NWT, Nunavut, Northwest Ontario ");}
else if (digit == 7){
System.out.println(" Registered in Pacific region ");}
else if (digit == 9){
System.out.println(" A temporary SIN ");}
else if (digit ==8 && digit ==0) {
System.out.println( "Not used");
}}
System.out.println(" *** End of program *** ");
}
else
{
System.out.println ("Error message goes here. Here you can tell them that you want them to enter an integer and not a string.");
}
}
}
Couple of things:
To Avoid skipping these leading 0 use String rather than int to hold the input.
Then use Regex pattern to validate that String contains only numbers (else throw error if not a number).
As in your code you want to check the value of first digit in number entered by user, to retrieve that get first index from entered String.
The last condition digit == 8 && digit == 0 should be replaced with digit == 8 || digit == 0, as here we are checking equality of single value. And single value can't be equal to both 8 and 0.
Here is the code:
public class FirstDigitSIN {
private static final String NUMBERS = "[0-9]+";
// Compile the ReGex
private static final Pattern NUMBER_PATTERN = Pattern.compile(NUMBERS);
public static void main(String[] args) throws JsonMappingException, JsonProcessingException {
Scanner kb = new Scanner(System.in);
System.out.print("Enter a SIN number :");
if (kb.hasNext()) {
// code that you want executed if the input is an integer goes in here
String num = kb.next();
// using Pattern.matcher()
Matcher m = NUMBER_PATTERN.matcher(num);
// Return if the string
// matched the ReGex
if (m.matches()) {
int numCopy = Integer.valueOf(num);
int digit = 0;
if (num.length() != 9) {
System.out.println("Invalid Entry");
} else {
System.out.println(num);
int digit = Character.getNumericValue(num.charAt(0));
System.out.println(digit);
if (digit == 1) {
System.out.println(" Registered in Atlantic Canada ");
} else if (digit == 2) {
System.out.println(" Registered in Quebec ");
} else if (digit == 3) {
System.out.println(" Registered in Quebec ");
} else if (digit == 4) {
System.out.println(" Registered in Ontario ");
} else if (digit == 5) {
System.out.println(" Registered in Ontario ");
} else if (digit == 6) {
System.out.println(" Registered in Prairie Provinces, NWT, Nunavut, Northwest Ontario ");
} else if (digit == 7) {
System.out.println(" Registered in Pacific region ");
} else if (digit == 9) {
System.out.println(" A temporary SIN ");
} else if (digit == 8 || digit == 0) {
System.out.println("Not used");
}
}
System.out.println(" *** End of program *** ");
} else {
System.out.println(
"Error message goes here. Here you can tell them that you want them to enter an integer and not a string.");
}
} else {
System.out.println(
"Error message goes here. Here you can tell them that you want them to enter an integer and not a string.");
}
}
}

How can I handle input string, during the process of if, else if, else including Integer.parseInt?

I would like to handle this situation about inputting wrong string, but error keeps happening because of the else if argument.
Tried try, catch but don't know how to apply it to this code.
import java.util.Scanner;
public class game
{
public static void main(String[] args) {
System.out.println("let's start the multiplication game.");
System.out.println("which times table do you want to choose?");
System.out.println("if you want to do it by your choice, please input number among 2~9. Or if you want to do it randomly, please input number 0");
System.out.println("press \"q\" if you want to quit");
System.out.println("==>");
String input;
Scanner s = new Scanner(System.in);
input = s.nextLine();
int answer;
int multiplier = (int)(Math.random()*8+2);
int random = (int)(Math.random()*8+2);
if (input.equals("q"))
{
System.out.print("quit the game.");
}
else if (Integer.parseInt(input) == 0)
{
System.out.println(random+"times table has been made automatically.");
System.out.print(random+" X "+multiplier+" = "+"? input your answer ==> ");
answer = s.nextInt();
if (answer == random*multiplier)
{
System.out.print("You're right!");
}
else
{
System.out.print("Wrong! The right answer is "+random*multiplier+".");
}
}
else if (Integer.parseInt(input)>=2 && Integer.parseInt(input)<=9)
{
int number = Integer.parseInt(input);
System.out.println("You chose"+number+" times table.");
System.out.print(number+" X "+multiplier+" = "+"? input your answer ==> ");
answer = s.nextInt();
if (answer == number*multiplier)
{
System.out.print("You're right!");
}
else
{
System.out.print("Wrong! The right answer is "+number*multiplier+".");
}
}
else
{
System.out.print("Error. Please try again.");
}
}
}
I expect the result from the else block, but when I input wrong string like "c" or "f" and etc, number format exception error: For input string: "c" (or "f" and etc) happens. Thanks for reading this, and hope you solve this problem.
int check = 0;
try{
check = Integer.parseInt(input);
}catch(NumberFormatException e){
System.out.println("Wrong input");
continue;
}
If you loop this input processing,if it enters catch,you may take input again or you can do what you want when invalid input is entered.If there is no exception,check is your input value,then you can use it in your if and else-if statements like
if(check>0){
...
}
Before Else blocks, you can parse the input like this:
if (input.equals("q")) {
System.out.print("quit the game.");
return;
}
int parsedInput = 0;
try {
parsedInput = Integer.parseInt(input);
} catch (NumberFormatException ex) {
System.out.print("Error. Please try again.");
return;
}
Then you can write if-else for integer input like below:
if (parsedInput == 0) { ... }
else if (parsedInput >= 2 && parsedInput <= 9) {...}
Last else is not needed because I moved it to catch block.
try this it can handle exception
import java.util.Scanner;
public class Game {
public static void main(String[] args) {
System.out.println("let's start the multiplication game.");
System.out.println("which times table do you want to choose?");
System.out.println(
"if you want to do it by your choice, please input number among 2~9. Or if you want to do it randomly, please input number 0");
System.out.println("press \"q\" if you want to quit");
System.out.println("==>");
String input;
Scanner s = new Scanner(System.in);
input = s.nextLine();
int answer;
int multiplier = (int) (Math.random() * 8 + 2);
int random = (int) (Math.random() * 8 + 2);
if (input.equals("q")) {
System.out.print("quit the game.");
}
try {
int check_input = Integer.parseInt(input);
if (check_input == 0) {
System.out.println(random + "times table has been made automatically.");
System.out.print(random + " X " + multiplier + " = " + "? input your answer ==> ");
answer = s.nextInt();
if (answer == random * multiplier) {
System.out.print("You're right!");
} else {
System.out.print("Wrong! The right answer is " + random * multiplier + ".");
}
} else if (check_input >= 2 && check_input <= 9) {
int number = Integer.parseInt(input);
System.out.println("You chose" + number + " times table.");
System.out.print(number + " X " + multiplier + " = " + "? input your answer ==> ");
answer = s.nextInt();
if (answer == number * multiplier) {
System.out.print("You're right!");
} else {
System.out.print("Wrong! The right answer is " + number * multiplier + ".");
}
}
else {
System.out.print("Error. Please try again.");
}
} catch (Exception e) {
System.out.print("Error. Please try again.");
}
}
}
You just need to check the user provided input is number or not. Before parsing it.
I have added new isNumberic method which is returning boolean flag depending user's input and verify it.
public class Game {
public static void main(String[] args) {
System.out.println("let's start the multiplication game.");
System.out.println("which times table do you want to choose?");
System.out.println(
"if you want to do it by your choice, please input number among 2~9. Or if you want to do it randomly, please input number 0");
System.out.println("press \"q\" if you want to quit");
System.out.println("==>");
String input;
Scanner s = new Scanner(System.in);
input = s.nextLine();
int answer;
int multiplier = (int) (Math.random() * 8 + 2);
int random = (int) (Math.random() * 8 + 2);
Game game = new Game();
boolean isvalid = game.isNumeric(input);
if (input.equals("q")) {
System.out.print("quit the game.");
}
else if (isvalid && Integer.parseInt(input) == 0) {
System.out.println(random + "times table has been made automatically.");
System.out.print(random + " X " + multiplier + " = " + "? input your answer ==> ");
answer = s.nextInt();
if (answer == random * multiplier) {
System.out.print("You're right!");
} else {
System.out.print("Wrong! The right answer is " + random * multiplier + ".");
}
}
else if (isvalid && Integer.parseInt(input) >= 2 && Integer.parseInt(input) <= 9) {
int number = Integer.parseInt(input);
System.out.println("You chose" + number + " times table.");
System.out.print(number + " X " + multiplier + " = " + "? input your answer ==> ");
answer = s.nextInt();
if (answer == number * multiplier) {
System.out.print("You're right!");
} else {
System.out.print("Wrong! The right answer is " + number * multiplier + ".");
}
}
else {
System.out.print("Error. Please try again.");
}
}
public static boolean isNumeric(String str)
{
for (char c : str.toCharArray())
{
if (!Character.isDigit(c)) return false;
}
return true;
}
}
You can't send values like a , b, c etc for
Integer.parseInt(String s)
https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt(java.lang.String)
I have try catch block to catch numberformat exception with message to enter valid integer
public static void main(String args[]) {
System.out.println("let's start the multiplication game.");
System.out.println("which times table do you want to choose?");
System.out.println("if you want to do it by your choice, please input number among 2~9. Or if you want to do it randomly, please input number 0");
System.out.println("press \"q\" if you want to quit");
System.out.println("==>");
String input;
Scanner s = new Scanner(System.in);
input = s.nextLine();
int answer;
int multiplier = (int)(Math.random()*8+2);
int random = (int)(Math.random()*8+2);
try {
if (input.equals("q"))
{
System.out.print("quit the game.");
}
else if (Integer.parseInt(input) == 0)
{
System.out.println(random+"times table has been made automatically.");
System.out.print(random+" X "+multiplier+" = "+"? input your answer ==> ");
answer = s.nextInt();
if (answer == random*multiplier)
{
System.out.print("You're right!");
}
else
{
System.out.print("Wrong! The right answer is "+random*multiplier+".");
}
}
else if (Integer.parseInt(input)>=2 && Integer.parseInt(input)<=9)
{
int number = Integer.parseInt(input);
System.out.println("You chose"+number+" times table.");
System.out.print(number+" X "+multiplier+" = "+"? input your answer ==> ");
answer = s.nextInt();
if (answer == number*multiplier)
{
System.out.print("You're right!");
}
else
{
System.out.print("Wrong! The right answer is "+number*multiplier+".");
}
}
else
{
System.out.print("Error. Please try again.");
}
}
catch (NumberFormatException e ) {
System.out.print("pleae enter Valid integer");
}
It's obvious that you are getting this error because you are calling Integer.parseInt on a string variable which doesn't contain an Integer. What you should be doing is putting a check once you get the input to check if the string contains what you need. Something like below
while (true)
{
// Check that the input is between 0 and 9 or q.
if (!((input.charAt(0) >= '0' && input.charAt(0) <= '9') || input.charAt(0) == 'q'))
{
// If it is not, ask for input again.
System.out.println("Input is not correct. If you want to do it by your choice, please input number among 2~9. Or if you want to do it randomly, please input number 0");
input = s.nextLine();
}
else {
// If input is correct, break this look.
break;
}
}
Below is the whole code
public class game
{
public static void main(String[] args)
{
System.out.println("let's start the multiplication game.");
System.out.println("which times table do you want to choose?");
System.out.println("if you want to do it by your choice, please input number among 2~9. Or if you want to do it randomly, please input number 0");
System.out.println("press \"q\" if you want to quit");
System.out.println("==>");
String input;
Scanner s = new Scanner(System.in);
input = s.nextLine();
while (true)
{
if (!((input.charAt(0) >= '0' && input.charAt(0) <= '9') || input.charAt(0) == 'q'))
{
System.out.println("Input is not correct. If you want to do it by your choice, please input number among 2~9. Or if you want to do it randomly, please input number 0");
input = s.nextLine();
}
else {
break;
}
}
int answer;
int multiplier = (int) (Math.random() * 8 + 2);
int random = (int) (Math.random() * 8 + 2);
if (input.equals("q"))
{
System.out.print("quit the game.");
}
else if (Integer.parseInt(input) == 0)
{
System.out.println(random + "times table has been made automatically.");
System.out.print(random + " X " + multiplier + " = " + "? input your answer ==> ");
answer = s.nextInt();
if (answer == random * multiplier)
{
System.out.print("You're right!");
}
else
{
System.out.print("Wrong! The right answer is " + random * multiplier + ".");
}
}
else if (Integer.parseInt(input) >= 2 && Integer.parseInt(input) <= 9)
{
int number = Integer.parseInt(input);
System.out.println("You chose" + number + " times table.");
System.out.print(number + " X " + multiplier + " = " + "? input your answer ==> ");
answer = s.nextInt();
if (answer == number * multiplier)
{
System.out.print("You're right!");
}
else
{
System.out.print("Wrong! The right answer is " + number * multiplier + ".");
}
}
else
{
System.out.print("Error. Please try again.");
}
}
}
Verify input in two separate if/else blocks. Add this code to your "else" statement to catch strings other than "q".
else{
try {
int inputNumber = Integer.parseInt(input);
if(inputNumber == 0) {
// code..
} else if (inputNumber >= 2 && inputNumber <= 9) {
// code..
}
} catch(java.lang.NumberFormatException e) {
System.out.print("Error. Please try again.");
}
}
why don't use try catch?
if (input.equals("q")) {
System.out.print("quit the game.");
}
try {
Integer i = Integer.parseInt(input);
}catch (NumberFormatException e){
System.out.print("Error. Please try again.");
return;
}

I'm having trouble outputing the user's amount of guesses in a Hangman game

This is basically just a hangman project for my class and I'm not allowed to use arrays. The word is hidden with dashes to the user.The user has to pick a letter and the number of spaces they would like to check. The user has a certain amount of guess depending on the difficulty they choose. If the letter they guessed is in at least one of the spaces they chose then the user loses no guesses, if the letter they guessed is in none of the spaces they chose then the user loses a guess.
for example the output should look like
The secret word is: loops
The word is: -----
Please enter the letter you want to guess
k
Please enter the spaces you want to check (separated by spaces)
0 1 2 3
Your letter was not found in spaces you provided
Guesses Remaining: 14
But it currently looks like this
The secret word is: loops
The word is: -----
Please enter the letter you want to guess
k
Please enter the spaces you want to check (separated by spaces)
0 1 2 3
Your letter was not found in spaces you provided
Guesses Remaining: 14
Your letter was not found in spaces you provided
Guesses Remaining: 13
Your letter was not found in spaces you provided
Guesses Remaining: 12
Your letter was not found in spaces you provided
Guesses Remaining: 11
Here is what I have so far
package e;
import java.util.Scanner;
public class HangmanBeta{
private static final boolean testingMode = true;
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
keyboard.useDelimiter("\\n");
while (true) {
System.out.println("Enter your difficulty: Easy (e), Intermediate (i), or Hard (h)");
String diff = keyboard.next();
int amountOfSpaces = 0;
String response = "";
String guess = "";
String newGuess = "";
String letterInput = "";
int count = 0;
String newWord = "loops";//RandomWord.newWord();
int guesses = 0;
for (int i = 0; i < newWord.length(); i++) {
guess = newWord.replaceAll("[^#]", "-");
}
if ((diff.equalsIgnoreCase("e")) || (diff.equalsIgnoreCase("i")) || (diff.equalsIgnoreCase("h"))) {
if (diff.equalsIgnoreCase("e"))
{
guesses = 15;
}
if(diff.equalsIgnoreCase("i"))
{
guesses = 12;
}
if(diff.equalsIgnoreCase("h"))
{
guesses = 15;
}
if (testingMode == true)
{
System.out.println("The secret word is:" + " " + newWord);
}
System.out.println("The word is:" + " " + guess);
while(!newWord.equalsIgnoreCase(guess))
innerloop:
{ while(true)
{
System.out.println("Please enter the letter you want to guess");
letterInput = keyboard.next();
letterInput = Character.toString(letterInput.charAt(0));
if(!Character.isLetter(letterInput.charAt(0)))
{
System.out.println("Your input is not valid, try again");
break;
}
if(letterInput.equalsIgnoreCase("solve"))
{
System.out.println("Please solve the answer:");
String userSolve = keyboard.next();
if (!userSolve.equalsIgnoreCase(newWord))
{
System.out.println("That is not the secret word");
guesses = guesses - 1;
System.out.println("Guesses remaining: " + guesses);
}
else
{
System.out.println("You win!");
System.out.println("You have guessed the word! Congratulations");
System.out.println("Would you like to play again? Yes(y) or No (n)");
response = keyboard.next();
if (response.equalsIgnoreCase("n"))
{
System.exit(0);
}
if(response.equalsIgnoreCase("y"))
{
continue;
}
}
}
System.out.println("Please enter the spaces you want to check (separated by spaces)");
String spaces = keyboard.next();
amountOfSpaces = spaces.length();
if (diff.equalsIgnoreCase("e"))
{
if(amountOfSpaces != 7)
{
System.out.println("Your input is not valid, try again");
break innerloop;
}
}
if (diff.equalsIgnoreCase("i"))
{
if(amountOfSpaces != 5)
{
System.out.println("Your input is not valid, try again");
break innerloop;
}
}
if (diff.equalsIgnoreCase("h"))
{
if(amountOfSpaces != 3)
{
System.out.println("Your input is not valid, try again");
break innerloop;
}
}
for ( String a : spaces.split("\\s"))
{
int x = Integer.valueOf(a);
if (x > guess.length())
{
System.out.println("Your input is not valid, try again");
break innerloop;
}
if (Character.toLowerCase(newWord.charAt(x)) == letterInput.charAt(0))
{
//System.out.println("Guess is correct for position " + x);
guess = guess.substring(0, x) + letterInput + guess.substring(x + 1, guess.length());
}
if (Character.toLowerCase(newWord.charAt(x)) != letterInput.charAt(0))
{
guesses= guesses - 1;
System.out.println("Your letter was not found in spaces you provided");
System.out.println("Guesses Remaining: " + guesses);
}
if (guesses == 0)
{
System.out.println("You have failed to guess the word....:(");
System.out.print("Would you like to play again? Yes(y) or No(n)");
response = keyboard.next();
if (response.equalsIgnoreCase("n"))
{
System.exit(0);
}
if(response.equalsIgnoreCase("y"))
{
continue;
}
}
}
}
if (newWord.equalsIgnoreCase(guess))
{
System.out.println("You win!");
System.out.println("You have guessed the word! Congratulations");
System.out.println("Would you like to play again? Yes(y) or No (n)");
response = keyboard.next();
if (response.equalsIgnoreCase("n"))
{
System.exit(0);
}
if (response.equalsIgnoreCase("y"))
{
continue;
}
}
}
System.out.println("Your Guess is in the word");
}
if(guesses == guesses - 1)
{
//System.out.print(spaces.split("\\s").length);
//System.out.println("Your Guess is in the word");
//System.out.println();
//System.out.println("Updated word " + guess);
//System.out.println("Guesses Remaining: " + guesses);
}
}
}
}
In the example I used the difficulty was set to easy.
There is a bug here:
if (Character.toLowerCase(newWord.charAt(x)) != letterInput.charAt(0))
{
guesses= guesses - 1;
System.out.println("Your letter was not found in spaces you provided");
System.out.println("Guesses Remaining: " + guesses);
}
You cannot print the message directly because you need to make sure all spaces are not matched. This should be work:
public class HangmanBeta {
private static final boolean testingMode = true;
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
keyboard.useDelimiter("\\n");
while (true) {
System.out.println("Enter your difficulty: Easy (e), Intermediate (i), or Hard (h)");
String diff = keyboard.next();
int amountOfSpaces = 0;
String response = "";
String guess = "";
String newGuess = "";
String letterInput = "";
int count = 0;
String newWord = "loops";//RandomWord.newWord();
int guesses = 0;
for (int i = 0; i < newWord.length(); i++) {
guess = newWord.replaceAll("[^#]", "-");
}
if ((diff.equalsIgnoreCase("e")) || (diff.equalsIgnoreCase("i")) || (diff.equalsIgnoreCase("h"))) {
if (diff.equalsIgnoreCase("e")) {
guesses = 15;
}
if (diff.equalsIgnoreCase("i")) {
guesses = 12;
}
if (diff.equalsIgnoreCase("h")) {
guesses = 15;
}
if (testingMode == true) {
System.out.println("The secret word is:" + " " + newWord);
}
System.out.println("The word is:" + " " + guess);
while (!newWord.equalsIgnoreCase(guess))
innerloop:
{
while (true) {
System.out.println("Please enter the letter you want to guess");
letterInput = keyboard.next();
letterInput = Character.toString(letterInput.charAt(0));
if (!Character.isLetter(letterInput.charAt(0))) {
System.out.println("Your input is not valid, try again");
break;
}
if (letterInput.equalsIgnoreCase("solve")) {
System.out.println("Please solve the answer:");
String userSolve = keyboard.next();
if (!userSolve.equalsIgnoreCase(newWord)) {
System.out.println("That is not the secret word");
guesses = guesses - 1;
System.out.println("Guesses remaining: " + guesses);
} else {
System.out.println("You win!");
System.out.println("You have guessed the word! Congratulations");
System.out.println("Would you like to play again? Yes(y) or No (n)");
response = keyboard.next();
if (response.equalsIgnoreCase("n")) {
System.exit(0);
}
if (response.equalsIgnoreCase("y")) {
continue;
}
}
}
System.out.println("Please enter the spaces you want to check (separated by spaces)");
String spaces = keyboard.next();
amountOfSpaces = spaces.length();
if (diff.equalsIgnoreCase("e")) {
if (amountOfSpaces != 7) {
System.out.println("Your input is not valid, try again");
break innerloop;
}
}
if (diff.equalsIgnoreCase("i")) {
if (amountOfSpaces != 5) {
System.out.println("Your input is not valid, try again");
break innerloop;
}
}
if (diff.equalsIgnoreCase("h")) {
if (amountOfSpaces != 3) {
System.out.println("Your input is not valid, try again");
break innerloop;
}
}
int numSpacesLeft = spaces.split("\\s").length;
for (String a : spaces.split("\\s")) {
int x = Integer.valueOf(a);
if (x > guess.length()) {
System.out.println("Your input is not valid, try again");
break innerloop;
}
if (Character.toLowerCase(newWord.charAt(x)) == letterInput.charAt(0)) {
//System.out.println("Guess is correct for position " + x);
guess = guess.substring(0, x) + letterInput + guess.substring(x + 1, guess.length());
}
numSpacesLeft--;
if (Character.toLowerCase(newWord.charAt(x)) != letterInput.charAt(0)) {
if (numSpacesLeft == 0) {
guesses = guesses - 1;
System.out.println("Your letter was not found in spaces you provided");
System.out.println("Guesses Remaining: " + guesses);
}
}
if (guesses == 0) {
System.out.println("You have failed to guess the word....:(");
System.out.print("Would you like to play again? Yes(y) or No(n)");
response = keyboard.next();
if (response.equalsIgnoreCase("n")) {
System.exit(0);
}
if (response.equalsIgnoreCase("y")) {
continue;
}
}
}
}
if (newWord.equalsIgnoreCase(guess)) {
System.out.println("You win!");
System.out.println("You have guessed the word! Congratulations");
System.out.println("Would you like to play again? Yes(y) or No (n)");
response = keyboard.next();
if (response.equalsIgnoreCase("n")) {
System.exit(0);
}
if (response.equalsIgnoreCase("y")) {
continue;
}
}
}
System.out.println("Your Guess is in the word");
}
if (guesses == guesses - 1) {
//System.out.print(spaces.split("\\s").length);
//System.out.println("Your Guess is in the word");
//System.out.println();
//System.out.println("Updated word " + guess);
//System.out.println("Guesses Remaining: " + guesses);
}
}
}
}
Hop this could help you!

I have to create a High Low game. I don't understand why it won't work

public static void main(String[] args) {
int money = 100, roll1, roll2;
int userBet;
char c;
int lostwin;
Scanner in = new Scanner(System.in);
do {
if (money == 0 || money < 0)
break;
System.out.println(" You have " + money + " dollars. ");
userBet = getBet(in, money);
if (userBet == 0)
break;
c = getHighLow(in);
roll1 = getRoll();
System.out.println(" Die 1 rolls : " + roll1);
roll2 = getRoll();
System.out.println(" Die 2 rolls : " + roll2);
System.out.println("Total of two dice is: " + (roll1 + roll2));
lostwin = determineWinnings(c, userBet, roll1 + roll2);
if (lostwin < 0)
System.out.println("You lost!");
else
System.out.println("You won " + lostwin + " dollars! ");
money = money + lostwin;
} while (true);
}
private static int getBet(Scanner inScanner, int moneyPot) {
System.out.println("Enter an amount to bet (0 to quit): ");
int result = inScanner.nextInt();
if (result > moneyPot) {
do {
System.out.println("Enter an amount to bet (0 to quit): ");
result = inScanner.nextInt();
} while (result > moneyPot);
}
return result;
}
private static char getHighLow(Scanner inScanner) {
System.out.println("High, low or sevens (H/L/S): ");
String str = inScanner.next();
return str.charAt(0);
}
private static int getRoll() {
return (int) (Math.random() * 6) + 1;
}
private static int determineWinnings(char highLow, int bet, int roll) {
int result = 0;
if (highLow == 'H') {
if (roll < 7) {
result = -1 * bet;
} else {
result = bet;
}
}
if (highLow == 'L') {
if (roll > 7) {
result = -1 * bet;
} else {
result = bet;
}
}
if (highLow == 'S') {
if (roll == 7) {
result = 4 * bet;
} else {
result = -1 * bet;
}
}
return result;
}
I need the program to say "Goodbye!" when the user enters the number 0, but I can't figure out where to put it or how to get it to work. The other issue I need help with is if the user enters a number higher than 100 or less than 1, the program needs to say "Your bet MUST be between 0 and 100 dollars". I don't know where to put them or how to get them to work.
You can modify your getBet function like this to achieve what you want.
private static int getBet(Scanner inScanner, int moneyPot) {
int result;
System.out.println("Enter an amount to bet (1-100) (0 to quit): ");
do {
result = inScanner.nextInt();
if (result == 0) {
System.out.println("Good Bye");
return result;
} else if (result < 0 && result > 100) {
System.out.println("Please enter an amount between (1-100) (0 to quit)");
} else if (result > moneyPot) {
System.out.println("Please enter an amount less than your moneyPot between (1-100) (0 to quit)");
} else {
return result;
}
} while (true);
}
public static void main(String[] args) {
int money = 100;
int roll1;
int roll2;
int userBet;
int lostwin;
char c;
Scanner in = new Scanner(System.in);
do {
if (money < 1)
break;
System.out.println(" You have " + money + " dollars. ");
userBet = getBet(in, money);
if (userBet == 0)
break;
c = getHighLow(in);
roll1 = getRoll();
System.out.println(" Die 1 rolls : " + roll1);
roll2 = getRoll();
System.out.println(" Die 2 rolls : " + roll2);
System.out.println("Total of two dice is: " + (roll1 + roll2));
lostwin = determineWinnings(c, userBet, roll1 + roll2);
if (lostwin < 0)
System.out.println("You lost!");
else
System.out.println("You won " + lostwin + " dollars! ");
money = money + lostwin;
} while (money > 0);
System.out.println("Goodbye!");
}
private static int getBet(Scanner inScanner, int moneyPot) {
int bet;
do {
System.out.println("Enter an amount to bet (0 to quit): ");
bet = inScanner.nextInt();
} while (bet > moneyPot && bet != 0);
return bet;
}
private static char getHighLow(Scanner inScanner) {
System.out.println("High, low or sevens (H/L/S): ");
String str = inScanner.next();
return str.charAt(0);
}

Best Before Puzzle [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Spotify puzzle problem
Been working on this puzzle because I am new to Java and would like to learn it. SO, I have been solving this puzzle for Spotify. But everytime I submit it. It says wrong answer. Im pretty sure its right though can anyone see what I am missing. This is the problem. http://www.spotify.com/us/jobs/tech/best-before/
Here is my solution
import java.io.*;
import java.util.Arrays;
public class best_before {
static boolean next;
static String month, day, year;
public static void main(String[] args) throws IOException{
//Setup to grab the input
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String input = "";
input = br.readLine();
//Spilt the input to grab each integer entered by user
String bits = input;
String[] tokens = bits.split("/");
int a_value1 = Integer.parseInt(tokens[0]);
int b_value1 = Integer.parseInt(tokens[1]);
int c_value1 = Integer.parseInt(tokens[2]);
//Sort the array in order from lowest to highest
int[] int_array = new int[] {a_value1, b_value1, c_value1};
Arrays.sort(int_array);
int a_value = int_array[0];
int b_value = int_array[1];
int c_value = int_array[2];
year = Integer.toString(a_value);
month = Integer.toString(b_value);
day = Integer.toString(c_value);
//Check the integers entered to put them in the right order
int check_days = Integer.parseInt(day);
int check_month = Integer.parseInt(month);
int check_year = Integer.parseInt(year);
//Check to make sure none of the values are a negative integer
if(check_days < 0){
System.out.println(input + " is illegal");
System.exit(0);
}
else if(check_month < 0){
System.out.println(input + " is illegal");
System.exit(0);
}
else if(check_year < 0){
System.out.println(input + " is illegal");
System.exit(0);
}
//Will only change the values around if the highest date in the array is bigger than 31
if(check_days > 31){
//Only reorganize if year if larger than month
if(check_month > check_year){
month = Integer.toString(check_year);
}
//Otherwise just keep month at its current value
else{
month = Integer.toString(check_month);
}
//Change date and year around since one is bigger than the other
year = Integer.toString(check_days);
day = Integer.toString(check_month);
}
else if(check_year == 0){
if(check_month < check_days){
month = Integer.toString(check_month);
}
else{
month = Integer.toString(check_days);
}
}
//Get the length so I can zero pad the numbers
int length_year = year.length();
int length_month = month.length();
int length_day = day.length();
//Doing my zero pad thing right here
if(length_year == 1){
year = "200" + year;
}
else if(length_year == 2){
year = "20" + year;
}
else if(length_year == 3){
year = "2" + year;
}
if(length_month == 1){
month = "0" + month;
}
if(length_day == 1){
day = "0" + day;
}
//A last check to make sure everything is Kosher
int last_check = Integer.parseInt(year);
int last_check_month = Integer.parseInt(month);
int last_check_day = Integer.parseInt(day);
//Checking to see if it is a leap year. Is the year Divisible by 4?
if (last_check % 4 == 0) {
// Is the year Divisible by 4 but not 100?
if (last_check % 100 != 0) {
next = true;
}
// Is the year Divisible by 4 and 100 and 400?
else if (last_check % 400 == 0) {
next = true;
}
// It is Divisible by 4 and 100 but not 400!
else {
next = false;
}
}
// It is not divisible by 4.
else {
next = false;
}
//Check to make sure the date is legal and valid :)
if(last_check > 2999 || last_check < 2000)
{
//Date must be between 2000 and 2999 inclusive
System.out.println(input + " is illegal");
}
else if(last_check_month > 12)
{
//Date month must be less than 12
System.out.println(input + " is illegal");
}
else if(last_check_day > 31)
{
//Date day must be less than 31
System.out.println(input + " is illegal");
}
else if(next == false && last_check_day > 28 && last_check_month == 2){
//if next is false and the day is greater than 28 and its not a leap year something is wrong
System.out.println(input + " is illegal");
}
else if(next == true && last_check_day > 29){
//if next is true and the day is greater than 29 and it is a leap year something is wrongs
System.out.println(input + " is illegal");
}
else if(last_check_month == 4 && last_check_day > 30){
System.out.println(input + " is illegal");
}
else if(last_check_month == 6 && last_check_day > 30){
System.out.println(input + " is illegal");
}
else if(last_check_month == 9 && last_check_day > 30){
System.out.println(input + " is illegal");
}
else if(last_check_month == 11 && last_check_day > 30){
System.out.println(input + " is illegal");
}
else if(last_check == 2000){
//Check to make sure there are no other days that are zero too because you cant have two zeros
if(last_check_day == 0 || last_check_month == 0){
System.out.println(input + " is illegal");
}
else{
System.out.print(year + "-" + month + "-" + day);
}
}
else{
System.out.print(year + "-" + month + "-" + day);
}
}
}
Your program fails for the input 31/9/73, where it returns 2073-09-31 instead of 31/9/73 is illegal. Since September only has 30 days, your program should check for September (and a couple of other months), and output the error.
In the updated version, your program still fails the input 1/2/31; it should give 2031-1-2.
By the way, the main intent behind these puzzles is not to solve them, but to solve them elegantly. Try reducing the number of variables, and avoiding duplicate lines etc.

Categories