Trouble evaluating user input - java

So I've been working on this Java program where the computer asks the user if he wants to know the square of a number. If the user's answer is either 'Y' or 'y', the computer asks the user the number he wants he wants to know the square of, and prints the square of the number. Then the computer asks the user if he wants to know the square of another number. If answer is 'Y' or 'y', the computer takes a number and prints the square. The user is again asked if he wants to know the square of another number. Like this it goes on.
I've also written code for cases where the user's answer is negative, or neither positive nor negative. By this, I meant cases where the user's answer is 'N' or 'n'. This program runs into a problem somewhere, and does not work from A to Z the way I want it to. See, when I run the code, the computer asks me if I want to know the square of a number, and I enter 'y'. I then get asked the number I want to know the square of. I enter the number and the computer prints out its square. Then I get asked if I want to know the square of another number. I enter 'y'. Then I am asked the number I want to know the square of and I enter a number. The computer prints the square of the number. Then the program asks if I want to know the square of another number and just ends, whereas it was supposed to take my answer. I've been working for almost 16 to 17 hours trying to find the bug, but I couldn't. Could you please maybe test the code and tell me where I went wrong? Thanks.
This is the code:
package looppracticea;
import java.util.Scanner;
public class LoopPracticeA {
public static void main(String[] args) {
Scanner geek = new Scanner(System.in);
Scanner geek2 = new Scanner(System.in);
long taken_number, taken_number2;
String answer, answer2, answer_not_recognized, if_answer_is_no;
answer_not_recognized = "You didn't enter any of the recognized answers.";
if_answer_is_no = "'Kay. Whatever.";
System.out.println("Do you want to know the square of a number? (Y/N)");
answer = geek.nextLine();
if (answer.equals("Y") || answer.equals("y")) {
System.out.println("The number you want to know the square of is:");
taken_number = geek.nextLong();
System.out.println("That number squared is " + taken_number * taken_number + ".");
System.out.println("Do you want to know the square of another number? (Y/N)");
answer2 = geek2.nextLine();
switch (answer2) {
case "N":
System.out.println(if_answer_is_no);
break;
case "n":
System.out.println(if_answer_is_no);
break;
case "Y":
while (answer2.equals("Y")) {
System.out.println("The number you want to know the square of is:");
taken_number2 = geek2.nextLong();
System.out.println("That number squared is " + taken_number2 * taken_number2 + ".");
System.out.println("Do you want to know the square of another number? (Y/N)");
answer2 = geek2.nextLine();
}
break;
case "y":
while (answer2.equals("y")) {
System.out.println("The number you want to know the square of is:");
taken_number2 = geek2.nextLong();
System.out.println("That number squared is " + taken_number2 * taken_number2 + ".");
System.out.println("Do you want to know the square of another number? (Y/N)");
answer2 = geek2.nextLine();
}
break;
default:
System.out.println(answer_not_recognized);
break;
}
} else if (answer.equals("N") || answer.equals("n")) {
System.out.println(if_answer_is_no);
} else {
System.out.println();
System.out.println(answer_not_recognized);
}
}
}

Here are the fixed contents of your main:
Scanner geek = new Scanner(System.in);
long taken_number;
String answer;
String answer_not_recognized = "You didn't enter any of the recognized answers.";
String if_answer_is_no = "'Kay. Whatever.";
boolean firstTime = true;
while(true)
{
if(firstTime)
System.out.println("Do you want to know the square of a number? (Y/N)");
else
System.out.println("Do you want to know the square of another number? (Y/N)");
answer = geek.nextLine();
if (answer.equalsIgnoreCase("y"))
{
System.out.println("The number you want to know the square of is:");
taken_number = geek.nextLong();
System.out.println("That number squared is " + taken_number * taken_number + ".");
answer = geek.nextLine();
}
else if (answer.equalsIgnoreCase("n")) {
System.out.println(if_answer_is_no);
break;
} else {
System.out.println();
System.out.println(answer_not_recognized);
break;
}
if(firstTime)
firstTime = false;
}
The problem is you have to read the line twice to get to the line you want.
The first nextLine will read the enter
Also I reduced the code by:
leaving only one Scanner since that is enough
used equalsIgnoreCase instead of 2 equals
used only one answer and taken_number variable since that was enough
put the variables declaration on separate lines because it is easier to maintain an a convention.
combined both input readings into one, with a boolean telling me if it is the first time so I know what message to output.
reading the nextLine() 2 times because the first one is the enter

Related

Stuck While Loop (Java)

all!
I'm a university freshman computer science major taking a programming course. While doing a homework question, I got stuck on a certain part of my code. Please be kind, as this is my first semester and we've only been doing Java for 3 weeks.
For context, my assignment is:
"Create a program that will ask the user to enter their name and to enter the number of steps they walked in a day. Then ask them if they want to continue. If the answer is "yes" ask them to enter another number of steps walked. Ask them again if they want to continue. If they type anything besides "yes" you should end the program by telling them "goodbye, [NAME]" and the sum of the number of steps that they have entered."
For the life of me, I can not get the while loop to end. It's ignoring the condition that I (probably in an incorrect way) set.
Can you please help me and tell me what I'm doing wrong?
import java.util.Scanner;
public class StepCounter
{
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
final String SENTINEL = "No";
String userName = "";
String moreNum = "";
int numStep = 0;
int totalStep = 0;
boolean done = false;
Scanner in = new Scanner(System.in);
Scanner in2 = new Scanner(System.in);
// Prompt for the user's name
System.out.print("Please enter your name: ");
userName = in.nextLine();
while(!done)
{
// Prompt for the number of steps taken
System.out.print("Please enter the number of steps you have taken: ");
// Read the value for the number of steps
numStep = in.nextInt();
// Prompt the user if they want to continue
System.out.print("Would you like to continue? Type Yes/No: ");
// Read if they want to continue
moreNum = in2.nextLine();
// Check for the Sentinel
if(moreNum != SENTINEL)
{
// add the running total of steps to the new value of steps
totalStep += numStep;
}
else
{
done = true;
// display results
System.out.println("Goodbye, " + userName + ". The total number of steps you entered is + " + totalStep + ".");
}
}
}
}
To compare the contents of String objects you should use compareTo function.
moreNum.compareTo(SENTINEL) return 0 if they are equal.
== operator is used to check whether they are referring to same object or not.
one more issue with addition of steps, addition should be done in case of "No" entered also
Use
if(!moreNum.equals(SENTINEL))
Instead of
if(moreNum != SENTINEL)
Also, make sure to add: totalStep += numStep; into your else statement so your program will actually add the steps together.

Outputting a stored value on the same line with text

Need help with this program. I am a very green Java student and am very lost. I want this program to prompt a user to input a number and then have the program decide if it's an odd or even number. I would like the output to display the number and then some text after it on the same line:
e.g.
User prompted: "Enter integer to check if it is odd or even"
User enters a "6"
Program should output "6 is an even number".
This is the program I have so far. It calculates odd/even and outputs text based on result. But every time I try to add something to the System.out.println("is an even number.") or the "odd" line it errors out. Not sure how to get the stored variable to output. If the inputted number stored at all?
import java.util.Scanner;
class OddOrEven
{
public static void main(String args[])
{
int integer;
System.out.println("Enter an integer to check if it is odd or even ");
Scanner in = new Scanner(System.in);
integer = in.nextInt();
if ( integer % 2 == 0 )
System.out.println("is an even number.");
else
System.out.println("is an odd number.");
}
}
You need to convert the int to a String, then concatenate it with the + operator:
System.out.println( Integer.toString(integer) + " is an even number.");

Java: Compiling Error Concerning Breaks

I am a freshman in college, currently in my first semester of my Computer Programming course; we have started by working with pseudo code and Java simultaneously.
We had been tasked with the creation of a java application that totals, and creates an average, of a series of numbers that have been input by the user. The user may input as many numbers as they wish until the number 0 is input, in which case the program outputs the total and the average, and then prompts the user to start over or exit the program.
I accomplished this task using two while loops, one of which is nested. When attempting to break the nested loop, however, I receive the error "Error: break outside switch or loop". Afterwards, I spent much time browsing this forum looking for answers and information concerning the problem, but none seemed relevant to my problem, and fixes did not work. Among the list was using labeled breaks and correcting curly brackets; because these did not seem to work, I'm convinced the problem lies deeper in the code.
Because my course is online, it is very difficult to communicate with the professor or other students in a timely manner, which is why I have turned to this community!
Below I will attach the pseudo code that the professor wanted us to base our application off of.
Start
Declarations
Num sumTotal = 0 // Initialize for clarity
Num numEntered
Num averageNum
Num loopCounter
Num answer
String endProgram = “Y” // Initialize so that outer loop will work
End declarations
// Greet the user
Output “Welcome to our calculator. “
Output “Enter as many numbers as you want.”
Output “When you are done entering numbers, enter 0 (zero) to display the sum.”
Output “Do you want to start the calculator? (Y/N): “ // Let the user decide to start
input endProgram
// Note: if the user enters anything but Y or y, the loop will not execute.
While endProgram <> “Y” OR endProgram <> “y” // Allows the user to perform multiple calculations
//Enter the first number (sentinel value)
Output “Please enter your first number.”
Input numEntered
While numEntered <> 0 // Allows the user to enter numbers for the current calculation
Output “You entered the number “ + numEntered // echo input
sumTotal = sumTotal + numEntered // Add number entered to total
loopCounter++ // Increment the number of entries
Output “Please enter the next number”
Input numEntered // If 0, the loop will end here
endWhile // the nested inner loop code stops here
// Output section
Output “The total numbers entered is: “ + loopCounter
Output “The total of the numbers entered is: “ + sumTotal
Output “The average of the numbers entered is: “ + averageNum
Output “Would you like to do a new set of calculations? Y/N
Input endProgram
End While // End outer While statement when endProgram = Y
Output “Thank you for using the calculator. The program will now end.”
Stop // Stop the program
Below I will attach my Java code
/* Module 4 Assignment 1 Part 1
* Aaron Field
* Submitted March 26, 2016
* Using DrJava */
import javax.swing.JOptionPane;
public class Calculator {
public static void main(String[] args) {
//variable declarations
int numEntered;
int sumTotal = 0;
int averageNum = sumTotal / numEntered;
int loopCounter;
String endProgram = "Y";
//end declarations
System.out.println("Welcome to the Totaling Calculator");
System.out.println("This program will accept integer inputs until 0 is entered" + '\n' + "When 0 is entered, a sum and an average will be displayed.");
endProgram = JOptionPane.showInputDialog(
"Do you want to start the calculator? (Y/N): ");
while(endProgram != "Y" || endProgram != "y"); {
numEntered = Integer.parseInt(JOptionPane.showInputDialog(
"Please enter your first number."));
while(numEntered != 0); {
System.out.println("You entered the number " + numEntered);
sumTotal = sumTotal + numEntered;
loopCounter++;
numEntered = Integer.parseInt(JOptionPane.showInputDialog(
"Please enter the next number"));
break;}
System.out.println("The total numbers entered is: " + loopCounter + '\n' + "The total of the numbers entered is: " + sumTotal + '\n' + "The average of the numbers entered is: " + averageNum);
endProgram = JOptionPane.showInputDialog(
"Would you like to do a new set of calculations? (Y/N): ");
break;
}
System.out.println("Thank you for using the calculator. The program will now end.");
}
}
I understand the code may be sloppy or strange, but I've only been working with Java for since mid-February, so excuse any sloppy formatting or incorrect use of code.
To my untrained eyes, the break statements seem to be within the loops; I am rather confused as to why my compiler would suggest they aren't. Any help would be GREATLY appreciated, thank you.
while(...); it's a bad practice :P. Your break commands are in fact all outside the while loops.
Remove the semicolons after your while statements.
Example: change
while(endProgram != "Y" || endProgram != “y”); {
//...
}
to
while(endProgram != "Y" || endProgram != “y”) {
//...
}
A while statement followed by a semicolon is actually interpreted as this
while(condition) {}

Console Calculator error java

So everything is working fine for this calculator besides for the askCalcChoice1. Since askCalcChoice1 is a string, I am calling it wrong (obviously). The error says it cannot convert string to int, as well as convert int to boolean. However, when i make the inputOperation as a string, it breaks the other 2 calls below askCalcChoice1. (it breaks displayRedults and askTwoValues because those are not strings). I do not know how to format askCalcChoice in order to call for this method that is written in another class wihtout breaking anything. askCalcChoice is written as a string which i pasted below the oopCalculator code. Is there any way and can someone please show me how to write that portion of that code in oopCalculator?
int inputOperation; // user to choose the function
askCalcChoice1 myAskCalcChoice1 = new askCalcChoice1();
//menu becomes a complete string below
String menu = "Welcome to Hilda Wu's Calculator\t\t"
+ "\n1. Addition\n"
+ "2. Subtraction\n"
+ "3. Multiplication\n"
+ "4. Division\n"
+ "5. Exit\n\n";
calculatorCommands.pickNewSymbol(menu); //complete menu will be picked up as a string and display
calculatorCommands.putDownSymbol();
while (inputOperation = myAskCalcChoice1.calcChoice()) { //this will call for myAskCalcChoice1 class
calculatorCommands.pickNewSymbol("\n"); //pick up the class
calculatorCommands.putDownSymbol(); //display the class
askTwoValues myAskTwoValues = new askTwoValues();
float[] myFloats = myAskTwoValues.inputFloats(inputOperation);
displayResults myDisplayResults = new displayResults();
float result = myDisplayResults.showResults(inputOperation, myFloats);
String strFormat = "The answer is: " + result + "\n\n"; //print out The answer is as a string
calculatorCommands.pickNewSymbol(strFormat); //pick up string from above
calculatorCommands.putDownSymbol(); //display string
calculatorCommands.pickNewSymbol(menu); // pick up menu from the beginning of code, loop to calculator menu
calculatorCommands.putDownSymbol(); //display menu as loop
}
calculatorCommands.pickNewSymbol("\nThank you for using Hilda Wu's Calculator\n"); //when user choose to exit calculator
calculatorCommands.putDownSymbol();
}
String calcChoice() {
String input;
do { //do loop will continue to run until user enters correct response
System.out.print("Please enter a number between 1 and 5, A for Addition, S for Subtraction, M for Multiplication, or D for Division, or X for Exit: ");
try {
input = readInput.nextLine(); //user will enter a response
if (input.equals("A") || input.equals("S") || input.equals("M") || input.equals("D") || input.equals("X")) {
System.out.println("Thank you");
break; //user entered a character of A, S, M, or D
} else if (Integer.parseInt(input) >= 1 && Integer.parseInt(input) <= 5) {
System.out.println("Thank you");
break; //user entered a number between 1 and 5
} else {
System.out.println("Sorry, you have entered an invalid choice, please try again.");
}
continue;
}
catch (final NumberFormatException e) {
System.out.println("You have entered an invalid choice. Try again.");
continue; // loop will continue until correct answer is found
}
} while (true);
return input;
}
}
To start with, you are calling showResults with two arguments:
int choice
and
float [] f
Choice is never used.
You use input variable instead in your switch but on default you return the error showing choice.
Better pass choice as an argument in the function and be sure it is char and not other type.
Also this is not the form of a good stated question. I will not rate it down but please remake it so the whole code is correctly shown. I can not make sense of it easily. I might misunderstood it already. Please do not add comments between, be sure you have correct indentation and you got all the code in.
If you need to comment do it afterwards. It's not very complicated, just show us the code and ask what is wrong later ;)
If choice was meant to pass in the switch... then do it, but not as int but as char.

Runtime Ignoring While Loops?

I am new to the forums so first of all I'd like to say "Hi"! I'm new to Java programming and am trying to make a simple payroll calculating program with three while loops.
The first while loop keeps the program going until the user enters the sentinel "stop". The second and third loops are error traps that ensure the user enters a positive number before continuing.
For some reason, the while loops are not working and I have tried every variation I can think of. The program runs just fine, it just ignores the while loops. If someone could provide some suggestions as to what I'm doing wrong, I'd really appreciate it.
I'm using NetBeans 8.0 IDE if that helps.
Here is my code:
Import java.util.*;
Import java.text.*;
public class PayrollProgramVersion2
{
//begin main program
public static void main(String[] args)
{
//declare new scanner
Scanner sc = new Scanner (System.in); // declare new scanner object
DecimalFormat Dollars = new DecimalFormat ("$0.00"); //format for dollars
String Employee; //employee's name
Double Hours, //hours worked
Rate, //pay rate
Pay; // Hours * Rate
Boolean Continue = true; // sentinel for program loop
//welcome user, prompt for employee name, and assign input to Employee
System.out.println ("Welcome to the payroll program!");
System.out.println ("What is the employee's name? (Enter stop to quit.)");
Employee = sc.nextLine();
// while loop continues program until user enters "stop"
while (Continue == true)
{
if (Employee.equalsIgnoreCase("stop"))
{
Continue = false;
} // end if
else
{
//prompt for hours worked and assign to Hours
System.out.println ("How many hours did " +Employee+ " work?");
Hours = sc.nextDouble();
//this block is an error trap to ensure input is positive before continuing
while (Hours < 0)
{
System.out.println( "Error - input must be a positive number");
System.out.println ("How many hours did " +Employee+ " work?");
Hours = sc.nextDouble();
}
//prompt for pay rate and assign to Rate
System.out.println( "How much does " +Employee+ " make per hour?");
Rate = sc.nextDouble();
//this block is an error trap to ensure input is positive before continuing
while (Rate < 0)
{
System.out.println( "Error - input must be a positive number");
System.out.println( "How much does " +Employee+ " make per hour?");
Rate = sc.nextDouble();
}
Pay = Hours * Rate; // calculate payrate
//display results
System.out.println(Employee+ "'s paycheck is " +(Dollars.format(Pay))+ ".");
System.out.println ("What is the employee's name? (Enter stop to quit.)");
Employee = sc.nextLine();
} //end else
} //end while
System.out.println ("Thank you for using the payroll program. Goodbye!");
} // end main
} // end program
From what I can see you should make your while (hours<0) to while (hours<0 || hours == null).
This is because... As far as I can see you initialise hours. But no value is input into it. So it remains as null. You could also try changing the while to an if.
Hope this helps. It may be that it does default to 0 but it may be worth for testin purposes to have a console output.
System.out.println(hours);
Befor the while loop to see what your program is reading hours as.
Hope this helps.
The error is that nextDouble does not eat the newline. It skips newlines at the beginning, so in effect only the last nextDouble is concerned.
Best to make a utility function:
Instead of
Hours = sc.nextDouble();
call your own function:
Hours = nextDouble(sc);
private static double nextDouble(Scanner sc) {
double value = -1.0;
if (sc.hasNextDouble()) {
value = sc.nextDouble();
}
sc.nextLine();
return value;
}
Use a small initial letter for field and method names.
Use double/boolean/int instead of the Double/Boolean/Integer as the latter are Object wrappers (classes); the first primitive types.
Call sc.close(); (for good order).
Aside from what has been said above:
sc.nextDouble consumes and returns the next input from the current line. It does not forward the line.
sc.nextLine consumes and returns the input from the current line and forwards to the next line
At the end of your while loop you call Employee = sc.nextLine(); If you follow your logic and only input allowed values, this will always return an empty string as it consumes the current line where your most previously removed double was stored(now empty string "")
When you do something like:
Hours = sc.nextDouble();
you trust the user to enter a double value, and in case the user entered illegal value, a String for example, this line will throw an exception.
You can solve it like this:
while (Hours < 0)
{
System.out.println( "Error - input must be a positive number");
System.out.println ("How many hours did " +Employee+ " work?");
String hours = sc.nextLine();
try {
Hours = Double.valueOf(hours);
}
catch (NumberFormatException e) {
// keep looping until we get a legal value
Hours = -1.0;
}
}

Categories

Resources