The code isn't working for some reason [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I'm making a thingy that takes 3 inputs like "1500, 1 and 1" or "1500, January and 1" and returns "January 1st, 1500" or "1/1/1500", i had some problems on the day part but someone already told me how to fix it, and now I'm having problems with the month part, i made this kinda fast and i haven't figured out why it isn't working, it SHOULD see if the input is a valid month, if it is then it outputs the month(this part is just for testing), and if it isn't then it should say "please use a valid month or a number between 1 and 12", but when i write anything that isn't a month it just stops, and doesn't output anything, even if i put a month after it just doesn't do anything, i tried to see if there was any errors but i didn't found any, this is the code that i used:
Scanner scan = new Scanner(System.in);
String mx;
System.out.println("Insert Month");
String[] mm = {"january","february","march","april","may","june","july","august","september","october","november","december"};
int mz = 0;
while (0 < 1){
mx = scan.nextLine();
mx = mx.toLowerCase();
for(int i = 0; i < 11; i++){
if (mx.equals(mm[i])){
mz = i + 1;
break;
}
else {
if(i == 11){
System.out.println("please use a valid month or a number between 1 and 12");
}
else{
}
}
}
//}
if(mz > 0){
break;
}
else {}
}
System.out.println(mx);

The reason your program just "stops" is that you only print the statement "please enter a valid month..." if i == 11 and you have your for loop break if i >= 11. Thus, this condition will never be met. The while loop keeps running, even though this statement isnt printed. You could have entered a non-month string on the first try, and then a month string on the second and your while loop would have been broken.
Here is how I have improved your code to work for taking in the month. Pay attention to subtle changes of highlighted. These are important for writing better, more readable code:
Scanner scan = new Scanner(System.in);
//initialize to empty string
String mx = "";
System.out.println("Insert Month");
//use good naming conventions for easier code readability
String[] validMonths = {"january","february","march","april","may","june","july","august","september","october","november","december"};
//using a boolean to break makes much more sense than the way you have written it with an infinite loop and a manual break statement
boolean noMonth = true;
while (noMonth){
mx = scan.nextLine();
for(int i = 0; i < 12; i++){
//rather than convert to lowercase, use this handy String method
//also compares for valid number entries
if (mx.equalsIgnoreCase(validMonths[i]) || mx.equals(Integer.toString(i+1))){
noMonth = false;
break;
}
}
if(noMonth){
System.out.println("please use a valid month or a number between 1 and 12");
}
}
System.out.println(mx);
Create a new while loop to take in the day and a new one to take in the year after these, checking for valid input. Also, every if does not require an else in Java.

You're not using meaningful variable names, making your code a little bit hard to read and maintain. So, I had to create you the following code from scratch:
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
String month = getMonthName(getInt("Enter Month: ", keyboard) - 1);
int day = getInt("Enter Day: ", keyboard);
int year = getInt("Enter Year: ", keyboard);
System.out.printf("%s %d, %d\n", month, day, year);
}
public static String getMonthName(final int monthNo)
{
String[] months = {"january","february","march","april","may","june","july","august","september","october","november","december"};
return months[monthNo];
}
public static int getInt(final String msg, Scanner keyboard)
{
System.out.print(msg);
return keyboard.nextInt();
}
The code above does NOT perform and input validation, as you may have noticed already. If you want to validate month input for example, your if condition may look something like this:
if (month < 0 || month < 12)
{
System.out.println("Invalid month number entered");
System.exit(0);
}

Related

Sum of digits using Java [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I am a beginner in programming and I am trying to output the sum of digits of the user input using Java.
The code should say certain message based on the length of the digit and end it when user types a blank space.
My code executes correctly. However, it only works on the first input. After the first input, I get an error message.
How can I possibly fix my code, so that my while loops work efficiently?
//scanner
Scanner input = new Scanner (System.in);
//ask user for a credit card number
System.out.print("Enter a credit card number (enter a blank line to quit): ");
String userNum = input.nextLine();
//length and last char of string
int len = userNum.length();
char lastDigit = userNum.charAt(len-1);
//initial values
int sumOfDigits = 0;
int strNum = 0;
int i;
//loops
while (len > 0) {
if (len == 16) { //when length equals 16
for (i = 0; i < 15; ++i ) { //calculates sum of digits
String s = userNum.substring(i, i+1);
strNum = Integer.parseInt(s);
sumOfDigits = sumOfDigits + strNum;
}
System.out.println("DEBUG: Sum is " + sumOfDigits);
System.out.println("Check digit is: " + lastDigit);
System.out.println();
System.out.print("Enter a credit card number (enter a blank line to quit): ");
userNum = input.next();
}
else if (userNum.equals("")) { //when user types blank space
System.out.println("Goodbye!");
}
else { //when user digit is not 16, nor types a blank space
System.out.println("ERROR! Number MUST have exactly 16 digits.");
System.out.println();
System.out.print("Enter a credit card number (enter a blank line to quit): ");
userNum = input.next();
}
}
//input close
input.close();
}
The main problem I can see is that you're not recalculating things from the newly-entered strings. I'd guess the specific problem is that len is not recalculated, meaning that you will enter the same branch in the conditional statement on each loop iteration.
Put all of the reading-from-input stuff in one place, and move all the variables you can into the loop:
while (true) {
System.out.print("Enter a credit card number (enter a blank line to quit): ");
// Read it.
String userNum = input.nextLine();
if (userNum.equals("")) {
System.out.println("Goodbye!");
break;
}
if (len == 16) {
// Derive the values you want from it.
//length and last char of string
int len = userNum.length();
char lastDigit = userNum.charAt(len-1);
// ..
} else {
// Print an error... but allow the loop to execute again.
}
}
In this way, you don't have to worry about forgetting to reinitialize variables, or making sure printed messages are the same to enter another value, and you don't have differing ways of reading from the input (your code contains both input.next and input.nextLine, for instance).

Multiple Choice and True/False Quiz using loops [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I'm trying to build a quiz for a user that has to have 5 multiple choice questions and 5 true/false questions. I must do this using loops (while loops). I've come to the point where I set up a separate method asking the user the questions and error checking for the true/false or multiple choice questions. I now have to somehow give the user a point if they answer each question correctly. Then in the end, I must give the user the the total amount of points they won. Then I have to ask if they want to play again in the end, if they say yes I have to go back to the first question and restart the game and if they say no the program has to close. Here is where I got to on my main method. I started putting a while loop for the first answer (correct answer being 3) and making a point variable but I'm not sure where to go from there and how to connect everything. I hope what I did so far is correct. Thanks!
UserInteraction input = new UserInteraction();
Questions ask = new Questions();
int answer1 = 0, answer2 = 0, answer3 = 0, answer4 = 0, answer5 = 0;
int a1 = ask.Question1(answer1);
int point;
while (a1==3)
{point = 1;
}
int a2 = ask.Question2(answer2);
int a3 = ask.Question3(answer3);
int a4 = ask.Question4(answer4);
int a5 = ask.Question5(answer5);
boolean answer6=false, answer7=false, answer8=false, answer9=false, answer10=false;
String a6 = ask.Question6(answer6);
String a7 = ask.Question7(answer7);
String a8 = ask.Question8(answer8);
String a9 = ask.Question9(answer9);
String a10 = ask.Question10(answer10);
For the Questions methods, I'll put two blank examples on here.
{public int Question1 (int answer1)
{String message = "";
int smallestValue = 1;
int largestValue = 4;
System.out.println("Q1) What is...?");
System.out.println("1: ....");
System.out.println("2: ......");
System.out.println("3: ......");
System.out.println("4: ......");
System.out.print("Enter the number");
Scanner input = new Scanner(System.in);
UserInteraction input2 = new UserInteraction();
answer1 = input2.getIntValueFromUserBetween(message, smallestValue, largestValue);
return answer1;
}
public String Question6(boolean answer10)
{String message = "";
System.out.println("(Q10) ....(true/false)");
System.out.print("Enter your answer here: ");
Scanner input = new Scanner(System.in);
UserInteraction input2 = new UserInteraction();
answer10 = input2.confirm(message);
return "" + answer10;
}
}
Sorry if I misunderstand your question, but I don't understand why you're using a loop here.
while (a1==3)
Your program is either going to get stuck here or never use it. What I mean is that if the user answers the question correctly (i.e 3), they will be stuck in the while loop until you set a1 != 3.
What I think is a better solution is using selection. For example:
if (a1 == 3) {
point += 1; // point = point + 1
// Or whatever functionality you need here
}
Edit: If you really must use a loop, then having a Boolean flag would be the way to go. For example:
Boolean flag = false;
if (a1 == 3) {
flag = true;
while (flag) {
point += 1; //point = point + 1
// Make sure that you set flag equals to false at the end of the loop though, otherwise it will infinitely loop
// Include any other functionality needed
flag = false;
}
}
Is this similar to what your looking for?
int correct;
public void quiz() { // this is so you can restart quiz easily
String[] answers = String[5];
//add answers to array, set them to variables/constant first then index
String[] questions = String[5];
// add questions to array
for(int i = 0; i <= questions.length; i++) { // stops after all questions have been asked, make sure its "<="
System.out.println(questions[i]); // prints question 1 first loop then 2 and so on
// read input from user
if(input == answers[i]) { // you may have to convert input to correct type
correct += 1;
}
}
}
System.out.println("You got " + correct + " correct answers");
System.out.println("Would you like to play again?");
if(input == yes) {
quiz(); //starts quiz again // starts quiz method again
P.S. sorry if I've misunderstood the question
To ask different questions you can just change the String variables then call quiz() to ask those questions. nice and simple :)

Cost Calculator

My code needs to calculate the cost of ISP service via 3 different questions.
choice of package (1,2,3)
Which month it is: (1-12)
How many hours used:(x)
I broke the months into 3 separate arrays. One for Feb. with 28 days, one for months with 30 days and one with months that have 31 days. I need to check the number of hours entered and make sure that it does not exceed the amount of hours that are in whichever month they have chosen. I have started to with this:
import java.util.Scanner; //Needed for the scanner class
public class ISP_Cost_Calc
{
public static void main(String[] args)
{
String input; //To hold users input.
char selectPackage; //To hold Internet Package
double hourUsage, totalCharges, addCharges; //Variables
Scanner keyboard = new Scanner(System.in); //Create a Scanner object to collect keyboard input.
int[] twentyeightArray; //List of months with 28 days (that's what the te is for)
twentyeightArray = new int[1]; //Make room for one integer in list
twentyeightArray[0] = 2; //Set the one integer in this list to month number 2
int[] thirtyArray; //List of months with 30 days.
thirtyArray = new int[4];
thirtyArray[0] = 4;
thirtyArray[1] = 6;
thirtyArray[2] = 9;
thirtyArray[3] = 11;
int[] thiryoneArray; //List of months with 31 days.
thiryoneArray = new int[7];
thiryoneArray[0] = 1;
thiryoneArray[1] = 3;
thiryoneArray[2] = 5;
thiryoneArray[3] = 7;
thiryoneArray[4] = 8;
thiryoneArray[5] = 10;
thiryoneArray[6] = 12;
//Prompt the user to select a Internet Package.
System.out.print("Enter your plan (1, 2, 3):");
input = keyboard.nextLine();
selectPackage = input.charAt(0);
//Prompt the user for the month.
System.out.print("Enter your month number (1-12):");
input = keyboard.nextLine();
char monthNum = input.charAt(0);
//Prompt the user for how many hours used.
System.out.print("Enter your hours:");
input = keyboard.nextLine();
hourUsage = Double.parseDouble(input);
//Display pricing for selected package...
switch (selectPackage)
{
case '1':
if (hourUsage > 10)
{
addCharges = hourUsage - 10;
totalCharges = (addCharges * 2.0) + 9.95;
System.out.println("You have used " + hourUsage + " hours and your total is $" + totalCharges + " per month. ");
}
else
{
System.out.println("Your total is $9.95 per month.");
}
break;
case '2':
if (hourUsage > 20 )
{
addCharges = hourUsage - 20;
totalCharges = (addCharges * 1.0) + 13.95;
System.out.println("You have used " + hourUsage + " and your total is $" + totalCharges + " per month.");
}
else
{
System.out.println("Your total is $13.95 per month.");
}
break;
case '3':
System.out.println("Your total is $19.95 per month.");
break;
default:
System.out.println("Invalid Choice.");
}
}
}
So I just need advice with how to incorporate this into my if statements.
Thank you
Instead of using separate arrays to implement your month. You can do this:
int[] month = {31,28,31,30,31,30,31,31,30,31,30,31};
int[] monthLeapYear = {31,29,31,30,31,30,31,31,30,31,30,31};
You can check whether a given year is a leap year first, then choose the right array to use for the month. This way you only need 2 arrays - ever.
and you may have something like this to help you. I also advise you to create some methods in your implementation to modularize your program.
public static Boolean isLeapYear(int year)
{
if(year % 4 == 0 && year % 100 != 0)
return true;
return false;
}
The array is by index 0 - 11. That be can be over come by doing this:
//Let say your current month is 1-12
month[currentMonth-1]
Alternatively add 1 element to your array (so that the elements tally now):
int[] month = {0,31,28,31,30,31,30,31,31,30,31,30,31};
It may be easier if instead of using seperatre arrays for different numbers of days, you use an enum of Months which contains the number of days and the number of hours.
public enum Month {
JANUARY(31),FEBRUARY(28),MARCH(31),APRIL(30),MAY(31),JUNE(30),JULY(31),AUGUST(30),SEPTEMBER(30),OCTOBER(31),
NOVEMBER(30),DECEMBER(31);
private int hours;
private Month(int days){
hours = days*24;
}
public int getHours(){
return hours;
}
}
Using something like that would cut down on the unnecessary array use and combine everything into a single class. This would make it a lot easier to get the number of days and hours in each month.
Instead of creating multiple arrays, just use one array like:
month[0] = 31;
month[1] = 28;//what if leap year?
month[2] = 31;
//and so on
Then you could do something like:
int monthNumber = monthNum - 48;
if (hours > month[monthNumber - 1] * 24) {
//do something
} else {
//else do another thing
}
This is insane.
What is going to happen in 2016 when February will have 29 days instead of 28 days?
Stop using integers to represent hours. Use proper data types like DateTime and TimeSpan.
Get the DateTime at 00:00 of the 1st day of the selected month,
then get the DateTime at 00:00 of the 1st day of the next month,
then calculate the difference of these two to obtain a TimeSpan holding the duration of the selected month.
Then convert your hours to a TimeSpan and compare this against the duration of the selected month.
This will tell you whether the entered number of hours fits within the selected month.
To check conditions based on your months.You can use contains method of arraylist by converting array into arraylist as
Arrays.asList(your1stArray).contains(yourChar)
in your char just add the input no of the month
for eg:
switch (monthNum )
{
case '1':
if (Arrays.asList(your1stArray).contains(yourChar)){
//code goes here
}
case '1':
if (Arrays.asList(your2ndArray).contains(yourChar)){
//code goes here
}
)
)

Making a hangman game [duplicate]

This question already has answers here:
Creating hangman game without arrays [closed]
(3 answers)
Closed 9 years ago.
Logic:
This is how the output should look like. http://prntscr.com/1is9ht i need to find the index of guess in the orginalString. If that's true then it should replace the question mark at the index with the character read in the string guess. After that it should take out that char from the string "abcdefghijklmnopqrstuvwxyz".
If originalString doesn't contain guess than it should only take out that char from the string "abcdefghijklmnopqrstuvwxyz" I looked up this question on google and found a bunch of codes, they were all using arrays or something that I have not learned in the classes. So please don't use arrays. I am stuck at the if else statement. Is there any way to solve this problem without using Arrays.
int count=1;
while (count<=24){
Scanner keyboard = new Scanner(System.in);
int length;
String originalString;
String guess;
String option= "abcdefghijklmnopqrstuvwxyz";
String questionmarks;
System.out.println("Please enter a string");
originalString=keyboard.nextLine();
length=originalString.length();
questionmarks = originalString.replaceAll(".", "?");
System.out.println("Original String: "+originalString);
System.out.println("Guessed String: "+questionmarks);
System.out.println("Characters to choose from: "+option);
System.out.println("Please guess a character");
guess=keyboard.nextLine();
if (originalString.contains(guess)){
count++;
}
else{
option.replace(guess, "_");
count++;
System.out.println(option);
}
Please suggest me some code that doesn't implement array concept for my problem,
Any help will be appreciated
A few things that I noticed from a cursory glance:
.replace() returns a String, it will not modify option unless you do:
option = option.replace(guess, "_");
Also, since you don't want to use Arrays, I highly suggest that you use StringBuilder
EDIT 1 (based off of comment from duplicate thread):
You can use a StringBuilder to have a String that's initialized to all -. Then when someone guess a correct letter, you can replace the - with the guess.
StringBuilder sb_word = new StringBuilder(lengthOfOriginalString);
for (int i = 0; i < length; i++)
sb_word.append('-'); //add hyphens to StringBuilder, StringBuffer would also work
You should really use something like:
final char blank = '-';
Then, after someone makes a guess, if you've determined that the character at position i should be replaced by guess, you could do:
sb_word.setCharAt(i, guess.charAt(0));
EDIT 2:
while (bodyparts > 0 && !win) //play game while you have bodyparts and haven't won
{
System.out.printf("Word to guess: %s\nEnter a letter or word guess: " , sb_word);
guess = keyboard.next();
if (guess.length() == 1)
{
for (int i = 0; i < length; i++) //loop to see if guess is in originalString
if (Character.toLowerCase(word.charAt(i)) ==
Character.toLowerCase(guess.charAt(0)))
{ //it is, so set boolean contains to be true and replace blank with guess
sb_word.setCharAt(i, guess.charAt(0));
contains = true;
}
if (!contains)
{
bodyparts--;
System.out.printf("Incorrect, you have %d bodyparts left.\n", bodyparts);
}
else if (sb_word.indexOf(String.valueOf(blank)) == -1)
{ //all the letters have been uncovered, you win
win = true;
System.out.println(word);
}
else
{
contains = false;
System.out.println("Good guess.");
}
}
else
{
if (guess.equals(word))
win = true;
else
{
bodyparts = 0;
System.out.printf("Incorrect, you have %d bodyparts left.\n" , bodyparts);
}
}
}

Problems with exception handling using try and catch

I'm trying to use try and catch. If the entered input isn't valid the loop sould repeat and ask the user for input again, but it's not working. When I type something wrong it just repeats the System.out.println.
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;
public class Price
{
public static void main(String[] args)
{
userInput();
}
public static void userInput()
{
Scanner scan = new Scanner(System.in);
int x = 1;
int month, day, year;
do {
try {
System.out.println("Please enter a month MM: ");
month = scan.nextInt();
if(month>12 && month<1)
{
System.out.println("FLOP");
}
x=2;
}
catch(Exception e){
System.out.println("not today mate");
}
}
while(x==1);
}
}
this is a working solution to your problem
public static void userInput(){
Scanner scan = new Scanner(System.in);
int x = 1;
int month, day, year;
System.out.println("Please enter a month MM: ");
month = scan.nextInt();
boolean i = true;
while(i == true)
{
if(month < 12 && month > 1)
{
System.out.println("FLOP");
i = false;
}
else if(month >= 12 || month <= 1)
{
System.out.println("not today mate");
month = scan.nextInt();
}
}
}
As a general rule, exceptions are used for exceptional circumstances, not to drive the logic of a program. Validating inputted data is not an exceptional circumstance in this case. It's a normal state of affairs that a user might make an error and enter an incorrect number. Put the input in a loop and repeat until a correct value is entered (perhaps with an option for the user to cancel).
First your condition is wrong.
You have:
if(month>12 && month<1)
{
System.out.println("FLOP");
}
So month cannot be bigger than 12 and at the same time less than 1.
I think you wanted to put OR instead of AND, e.g.
if(month > 12 || month < 1)
{
System.out.println("FLOP");
}
As for the exception, it might occur when user enters non numeric value or input is exausted.
Throws:
InputMismatchException - if the next token does not match the Integer regular expression, or is out of range
NoSuchElementException - if input is exhausted
IllegalStateException - if this scanner is closed

Categories