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).
Related
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
I am wondering how I can stop the scanner from reading extra erroneous input from the user.
For example, I would like to read in the user input 2 one as 2 into the variable diam, which the program below achieves.
The issue is then, that the next loop automatically detects the one leftover from the input, and executes the if statement accordingly.
I was able to work around this by creating two scanners, but unfortunately this is not allowed for this particular assignment. In addition, we are required to use .hasNextInt() in our program.
How do I prevent this "spill-over" using only one scanner? I have to assume this question has been posed before, but I did not have much luck finding an answer.
Scanner scnr = new Scanner(System.in);
System.out.print("Enter the diameter of a "
+ "cylinder (in centimeters): ");
// BEGIN: diameter input verification loop
for (;;) {
if (!scnr.hasNextInt()) {
System.out.print("Please enter an integer value "
+ "(less than 2,147,483,648) as decimal digits: ");
scnr.nextLine();
continue;
}
diam = scnr.nextInt();
if (diam >= 0) {
//null statement
}
else {
System.out.print("Please enter a positive integer value: ");
continue;
}
break;
}
//END: diameter input verification loop
//prompts user for container height
System.out.print("Enter the height of a "
+ "cylinder (in centimeters): ");
// BEGIN: height input verification loop
for (;;) {
if (!scnr.hasNextInt()) {
System.out.print("Please enter an integer value "
+ "(less than 2,147,483,648) as decimal digits: ");
scnr.nextLine();
continue;
}
height = scnr.nextInt();
if (height >= 0) {
//null statement
}
else {
System.out.print("Please enter a positive integer value: ");
continue;
}
break;
}
//END: height input verification loop`
One option would be to just read the entire line of input from the Scanner, and then retain only the first word. For example, for the diameter of a cylinder you could use:
System.out.print("Enter the diameter of a cylinder (in centimeters): ");
String input = scnr.nextLine();
try {
int diam = Integer.parseInt(input.split(" ")[0]);
}
catch (NumberFormatException e) {
System.out.print("Please enter an integer value "
+ "(less than 2,147,483,648) as decimal digits: ");
}
I can think of a couple of approaches:
As Tim notes, you can use readLine() to read a complete line from the user, then parse the line. You could use split, or create a new Scanner to parse the line, or various other approaches.
You can stick with a single Scanner and call nextLine() to discard unconsumed characters up to and including the next end-of-line. Obviously, you need to do this after calling nextInt(). For example:
height = -1;
while (height < 0) {
if (!scnr.hasNextInt()) {
System.out.print("Please enter an integer value "
+ "(less than 2,147,483,648) as decimal digits: ");
} else {
height = scnr.nextInt();
if (height < 0) {
System.out.print("Please enter a positive integer value: ");
}
}
scanner.nextLine();
}
(The above version of your code has restructured things to get rid of the break and continue. The restructuring also allows me to put the readLine as an unconditional last statement for the loop. I think it makes the logic easier to understand ...)
// BEGIN: height input verification loop
for (;;) {
scnr.nextLine(); /* read fresh input, deleting the left over input */
if (!scnr.hasNextInt()) {
System.out.print("Please enter an integer value " + "(less than 2,147,483,648) as decimal digits: ");
scnr.nextLine();
continue;
}
height = scnr.nextInt();
if (height >= 0) {
// null statement
} else {
System.out.print("Please enter a positive integer value: ");
continue;
}
break;
}
You can simply add a scnr.nextLine() to remove the "old" scnr left over from the previous input. This fixes the spill-over problem.
I am trying to write a method that will subtract multiple numbers instead of using just 2 input numbers.
So far I have...
public void getSub() {
Scanner in = new Scanner(System.in);
System.out.print("Please enter the number: ");
double value = in.nextDouble();
double difference = 0;
while(in.hasNextDouble()) {
System.out.print("Please enter the next number: ");
double valueTwo = in.nextInt();
difference = value - valueTwo;
}
System.out.println("Difference: " + difference);
}
this currently only works with 2 inputs, but my end goal is to be able to continue subtracting multiple numbers.
Instead of continually subtracting from value, instead subtract from difference
Change difference = value - valueTwo; to difference -= valueTwo
This will be equivalent to doing ((A - B) - C) - ..., A being the first input, B the second input, C the third input...
public void getSub() {
Scanner in = new Scanner(System.in);
System.out.print("Please enter the number: ");
double difference = in.nextDouble();
while(in.hasNextDouble()) {
System.out.print("Please enter the next number: ");
difference -= in.nextDouble();
}
System.out.println("Difference: " + difference);
}
This should work fine
#include <stdio.h>
int main()
{
int result=0, n,number,i;
printf("How many numbers you want to use?\n");
scanf("%d",&n);
for(i=0;i<n;i++){
scanf("%d", &number);
if(i ==0 ){
result=number;
}
else{
result -= number;
}
}
printf("Answer is= %d ", result);
return 0;
}
Output:
How many numbers you want to use?
4
55
34
1
3
Answer is= 17
This solution doesn't hang after the first input. It is more user friendly.
public static void getSub() {
Scanner in = new Scanner(System.in);
System.out.print("Please enter the next number: ");
double difference = 0.0;
while(in.hasNextDouble()) {
System.out.print("Please enter the next number: ");
difference -= in.nextDouble();
}
System.out.println("Difference: " + difference);
}
Why have two variables? Anyway, the following is simpler and prompts correctly:
Scanner in = new Scanner(System.in);
System.out.print("Please enter the number: ");
double value = in.nextDouble();
while (true) {
in.nextLine(); // Silently discard rest of line
System.out.print("Please enter the next number, or . to stop: ");
if (! in.hasNextDouble())
break;
value -= in.nextDouble();
}
System.out.println("Difference: " + value);
Test
Please enter the number: 10
Please enter the next number, or . to stop: 1
Please enter the next number, or . to stop: 2
Please enter the next number, or . to stop: 3
Please enter the next number, or . to stop: .
Difference: 4.0
Below is the code I have so far, it is a calculator for my computer science class. The problem I am having is that on the second run of the program the System.out.print("Would you like to perform a calculation? (y/n) "); runs twice instead of once. I have already turned in the project, but I would like to know why it does this and how, in my future programs, I can fix it. I'll post the rest of the code below.
I appreciate all of your help, I credit the "A" that I got on it to all of you. Thanks!
/**
* A calculator with multiple functions.
* #author ()
* #version (version 2.1)
*/
import java.io.*;
import java.util.Scanner;
public class Calc
{
public static void main(String args[])
{
Scanner reader = new Scanner(System.in);
String cont = "", funct = "";
double fnum = 0, snum = 0, answer = 0;
while(true)
{
System.out.print("Would you like to perform a calculation? (y/n) ");
cont = reader.nextLine();
if (cont.equalsIgnoreCase("y"))
{
System.out.println("What function would you like to do?");
System.out.println("+?");
System.out.println("-?");
System.out.println("*?");
System.out.println("/?");
funct = reader.nextLine();
if (funct.equals("+"))
{
System.out.println("Simple addition calculator");
System.out.println("Enter first num: ");
fnum = reader.nextDouble();
System.out.println("Enter second num: ");
snum = reader.nextDouble();
answer = fnum + snum;
System.out.println("Answer: " + answer);
System.out.println(" ");
}
if (funct.equals("-"))
{
System.out.println("Simple subtraction calculator");
System.out.println("Enter first num: ");
fnum = reader.nextDouble();
System.out.println("Enter second num: ");
snum = reader.nextDouble();
answer = fnum - snum;
System.out.println("Answer: " + answer);
System.out.println(" ");
}
if (funct.equals("*"))
{
System.out.println("Simple multiplication calculator");
System.out.println("Enter first num: ");
fnum = reader.nextDouble();
System.out.println("Enter second num: ");
snum = reader.nextDouble();
answer = fnum * snum;
System.out.println("Answer: " + answer);
System.out.println(" ");
}
if (funct.equals("/"))
{
System.out.println("Simple division calculator");
System.out.println("Enter first num: ");
fnum = reader.nextDouble();
System.out.println("Enter second num: ");
snum = reader.nextDouble();
answer = fnum / snum;
System.out.println("Answer: " + answer);
System.out.println(" ");
}
}
else if (cont.equalsIgnoreCase("n"))
{
break;
}
}
}
}
In all of your function conditions inside the loop, you are using reader.nextDouble(). This will only read the number (e.g "8") input not the new line (the enter) which is entered by the user after the number.
Following code for the minus(-) function will not print "Would you like to perform a calculation? (y/n) " twice as the new line is already read. Here reader.nextLine() is used instead of reader.nextDouble(). reader.nextLine() will read the whole line not only the number.
if (funct.equals("-"))
{
System.out.println("Simple subtraction calculator");
System.out.println("Enter first num: ");
fnum = Double.parseDouble( reader.nextLine());
System.out.println("Enter second num: ");
snum = Double.parseDouble( reader.nextLine());
answer = fnum - snum;
System.out.println("Answer: " + answer);
System.out.println(" ");
}
You need to consume the newline character after you call nextDouble() and before the next nextLine() to prevent nextLine() consume the newline character. Otherwise funct = reader.nextLine(); will take the new line character as input and not wait for any more user input, which results in the repeat.
if (funct.equals("/"))
{
System.out.println("Simple division calculator");
System.out.println("Enter first num: ");
fnum = reader.nextDouble();
System.out.println("Enter second num: ");
snum = reader.nextDouble(); // consume the new line character
reader.nextLine();
answer = fnum / snum;
System.out.println("Answer: " + answer);
System.out.println(" ");
}
Try adding this reader.nextLine(); before the while loop ends, as mentioned below. This will clear the screen buffer.
else if (cont.equalsIgnoreCase("n"))
{
break;
}
reader.nextLine();
}
Hope this helps,
Basically what is happening is when you are using the reader.nextLine() method, there is still a newline character left in the buffer, which is picked up when calling nextLine(). So it's making an extra run with the newline character. If you run your program with newline as the input even for the first time, it will loop without doing anything. So, you just need to clear out the buffer before going into your while loop.
I have a little problem with this do while loop; when I run the program it is working, at least partially, what I mean is first you need to make a choice for convertion from C to F or from F to C and after you enter the values the program stops what I want to do is to keep asking for values until you enter 3. I tried to do it with a do while loop but it is not working so if someone has any ideas I would be grateful. Here is the code:
import java.util.Scanner;
public class DegreesInConversion2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Conversion table: ");
int choice = input.nextInt();
do {
System.out.println();
System.out.println("1 for convertion from Celsious to Fahrenhait: ");
System.out.println("2 for convertion froom Fahrenheit to Celsious: ");
System.out.println("3 for Exit: ");
System.out.println();
System.out.println("Make a choice between 1 - 3 ");
choice = input.nextInt();
System.out.println();
switch (choice) {
case 1:
System.out.println("Enter temperature in Celsious: ");
double cel = input.nextDouble();
if (cel < -273.15) {
System.out.println("Invalid values, please enter temperature greater than -273.15 in C:");
} else {
System.out.println("You enetered " + cel + "C " + "which is " + (((cel * 9) / 5) + 32) + "F");
}
break;
case 2:
System.out.println("Enter temperature in Farhneit: ");
double far = input.nextDouble();
if (far < -459.67) {
System.out.println("Invalid values, please enter temperature greater than -459.67 in F:");
} else {
System.out.println("You enetered " + far + "F " + "which is " + (((far - 32) * 5) / 9) + "C");
}
break;
case 3:
System.out.println("Goodbyu have a nice day: ");
break;
default:
System.out.println("Invalid entry: Please enter a number between 1-3:");
}
} while (choice != 3);
}
}
Like in your other question, here you're scanning for input before prompting the user for input.
You need to remove the second line below:
System.out.println("Conversion table: ");
int choice = input.nextInt();
do
With your code as is, it outputs
Conversion table:
and then blocks waiting for input. Whereas you want it instead to continue into the while loop and output
1 for convertion from Celsious to Fahrenhait:
2 for convertion froom Fahrenheit to Celsious:
3 for Exit:
Make a choice between 1 - 3
before blocking to scan for input.
As is, if you enter any number at the first block, your program enters the loop and behaves as you wanted. So you're nearly there!
The code does work. the problem is most likely the
int choice = input.nextInt();
before the do
Remove this, and change
choice = input.nextInt();
to
int choice = input.nextInt();
Besides the fact that you have: int choice = input.nextInt(); outside of the loop which is unnecessarily getting input before showing the menu, it seems to all work relatively fine. You can just declare int choice inside the loop where you have choice = input.nextInt(); (ie. just change that to intchoice = input.nextInt();).
I tested your code, and it works fine if you change the line int choice = input.nextInt(); (just before your do{} while() block) into int choice;.
As others have already mentioned, you should not read input before your do{} while() block, since the question has not been asked yet.
you forgot the break; after your default case