Looping distance between two points, and q for quit - java

This is my situation:
i need the code to run in a loop, over and over again asking the same question(s) to the user, until the user types a "q" for any point to terminate/exit the loop, thus exiting the program.
The problem is that i tried to used a do-while/while loop, and those loops executes only if the conditions comes out to be true. But i need the condition ("q") to be false so it can continue the loop. If the condition is true (input.equals("q")) , then it just does not nothing because instead of the integer/double, it will use a string ("q") to calculate the distance.
i have already figured out how to get the distance, the code as is works well, but is there any work-around that i can make the loop continue while the condition is false?
and by the way, i am just barely learning java just in case...
'.
import java.*;
public class Points {
public static void main(String[] args){
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("Enter the first X coordinate: ");
double x1 = input.nextDouble();
System.out.print("Enter the first Y coordinate: ");
double y1 = input.nextDouble();
System.out.print("Enter the second X coordinate: ");
double x2 = input.nextDouble();
System.out.print("Enter the second Y coordinate: ");
double y2 = input.nextDouble();
System.out.println("(" + x1 + ", " + y1 + ")" + " " + "(" + x2 + ", " + y2+ ")");
double getSolution = Math.sqrt(((x2-x1) * (x2-x1)) + ((y2-y1) * (y2-y1)));
System.out.println(getSolution);
}
}'

The solution to this is to use String line = input.nextLine() instead of nextDouble(). Then you can have a method like:
public static boolean timeToExit(String input) {
return input.equalsIgnoreCase("q");
}
This method will need to be called each time the user provides input:
if (timeToExit(line)) break;
That will exit a loop.
Now, since you have a String representation of the double, you will need to use Double.parseDouble(line) to turn the String into a number.
Then all you have to do is enclose everything in an infinite loop -> while(true) { }
And, the only time it will exit the loop is if the timeToExit method returned true, and you break the loop.
This all turns into something like:
while (true) {
...
System.out.print("Enter the first X coordinate: ");
String x1 = input.nextLine();
if (timeToExit(x1)) break;
double x1_d = Double.parseDouble(x1);
...
}

just some pseudocode:
while (! input.equals("q") )
// do something
If the user inputs q, input.equals("q") returns true which is then negated and breaks the loops.
Otherwise, the user inputs another number say 44, input.equals("q") equals false, which is negated and the loop continues.

I don't see a loop in your code... :s
But, why don't you try this:
while(true)
{
string input = // I don't remember the code to create a stream for standard input
if(input == "q"){
break;
}
else{
java.util.Scanner inputWithNumbers = new java.util.Scanner(input);
//---! All math operations here
}
}

Related

Why is my program printing two statements including of my previously entered number?

'So question was to find pytho triplet using the number inputted but number has to be greater than one and natural.
The error I am facing is that suppose I enter -4, then it runs method again and asks me to enter number again and I enter suppose 9 but while printing final statement, it prints triplets of both -4 and 9. How can I fix it as I only want triplet of 9 to be printed?
import java.util.*;
public class Pythagorean_Triplet
{
private static int a;
public static void main(String[]args) //main method
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter number to find Pythagorean Triplet : ");
int a=sc.nextInt();
if(a<2) //our program only works on natural numbers greater than 1
{
System.out.println("");
System.out.println("Your number is not a natural number or is 1");
System.out.println();
main(args);
}
double p1= 2*a;
double p2=Math.pow(a,2) - 1;
double p3=Math.pow(a,2) + 1;
System.out.println("");
System.out.println(p1 + ", " + p2 + " and " + p3 + " form a 'Pythagorean Triplet'");
}
}
You are calling the main method again (recursive call) so after you entered "9" the main(args); call returns and print the output for the first input.
So you should ask for a new number until you get a correct input.
import java.util.Scanner;
public class PythagoreanTriplet {
public static void main(String[]args) //main method
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter number to find Pythagorean Triplet : ");
int a = sc.nextInt();
while(a<2) //our program only works on natural numbers greater than 1
{
System.out.println("");
System.out.println("Your number is not a natural number or is 1");
System.out.println();
System.out.println("Please retry with a number greater than 1 : ");
a = sc.nextInt();
}
double p1= 2*a;
double p2=Math.pow(a,2) - 1;
double p3=Math.pow(a,2) + 1;
System.out.println("");
System.out.println(p1 + ", " + p2 + " and " + p3 + " form a 'Pythagorean Triplet'");
}
}
Calling a method doesn't stop the current method from executing. When the method you call completes, the current method continues.
For example, when you do this:
System.out.println();
You are calling a method. That method performs its logic, completes, and then this code continues on to the next statement. So when you do this:
main();
The same exact thing happens. The method performs its logic (in this case accepts your new input and produces output), completes, and then this code continues on to the next statement. That next logic is to produce the rest of the output.
Basically, recursion is the wrong tool for this job. Instead, loop over reading the input until correct input is received. Perhaps something like this:
Scanner sc = new Scanner(System.in);
int a = 0;
while (a < 2) {
// your loop logic
}
Notice how a is initialized to something that will cause us to enter the loop. Then in the loop is the operation we want to repeat, where we will continually ask for input until a is a valid value:
Scanner sc = new Scanner(System.in);
int a = 0;
while (a < 2) {
System.out.println("Enter number to find Pythagorean Triplet : ");
a = sc.nextInt();
if (a < 2) {
System.out.println("");
System.out.println("Your number is not a natural number or is 1");
System.out.println();
}
}
There are different ways to structure it. In this approach I've repeated the a < 2 logic. Another approach might ask outside the loop then re-ask within the loop, repeating the nextInt() logic. How you structure it generally comes down to the UX you want in the prompts and personal preference on how to organize the logic.
But overall the point here is that you want a loop, not recursion.
Since none of the above answers are accepted as the answer to your problem, i guess you actually want to work with recursion. Following is a representation of what your program currently does with the your example inputs.
what we need to do now, is to stop the first 'main()' call from printing its output. to achive that, we can simply 'return' after calling 'main()' the second time, or put the block of code which prints the output into the 'else' block of your if statement. your program would then look something like this:
using 'return' to stop wrong outputs
import java.util.*;
public class Pythagorean_Triplet
{
private static int a;
public static void main(String[]args) //main method
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter number to find Pythagorean Triplet : ");
int a=sc.nextInt();
if(a<2) //our program only works on natural numbers greater than 1
{
System.out.println("");
System.out.println("Your number is not a natural number or is 1");
System.out.println();
main(args);
return;
}
double p1= 2*a;
double p2=Math.pow(a,2) - 1;
double p3=Math.pow(a,2) + 1;
System.out.println("");
System.out.println(p1 + ", " + p2 + " and " + p3 + " form a 'Pythagorean Triplet'");
}
}
using 'else' to stop wrong outputs
import java.util.*;
public class Pythagorean_Triplet
{
private static int a;
public static void main(String[]args) //main method
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter number to find Pythagorean Triplet : ");
int a=sc.nextInt();
if(a<2) //our program only works on natural numbers greater than 1
{
System.out.println("");
System.out.println("Your number is not a natural number or is 1");
System.out.println();
main(args);
} else {
double p1= 2*a;
double p2=Math.pow(a,2) - 1;
double p3=Math.pow(a,2) + 1;
System.out.println("");
System.out.println(p1 + ", " + p2 + " and " + p3 + " form a 'Pythagorean Triplet'");
}
}
}

Loops and user input validation in java, again

So, I think about two days back I asked a question about input validation, and how to loop programs until the user gave a valid input..
So I made a calculator and I wanted to loop every step of the program so that if the user didn't put a double (69, 42.0) or the appropriate operator char (/, *, +, -) they would be stuck on that step till they got it right or otherwise closed the app entirely.
So one thing I got from the last question about this is that I could make a boolean value called "restart" or something and encapsulate my entire code except for the main method obviously and at the end I could make a question that they could answer true or false and the entire app could run again. While I admit having a "start over" button on my app is cool and useful for all my other a projects (probably not, I'm sure this can be done more efficiently), It still didn't satiate me and my original problem.
SO...
I got to trying everything I could (I know stack likes people who show that they at least tried).
EXAMPLE 1
Scanner input = new Scanner(System.in);
double valX;
System.out.println("Calculator Activated.");
do
{
System.out.print("Value X: ");
valX = input.nextDouble();
}while (!input.hasNextDouble());
{
System.out.println("Invalid number!");
}
//Didn't work ¯\_(ツ)_/¯
EXAMPLE 2
Scanner input = new Scanner(System.in);
double valX;
System.out.println("Calculator Activated.");
while (!input.hasNextDouble())
{
System.out.println("Value X: ");
valX = input.nextDouble();
}
//neither this one...
Note that the solution you guys give me has to apply to every step of the program.
And for a bit more clarity is the entire src code without the stuff I tried and the "restart" loop.
import java.util.Scanner;
public class CalTest
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
double valX, valY, divided, multiplied, added, subtracted; //Declared all my variables...
char operator;
boolean restart; //Didn't need to declare it true or false since I'm using a Scanner anyway
do //Start of the entire program
{
System.out.println("Calculator Activated.");
System.out.print("Value X: "); //I need a loop here...
valX = input.nextDouble();
System.out.print("Operator: "); //And here...
operator = input.next().charAt(0);
System.out.print("Value Y: "); //And here too..
valY = input.nextDouble();
divided = valX / valY;
multiplied = valX * valY;
added = valX + valY;
subtracted = valX - valY;
if (operator == '/')
System.out.println("Result: " + divided );
else if (operator == '*')
System.out.println("Result: " + multiplied); //<--Not sure if I need a loop with the if's
else if (operator == '+')
System.out.println("Result: " + added);
else if (operator == '-')
System.out.println("Result: " + subtracted);
else
System.out.println("Invalid operator!");
System.out.print("Try again? "); //I also need a loop here, I think.
restart = input.nextBoolean();
} while (restart); //End of it if you declared false.
System.out.println("Calculator terminated.");
}
}
At one point I tried to use the same "restart the app" concept and made a boolean variable for every single step in the code and it honestly was tiresome and not worth it.
Also I'm just a beginner if it's a concept of the loops that I'm missing then I'm happy to learn it from you guys.
Again, gracias to anyone who answers and helps contribute to my learning.
In your final code example in the class called CalTest where you assign valX = input.nextDouble(); you could a call recursive method that handles the exception until the input is what you want. Something like this:
private static double getNextDouble(Scanner input) {
try {
return input.nextDouble();
} catch (InputMismatchException e) {
System.out.println("Value X must be a number: ");
input.next();
return getNextDouble(input);
}
}
You'll replace valX = input.nextDouble(); with valX = getNextDouble(input);.
You can tidy this up and make it work for your other potential error cases, perhaps creating a parameter for the output message and passing it in as an argument.
public static void main(String[] args) {
double valX=0,valY=0;
char operator='0';//dummy default
Scanner input = new Scanner(System.in);
System.out.println("Calculator Activated.");
Double dX = null;
do
{
System.out.print("Value X: ");
dX = getDouble(input.next());
}while (dX==null);
{
valX = dX;
}
Character op = null;
do
{
System.out.print("Operator: ");
op = getOperator(input.next());
}while (op==null);
{
operator=op;
}
Double dY = null;
do
{
System.out.print("Value Y: ");
dY = getDouble(input.next());
}while (dY==null);
{
valY = dY;
}
System.out.println("Done: "+ valX + " "+operator + " " +valY);
}
static Double getDouble(String input) {
Double d = null;
try {
d = new Double(input);
}catch(NumberFormatException ex){
}
return d;
}
static Character getOperator(String input) {
Character c = null;
if("+".equals(input) || "-".equals(input) || "*".equals(input) || "/".equals(input)){
c = input.charAt(0);
}
return c;
}

Calculator int choice = Integer.parseInt(char_a); java

Trying to create a simple calculator on java. No errors show up in the code. But it still doesn't work at all. am I missing anything?
import java.util.Scanner;
public class JavaApplication15 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("This is a calculator. Enter a letter followed by a number to calculate it.");
System.out.println(" S = sine \n C = Cosine \n T = Tangent \n R = Square Root \n N = natural Log \n X = exit the program");
String num = in.nextLine();
String sValue = num.substring(2);
String char_a = num.substring(0);
int choice = Integer.parseInt(char_a);
double dValue = Double.parseDouble(sValue);
while (choice != 'x'){
switch(choice){
case 's':
Math.sin(dValue);
System.out.println("The sine of your number is " + dValue);
break;
case'c':
Math.cos(dValue);
System.out.println("The Cosine of your number is " + dValue);
break;
case't':
Math.tan(dValue);
System.out.println("The Tangent of your number is " + dValue);
break;
case'r':
Math.sqrt(dValue);
System.out.println("The square root of your number is " + dValue);
break;
case'n':
Math.log(dValue);
System.out.println("The Log of your number is " + dValue);
break;
case'x':
break;
}
}
}
}
I think I see your error.
You're performing operations using the Math class but aren't assigning the result of the operation back to your variable.
For example, Math.cos(dValue); should probably be dValue = Math.cos(dValue);
There are a few problems with your code.
Firstly, you are not using .substring method correctly. It returns everything from the index you specify to the end of your String. So for a user input of "S 4"
sValue equals to "4", but char_a equals to "S 4".
The way you use substring method is:
value = input.substring(2);
operation = input.substring(0,1);
I would actually suggest that you use something like:
params = input.split(" ");
Then you have:
params[0] // as your command
and
params[1] // as your value
This way you don't have to worry about how many symbols each bit actually takes up.
Next, don't convert your command to char like this. My previous suggestion means you should really be using something like
if (params[0].equals("sin")) {
} else if (params[0].equals("cos")) {
} else {
// catch unknown command
}
However, you can convert to char simply by:
sValue.toCharArray()[0]
Also, there is no reason why your switch statement should be in a while loop. There is nothing to be done continuously, it will just keep printing the same answers. And lastly, ajb said, you calculate the values and throw them away, whilst printing the old value. You have to use:
System.out.println("The Tangent of your number is " + Math.tan(dValue));

Do Loops to create read user input to repeat or exit program Java

This is my first post.
Using a Scanner class, I'm trying to let user input to choose to repeat the program or quit. The thing is my Do loop statement repeats the program and does not exit even if the Do Loop is false and should exit the program.
// loop repeat or quit
do {
//initialize variable
int integer;
int x = 1;
int factorial = 1;
System.out.print("Please enter an integer \n");
integer = getInt.nextInt();
//loop for factorial
//multiple each increment until it reaches the integer
while (x <= integer) {
factorial *= x;
x++;
}; // factorial=x*x
System.out.println("the factorial of the integer " + integer + " is " + factorial);
System.out.print("do you want to quit? y or n \n");
quit = getString.next();
} while(quit != yes);
System.exit(0);
}
There were a few mistakes in your code, so I rewrote it a little bit and used the correct functions where you used incorrect ones.
public static void main(String args[])
{
// Scanner is used to take in inputs from user
Scanner scan = new Scanner (System.in);
String quit = "";
// loop repeat or quit
do {
//initialize variable
int integer = 0;
int x = 1;
int factorial = 1;
// User needs to enter integer, or it'll throw exception.
System.out.println("Please enter an integer");
integer = scan.nextInt();
//loop for factorial
//multiple each increment until it reaches the integer
// factorial = x!
while (x <= integer) {
factorial *= x;
x++;
};
System.out.println("the factorial of the integer " + integer + " is " + factorial);
System.out.println("do you want to quit? y or n");
quit = scan.next();
// if quit is NOT equal to y, we do it again
} while(!quit.equals("y"));
System.exit(0);
}
I hope the comments helps :)
I've edited your code and it now runs.
For future reference: include more comprehensive snippets so viewers of your code can more easily discover mistakes.
Problem: There is no way to guarantee the user only inputs y without any spaces . THe easy solution to this problem is to use the string method contains(). I've modified your loop so that if the user input y the program will exit and it now works. Let me know if this works and happy coding!
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String quit ="";
do { //initialize variable
int integer; int x = 1; int factorial = 1;
System.out.print("Please enter an integer \n");
integer = in.nextInt();
//loop for factorial
//multiple each increment until it reaches the integer
while (x <= integer) {
factorial *= x;
x++;
}; // factorial=x*x
System.out.println("the factorial of the integer " + integer + " is " + factorial);
System.out.print("do you want to quit? y or n \n");
quit = in.next();
} while(!quit.contains("y"));
System.exit(0);
}
Shouldn't it be
while(quit != "y");
I also don't understand why you use System.out.print(); and then use \n when there's a perfectly good System.out.pritnln();
Also, since we're dealing with Strings the .nextLine(); is good enough for the Scanner. (You'll have to declare String quit as well.)

Trying to restart a do-while loop with a String variable to equal "yes" or "no"

Very simple program calculating travel distance(just started a week ago) and I have this loop working for a true or false question, but I want it to work for a simple "yes" or "no" instead. The String I have assigned for this is answer.
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double distance;
double speed;
boolean again = true;
String answer;
do{
System.out.print("Tell me your distance in miles: ");
distance = input.nextDouble();
System.out.print("Tell me your speed in which you will travel: ");
speed = input.nextDouble();
double average = distance / speed;
System.out.print("Your estimated time to your destination will be: " + average + " hours\n\n");
if(average < 1){
average = average * 10;
System.out.println(" or " + average + " hours\n\n");
}
System.out.println("Another? ");
again = input.nextBoolean();
}while(again);
}
}
You need to use input.next() instead of input.nextBoolean(), and compare the result to a string literal "yes" (presumably, in a case-insensitive way). Note that the declaration of again needs to change from boolean to String.
String again = null;
do {
... // Your loop
again = input.nextLine(); // This consumes the \n at the end
} while ("yes".equalsIgnoreCase(again));
just do
answer = input.nextLine();
} while(answer.equals("yes"));
You might want to consider being more flexible though. For example:
while (answer.startsWith("Y") || answer.startsWith("y"));
String answer=null;
do{
//code here
System.out.print("Answer? (yes/no) :: ");
answer=input.next();
}while(answer.equalsIgnoreCase("yes"));
the above condition makes " while" loop run if user enter's yes and will terminate if he enters anything except yes.

Categories