I want to add a number from my previous calculations. I currently am unable to because the loop continues. Here is my code. For example, if i get 11 as my answer, i want to be able to add 6. I also want to be able to add 6+6 and get the answer 23. How do I do this because currently I am stuck.
Thanks for the help!
public static void main(String [] args){
scan = new Scanner(System.in);
while(!done){
int numOne, numTwo, result;
System.out.print("Enter Two Numbers : ");
numOne = scan.nextInt();
scan.nextLine();
numTwo = scan.nextInt();
scan.nextLine();
result = numOne + numTwo;
System.out.println("Addition = " +result);
result = numOne - numTwo;
System.out.println("Subtraction = " +result);
result = numOne * numTwo;
System.out.println("Multiplication = " +result);
result = numOne / numTwo;
System.out.println("Division = " +result);
System.out.println("Enter a number for a root : ");
double number1 = scan.nextDouble();
scan.nextLine();
double number2 = scan.nextDouble();
scan.nextLine();
System.out.println(Math.pow(number1, (1/number2)));
System.out.println("Enter the base: ");
long n,p,r=1;
System.out.println("enter number");
n=scan.nextLong();
scan.nextLine();
System.out.println("enter power");
p=scan.nextLong();
scan.nextLine();
if(n>=0&&p==0)
{
r =1;
}
else if(n==0&&p>=1)
{
r=0;
}
else
{
for(int i=1;i<=p;i++)
{
r=r *n;
}
}
System.out.println(n+"^"+p+"="+r);
System.out.println("Do you wish to continue?");
String ans2 = scan.nextLine();
System.out.println(ans2);
if(ans2.contains("Yes")|| ans2.contains("yes")){
System.out.println("Do you wish to add on to the previous calculation?");
}
if(ans2.contains("No") || ans2.contains("no")){
System.out.println("You are done calculating!");
}
scan.nextLine();
}
}
}
Store the answers in different variables instead of storing everything in result.
Say 'add' is the variable used for addition then use the expression add=add+numone+numtwo;
Initialize add variable before the loop.
And you haven't set done variable to zero.set done=0 inside the if which checks if the choice is 'no'.
You can initialize the result variable on top of the while loop so that it's value won't be reset everytime the loop is repeated.
Firstly, the loop continues because there is no exit condition. When you write a while loop you need to make sure the condition becomes false upon achieving your objective.
To keep result persistent, declare it outside the while loop.
int result = 0;
while (!done) {
And make the result add to itself.
result += numOne + numTwo;
Make while condition exit when user is done calculating by setting done as true. And add another condition to reset the result when user doesn't want it anymore.
String ans3 = "";
if (ans2.contains("Yes") || ans2.contains("yes")) {
System.out.println("Do you wish to add on to the previous calculation?");
ans3 = scan.nextLine();
}
if (ans2.contains("No") || ans2.contains("no")) {
System.out.println("You are done calculating!");
done = true;
}
if (!ans3.toLowerCase().contains("y")) {
result = 0;
}
Hope this helps
Related
I am making a program that will take a user's input on how many numbers he wants and determine the highest number between the given. After that the user will be prompt with a Yes or no question. If the user decides to say yes, the program will loop again and if not, the program will end. Now my question is why does it take the highest number from the previous run?
import java.util.Scanner;
public class IT_VILLAFLOR_Lab1_Prog2
{
public static void main(String[] Args){
int num=1,num2,Largest=0,max;
char YN;
Scanner sc = new Scanner(System.in);
System.out.print("Enter the Max Number = ");
max = sc.nextInt();
for(num=1; num<=max; num++)
{
System.out.print("Enter Number " + num + ": ");
num2 = sc.nextInt();
if(Largest<num2)
{
Largest=num2;
}
else if(num==max)
{
System.out.println("The Biggest number is " + Largest );
System.out.print( "Do you want to try again? Y/N ");
YN = sc.next().charAt(0);
if(YN =='Y'|| YN =='y')
{
num=0;
System.out.print('\f');
System.out.print("Enter the Max Number " );
max = sc.nextInt();
}
else
{
System.exit(0);
}
}
}
}
}
If the user wants to continue, you are resetting num to 0. Along with this, Largest also needs to be reset to 0.
num=0;
Largest=0; //new code
By the way, you need to change the line else if(num==max) to if(num==max) . Try the test case with max of 2 and values as 12 ,23.
When the user selects yes, it loops and starts again. When the user selects N, it should end the program but I am not sure what I am missing here. This is a program to tell you the x and y values when giving the slope and y-intercept to the program.
Java file
int slope;
int yintercept;
String newEquation;
boolean play = true;
System.out.print("Enter the slope: ");
slope = input.nextInt();
System.out.print("Enter y-intercept: ");
yintercept = input.nextInt();
System.out.printf("The equation of the line is: y = %dx + %d", slope, yintercept);
System.out.print("\nWould you like to create a new equation... Y or N? ");
newEquation = input.next();
while (play)
{
if (newEquation.equals("Y"))
{
System.out.print("Enter the slope: ");
slope = input.nextInt();
System.out.print("Enter y-intercept: ");
yintercept = input.nextInt();
System.out.printf("The equation of the line is: y = %dx + %d", slope, yintercept);
System.out.print("\nWould you like to create a new equation... Y or N? ");
newEquation = input.next();
}
if (newEquation.equals("N")){
play =false;
}
else{
System.out.print("Enter the slope: ");
slope = input.nextInt();
System.out.print("Enter y-intercept: ");
yintercept = input.nextInt();
System.out.printf("The equation of the line is: y = %dx + %d", slope, yintercept);
System.out.print("\nWould you like to create a new equation... Y or N? ");
newEquation = input.next();
}
}
}
}
Why do you have the same code in if (newEquation.equals("Y")) and else part? If you expect user only to enter "Y" or "N", then you can put else in fron, like this:
else if(newEquation.equals("N"))
and delete else part.
Because the way how you wrote it, it tests if input is "Y", and then second time in the same loop iteration it is going to test if input is "N", so that means that your program take the slope info twice once when it goes trough loop, because else refers only to "N".
Try a do-while construct, as well as a equalsIgnoreCase (to make "y" and "Y" both tested against "Y").
int slope;
int yintercept;
String newEquation;
boolean play = true;
do
{
System.out.print("Enter the slope: ");
slope = input.nextInt();
System.out.print("Enter y-intercept: ");
yintercept = input.nextInt();
System.out.printf("The equation of the line is: y = %dx + %d", slope, yintercept);
System.out.print("\nWould you like to create a new equation... Y or N? ");
newEquation = input.next();
} while newEquation.equalsIgnoreCase("Y")
(I have only cut-and-pasted your lines, but have not compiled and tested. My apologies if I missed something.)
The do-while tests if the user has typed a Y/y after the first round. Note that the user doesn't have to type N/n, but instead could type, say, q in order for the loop to terminate.
I want it to loop again when the user enters "Y" or "y" and quit when they enter "N" or "n". The quitting option works, however, when they enter Y/y, it shows the first system out, but does not let the user pick which operation they wish to do. Instead the option to continue pops up again and inhibits the user from making any choice.
Here is the code:
import java.util.Scanner;
public class Calc2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double numOne, numTwo, ans;
String option;
do {
System.out.println(
"For addition press '1', for subtraction press '2', for division press '3', for multiplication press '4'");
String choice = input.nextLine();
if (choice.contains("1")) {
System.out.println("Enter the first number : ");
numOne = input.nextDouble();
System.out.println("Enter the second number : ");
numTwo = input.nextDouble();
ans = numOne + numTwo;
System.out.println("The answer is: " + ans + " ya bish.");
}
else if (choice.contains("2")) {
System.out.println("Enter the first number : ");
numOne = input.nextDouble();
System.out.println("Enter the second number : ");
numTwo = input.nextDouble();
ans = numOne - numTwo;
System.out.println("The answer is: " + ans + " ya bish.");
} else if (choice.contains("4")) {
System.out.println("Enter the first number : ");
numOne = input.nextDouble();
System.out.println("Enter the second number : ");
numTwo = input.nextDouble();
ans = numOne * numTwo;
System.out.println("The answer is: " + ans + " ya bish.");
} else if (choice.contains("3")) {
System.out.println("Enter the first number : ");
numOne = input.nextDouble();
System.out.println("Enter the second number : ");
numTwo = input.nextDouble();
ans = numOne / numTwo;
System.out.println("The answer is: " + ans + " ya bish.");
}
System.out.println("Press 'Y' to continue or 'N' to quit.");
option = input.next();
} while (option.equals("Y") || option.equals("y"));
if (option.equals("N") || option.equals("n")) {
System.out.println("Thank you. ");
}
}
}
If anyone can help me, it'd be greatly appreciated. Thanks!
Please change below line in your code
String choice = input.nextLine();
from this code
String choice = input.next();
There trouble you see here is the use of nextLine after nextDouble. Check here [Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods
Your problem appears to be at the beginning of your do-while loop as such:
System.out.println(
"For addition press '1', for subtraction press '2', " +
"for division press '3', for multiplication press '4'");
String choice = input.nextLine();
This is the only place where you use nextLine method (rahter than next or nextDouble and so on). This means that after you've read the option argument at the end of the iteration:
option = input.next();
there's still a new line character that hasn't been read by the scanner. When you do nextLine() in the next iteration it reads the new line character before the user has any chance to input something).
Either change that first line to input.next() as well, or make sure every time you read a value, you clear the new line character (for instance by reading nextLine and then casting the value - this would also allow you to do input validations).
import java.util.Scanner;
public class Dice {
public static void main(String[] args) {
//I used 'print' instead of 'println' just to make it look a little cleaner in the console.
System.out.print("Input your first number: ");
Scanner sc1 = new Scanner(System.in);
double num1 = sc1.nextInt();
//I use doubles for my variables just in case the user wants to divide.
System.out.print("Input your second number: ");
Scanner sc2 = new Scanner(System.in);
double num2 = sc2.nextInt();
/* I used words rather than the actual symbols for my operators just to get practice using scanners for strings.
* Until now I'd solely been using them for int variables. And also due to the small detail that before programming,
* I had no idea what a modulo was and I felt that would be confusing to a random person.
*/
System.out.println("What would you like to do with these numbers?(Add, Subtract, Multiply, Divide, or Check Divisibility): ");
System.out.println("Simply type 'check' to check the divisibility of your two numbers.");
Scanner sc3 = new Scanner(System.in);
String str1 = sc3.nextLine().toUpperCase();
/* toUpperCase to prevent the user from creating an error by typing their in put in a 'unique' way.
*It took me several failures to finally look up toUpperCase.
*/
double num3;
switch(str1) {
case "ADD":
num3 = num1 + num2;
System.out.println("The sum is: " + num3);
break;
case "SUBTRACT":
num3 = num1 + num2;
System.out.println("The difference is: " + num3);
break;
case "MULTIPLY":
num3 = num1 * num2;
System.out.println("The product is: " + num3);
break;
case "DIVIDE":
num3 = num1 / num2;
System.out.println("The quotient is: " + num3);
break;
case "CHECK":
num3 = num1 % num2;
System.out.println("The remainder is: " + num3);
break;
default:
System.out.println("Invalid input. Please ensure that two numbers were entered and that you entered a valid math operation.");
break;
}//switch statement
}//main method
}//class
How would I get my code to run again if I wanted to maybe add another number to my answer? I'm just trying to get some practice in with my Java (I'm extremely green) and I apologize in advance if my question is too broad.
Consider the following small program
boolean quit = false;
while(!quit) {
System.out.print("Enter Something:");
Scanner sc1 = new Scanner(System.in);
String input = sc1.nextLine();
if(input.compareToIgnoreCase("quit") == 0) {
quit = true;
continue;
}
System.out.println("You entered " + input);
}
In this sample we keep asking them to enter something and print it out unless that input is "quit" in that case we use the continue statement to skip the rest of the loop and go back to the top of the while loop and re-evaluate the condition for another iteration. If you entered 'quit' this will evaluate to false and stop the loop and exit the program.
Heres a sample input/output from the program. Notice there is no "You entered quit", this is because the continue statement brought us back to the top of the while loop.
Enter Something:hello
You entered hello
Enter Something:quit
Now how can you adapt this to your program? Heres a small sample of how you can do one of your inputs
double num1 = 0;
String input1 = sc1.nextLine();
if(input1.compareToIgnoreCase("quit") == 0) {
// quit was entered, leave the loop
quit = true;
continue;
}
try {
num1 = Double.parseDouble(input1);
} catch(NumberFormatException e) {
// user entered something that isnt a number, quit the program for now
// you can change this to whatever behavior you like in the future
quit = true;
continue;
}
This will likely leave you with some validation questions like "I want to have my user try again if they input an invalid number" Those are all possible using this method and it leads you in the right direction.
Remember, main() is a callable method. Instead of using a while or for loop, you could just call it again at the end of the main method method.
// Put this at the end of your main method
System.out.print("Do you want to execute again? (yes/no)");
boolean repeat = sc1.nextLine().toUpperCase().equals("YES");
if (repeat) {
main(null); // You're not using any arguments in main()
}
On a separate note, you don't need all three of sc1, sc2, and sc3. They're basically the same. You could probably use sc1 everywhere and remove sc2 and sc3 completely.
// something like this then ask if to do another run if not set flag false
boolean flag = true;
while(flag)
{
System.out.print("Input your first number: ");
Scanner sc1 = new Scanner(System.in);
double num1 = sc1.nextInt();
You should put all your logic around a while loop which will grant to you to repeat your task until a condition is reached.
Maybe you can ask to the user to insert the string "EXIT" when he wants to exit from your program.
In your case I'll do something like this:
boolean exitFlag = false;
do {
// <put your logic here>
String answer = sc3.nextLine().toUpperCase();
if (answer.equals("EXIT")) {
exitFlag = true;
}
} while(!exitFlag);
package cst150zzhw4_worst;
import java.util.Scanner;
public class CST150zzHW4_worst {
public static void main(String[] args) {
//Initialize Variables
double length; // length of room
double width; // Width of room
double price_per_sqyd; // Total carpet needed price
double price_for_padding; // Price for padding
double price_for_installation; // Price for installation
String input; // User's input to stop or reset program
double final_price; // The actual final price
boolean repeat = true;
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
while (repeat)
{
//User Input
System.out.println("\n" +"What is the length of the room?: ");
length = keyboard.nextInt();
System.out.println("What is the width of the room?: ");
width = keyboard.nextInt();
System.out.println("What is the price of the carpet per square yard?: ");
price_per_sqyd = keyboard.nextDouble();
System.out.println("What is the price for the padding?: ");
price_for_padding = keyboard.nextDouble();
System.out.println("What is the price of the installation?: ");
price_for_installation = keyboard.nextDouble();
final_price = (price_for_padding + price_for_installation + price_per_sqyd)*((width*length)/9);
keyboard.nextLine(); //Skip the newline
System.out.println("The possible total price to install the carpet will be $" + final_price + "\n" + "Type 'yes' or 'no' if this is correct: ");
input = keyboard.nextLine();
}
}
}
How would I make it so when the user says yes the program stop and if the user says no then the program just repeats? I don't know why I'm having so much trouble. I've searched for well over 4 hours. I am only supposed to use a while loop, I think.
You have to assign repeat in your while-loop so it becomes false if the user says yes:
repeat = !input.equalsIgnoreCase("yes");
You just need to set repeat to true or false based on user input. So in the end, compare input with yes or no. Something like this would work for you :
if ("yes".equals(input))
repeat = true; // This would continue the loop
else
repeat = false; // This would break the infinite while loop
boolean repeat = true;
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
while (repeat)
{
-----------------------
-------------------------
System.out.println("Do you want to continue:");
repeat = keyboard.nextBoolean();
}
you also if you want your code to be more systematic , go and search about the interrupt , specially thread interrupt , these answers above is correct , find the more organic code and implement it
You can use a break statement to exit a while loop.
while (...) {
input = ...;
if (input.equals("Y")) {
break;
}
}