user input to create java program - java

I've tried creating codes to solve a quadratic formula but I've only succeeded in creating it for a specific formula. Is there any way I can be providing the variables a, b, c by user input then the solution prints out? The program also refuses to run on command prompt but can run in eclipse. What might be the issue?
Here it is.
public class Equationsolver {
public static void main(String[] args) {
double a, b, c;
a = 2;
b = 6;
c = 4;
double disc = Math.pow(b,2) - 4*a*c;
double soln1 = (-b + Math.sqrt(disc)) / (2*a) ;
double soln2 = (-b - Math.sqrt(disc)) / (2*a);
if (disc >= 0) {
System.out.println("soln1 = " + soln1);
System.out.println("soln2 = " + soln2);
}else{
System.out.println("equation has no real roots");
}
}
}

One possibility to take user input is to use the paramater String [] args.
The String [] args contains the value pass to the program when you executed it like java -jar program.jar arg1 arg2 arg3.
In your case, you will need to check if the user pass 3 arguments to the program and if so then assigned thoses values to your variables.
Here is a little bit of code that might help, note that I didn't add the validation and you will need more validation to make sure that you sanitize the user input:
public class Equationsolver {
public static void main(String[] args) {
double a, b, c;
a = Double.parseDouble(args[0]); //Here it will get the first argument pass to the program
b = Double.parseDouble(args[1]);
c = Double.parseDouble(args[2]);
double disc = Math.pow(b,2) - 4*a*c;
double soln1 = (-b + Math.sqrt(disc)) / (2*a) ;
double soln2 = (-b - Math.sqrt(disc)) / (2*a);
if (disc >= 0) {
System.out.println("soln1 = " + soln1);
System.out.println("soln2 = " + soln2);
}else{
System.out.println("equation has no real roots");
}
}
}
EDIT: You will probably need to change your code to adapt to the fact that now a b and c might not be what you were thinking.

You can take dynamic inputs from users in following way too
Scanner in = new Scanner(System.in);
double a = in.nextDouble();
double b = in.nextDouble();
double c = in.nextDouble();

Related

Need help adding methods in main class

Hello I'm working on a project for my java class, I'm supposed to write a code for a Algebra tutor that goes like this:
Write a program with a that displays a randomly generated problem that asks the user to solve for the y variable, takes input from the user, and prints "correct" if the user answered correctly and prints "incorrect" if not. Your main should give one problem and then exit. Use one or more methods to produce this behavior.
This is regarding the formula mx + b. So here is what I have so far, and works!
import java.util.Random;
import java.lang.Math;
import java.util.Scanner;
class Main {
public static void main(String[] arg){
double min_value = -100;
double max_value = 100;
double m_value = (int)(Math.random()*((max_value-min_value)+1))+min_value;
double x_value = (int)(Math.random()*((max_value-min_value)+1))+min_value;
double b_value = (int)(Math.random()*((max_value-min_value)+1))+min_value;
System.out.println("Given: ");
System.out.println("m = " + m_value);
System.out.println("x = " + x_value);
System.out.println("b = " + b_value);
System.out.print("What is the value of y? ");
Scanner user_input = new Scanner(System.in);
String user_answer = "";
user_answer = user_input.next();
int correct_answer = (int)m_value * (int)x_value + (int)b_value;
if (user_answer.equals(correct_answer))
System.out.println("You are correct!");
else
System.out.print("Sorry, that is incorrect. ");
System.out.println("The answer is " + correct_answer);
}
}
so even tho the output is correct, I need to break down the code into smaller methods, this is where Im getting confused on how to take a piece of that code and put it in another method that once it runs it calls for that method too and gives me the same output. I been ready the material given but the more I read it the more confuse I get. If anybody has any ideas or suggestions please let me know any info will be really appreciate. Thank you
Here's a quick rundown on methods, so it's not completely done yet. Ask, if you need more help! Good luck on your homework and on becoming one of the beast developers!
public class Main {
public static void main(String[] args) {
int a = 1; // give a value of 1
methodTwo(a); // sending the int a into another method
}
// Here's method number two
static void methodTwo (int a) { // it gives a's type and value
System.out.println(a); //Gives out a's value, which is 1
}
}
Technically you've solved the problem correctly, you are using one or more methods, but perhaps what you trying to do is a common code refactor called the extract method / extract function refactor Executing this type of refactor leads to much more readable and maintainable code, and is easy to do.
As a starter, identify code that repeats or looks similar, in your case, the following lines look ripe for extract method:
double m_value = (int)(Math.random()*((max_value-min_value)+1))+min_value;
double x_value = (int)(Math.random()*((max_value-min_value)+1))+min_value;
double b_value = (int)(Math.random()*((max_value-min_value)+1))+min_value;
Notice that the RHS of each line is identicial, so we can replace the explicit code with a method call like this:
double m_value = getRandomDoubleBetween(max_value, min_value);
double x_value = getRandomDoubleBetween(max_value, min_value);
double b_value = getRandomDoubleBetween(max_value, min_value);
private double getRandomDoubleBetween(double max_value, double min_value) {
return (int)(Math.random()*((max_value-min_value)+1))+min_value;
}
You can identify other areas of code that either contain repetition or perhaps some hard to understand code that would be more understandable if it was extracted into a method that had a name that reveals what the code is doing.
Please review this, you are comparing string with integer,
if (user_answer.equals(correct_answer))
This may help you:
import java.util.Scanner;
class Main {
public static void main(String[] arg) {
double min_value = -100;
double max_value = 100;
double m_value = generateRandom(max_value, min_value);
double x_value = generateRandom(max_value, min_value);
double b_value = generateRandom(max_value, min_value);
System.out.println("Given: ");
System.out.println("m = " + m_value);
System.out.println("x = " + x_value);
System.out.println("b = " + b_value);
checkAnswer(m_value, x_value, b_value);
}
private static void checkAnswer(double m_value, double x_value, double b_value) {
System.out.print("What is the value of y? ");
Scanner user_input = new Scanner(System.in);
String user_answer = "";
user_answer = user_input.next();
int correct_answer = (int) m_value * (int) x_value + (int) b_value;
if (user_answer.equals(String.valueOf(correct_answer))) {
System.out.println("You are correct!");
} else {
System.out.print("Sorry, that is incorrect. ");
System.out.println("The answer is " + correct_answer);
user_input.close();
}
}
static int generateRandom(double max_value, double min_value) {
return (int) ((int) (Math.random() * ((max_value - min_value)
+ 1)) + min_value);
}
}

Java loop structure that iterates over strings and works with multiple variables

Today I am working on refactoring one of my old java exercises.
It is as simple addition program that asks a user to input some numbers, then returns the sum of all of the numbers entered.
package methodparametertest;
import java.util.Scanner;
public class MethodParameterTest {
public static double adds(double a, double b, double c, double d, double e,
double f, double g) {
double sum = a + b + c + d + e + f + g;
return sum;
}
public static double getDoubleInput(String valueWanted) {
Scanner input = new Scanner(System.in);
String askFor = valueWanted;
System.out.println("Please enter a positive integer or decimal value"
+ "for your numnber of "+askFor);
double valueGiven = input.nextDouble();
return valueGiven;
}
public static void main(String[] args) {
double a = getDoubleInput("passengers");
double b = getDoubleInput("odometer_miles");
double c = getDoubleInput("fuel_gallons");
double d = getDoubleInput("miles_per_gallon");
double e = getDoubleInput("seats");
double f = getDoubleInput("wheels");
double g = getDoubleInput("lights");
System.out.println("Your total number of things: " +adds(a,b,c,d,e,f,g));
}
}
In the past, most of my program's logic was in my main method. I have made it my goal today to have as few lines as
possible in main, and package as much logic as I can into separate methods.
I still have several lines in main that use my getDoubleInput method to set the values for the variables a through g (which will then be used as parameters for my "adds" method.
I would like to alter this block and use a loop. Perhaps something that would work like this:
#Shell-like pseudocode
For i in (a b c d e f g)
For j in ("passengers", "odometer miles", "fuel gallons", "miles_per_gallon", "seats", "wheels", "lights");
do
double $i = getDoubleInput($j);
done
//OUTPUT
// double a = getDoubleInput("passengers");
// double b = getDoubleInput("odometer miles");
// double c = getDoubleInput("fuel gallons");
// double d = getDoubleInput("miles_per_gallon");
// double e = getDoubleInput("seats");
// double f = getDoubleInput("wheels");
// double g = getDoubleInput("lights");
However, I cannot find an example of how to implement this in java. Most of the loops that I have seen only iterate over numericalvalues, not a defined set of strings.
Does anyone know of a loop structure that could A: iterate over strings, and B: work with two variables ?
Don't have an adds method; just use plain old addition. Put the titles in a list and iterate that:
double sum = 0;
for (String title : Arrays.asList("passengers", "odometer miles", ...)) {
sum += getDoubleInput(title);
}
System.out.println("Your total number of things: " + sum);
Try this:
String[] strArray = Arrasy.asList(new String[] {"passengers", "odometer miles", "fuel gallons", "miles_per_gallon", "seats", "wheels", "lights"});
List<Integer> list = new ArrayList<>();
for (String str: strArray) {
list.add(getDoubleInput(str));
}
System.out.println("Your total number of things: " +adds(list));
And then modify adds to accept lists.

Error in Pythagorean Theorem Program

I am making a Pythagorean theorem program to solve for a missing side, and if the user enters 0 as the value that means that that is the missing side to solve for. My program is not getting the correct answer. Your help is greatly appreciated.
import java.util.Scanner;
import java.lang.Math;
public class pythagTheorem {
static double a;
static double b;
static double c;
static double newa;
static double newb;
static double newc;
public static void main(String[] args) {
Scanner scan= new Scanner(System.in);
System.out.println("Enter the value of a");
a=scan.nextDouble();
scan.nextLine();
System.out.println("Enter the value of b");
b=scan.nextDouble();
scan.nextLine();
System.out.println("Enter the value of c");
c=scan.nextDouble();
scan.nextLine();
if(a==0)
{
newb=Math.pow(b, b);
newc=Math.pow(c, c);
double result=newc-newb;
newa=Math.sqrt(result);
}
System.out.println("The value of a is " + newa);
}
}
Okay! So the problem I see with this Java code would be that it doesn't necessarily follow the actual pythagorean theorem. I see that if (A==0) then execute the actual equation, but you must remember that variable A isn't the hypotenuse of the triangle!
A^2 + B^2 = C^2 (C being the hypotenuse) If you want to make it so that it finds any part of the triangle you must remember to derive the equation so that you can find the missing side! Such as, you have side A and C but you want to find side B, the equation would then be B^2 = C^2-A^2.
Last of all, I see you have newb=Math.pow(b, b); that would power your variable to itself! Even the the powers are only 2, so it would be newb=Math.pow(b, 2);
TIP! Remember to capitalize the second word in a variable name like numa to numA
/* REMEMBER THAT A NUMBER MUST NEVER BE GREAT THAN C UNLESS IT IS THE UNKNOWN OR YOU WILL ENCOUNTER A NONREAL NUMBER BECAUSE YOU CAN'T SQUARE ROOT A NEGATIVE NUMBER*/
import java.util.Scanner;
import java.lang.Math;
public class pythagTheorem {
static double a;
static double b;
static double c;
static double newa;
static double newb;
static double newc;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a ZERO for the unknown side!");
System.out.println("Enter the value of side A :: ");
a = scan.nextDouble();
System.out.println("Enter the value of B :: ");
b = scan.nextDouble();
System.out.println("Enter the value of C :: ");
c = scan.nextDouble();
if (a == 0) {
newc = Math.pow(c, 2);
newb = Math.pow(b, 2);
newa = Math.sqrt(newc - newb);
System.out.println("Your missing side is :: " + newa);
}
else if(b == 0){
newc = Math.pow(c, 2);
newa = Math.pow(a, 2);
newb = Math.sqrt(newc - newa);
System.out.println("Your missing side is :: " + newb);
}
else if(c == 0){
newa = Math.pow(a, 2);
newb = Math.pow(b, 2);
newc = Math.sqrt(newa + newb);
System.out.println("Your missing side is :: " + newc);
}
else
System.out.println("Sorry! There is an error!");
}
}

java program has error after "bootlean go=true"? [duplicate]

This question already has answers here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
java.util.NoSuchElementException - Scanner reading user input
(5 answers)
Closed 7 years ago.
I'm getting an exception:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextDouble(Unknown Source)
at package1.smth.main(clas1.java:19)
When I remove the while(go) part, everything is working fine. But I added it to be able to reset program, and now there is an exception. I also have a code for another similar program, where I added the same loop and it is working without this exception.
Can someone explain what's the problem?
public static void main(String[] args) {
boolean go = true;
while (go) {
Scanner input = new Scanner(System.in);
double a = 0;
double b = 0;
double c = 0;
double discriminant = 0;
double d = 0;
System.out.print("Enter a : ");
a = input.nextDouble();
System.out.print("Enter b : ");
b = input.nextDouble();
System.out.print("Enter c : ");
c = input.nextDouble();
discriminant = (b * b - 4 * a * c);
d = Math.sqrt(discriminant);
if (discriminant >= 0.0) {
System.out.println("first answer : " + (-b + d) / (2.0 * a));
System.out.println("second answer : " + (-b - d) / (2.0 * a));
} else if (discriminant == 0.0) {
System.out.println("first answer : " + (-b) / (2.0 * a));
System.out.println("second answer : " + (-b) / (2.0 * a));
} else {
System.out.println("no asnwers.");
input.close();
}
}
}
I've read everything I could find similar to my problem, and most answers came from this site. I tried to implement the given solutions to my code, and some didn't work, some I could not understand how to use because my code is different from the example in a question. I am total newbie, it is probably third program I wrote.
UPDATE:
The final code I have. The only problem it shows, is "leak: scanner not closed".
package gg;
import java.util.Scanner;
public class hbh {
public static void main(String[] args) {
boolean go = true;
while (go) {
Scanner input = new Scanner(System.in);
double a = 0;
double b = 0;
double c = 0;
double discriminant = 0;
double d = 0;
System.out.print("Enter a: ");
a = input.nextDouble();
System.out.print("Enter b: ");
b = input.nextDouble();
System.out.print("Enter c: ");
c = input.nextDouble();
discriminant = (b * b - 4 * a * c);
d = Math.sqrt(discriminant);
if (discriminant >= 0.0) {
System.out.println("First answer: " + (-b + d) / (2.0*a));
System.out.println("Second answer: " + (-b - d) / (2.0*a));
}
else if (discriminant ==0.0) {
System.out.println("First answer: " + (-b) / (2.0*a));
System.out.println("Second answer: " + (-b) / (2.0*a));
}
else {
System.out.println("No answers");
input.nextLine();
}
}
}
}
You should delete
input.close();
When you close the System.in once, you can not use it again after having closing it.
I can not find the source but here is a proof that this is causing the problem.
Try running the following code and you'll get the exact same exception.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
input.close();
Scanner other = new Scanner(System.in);
other.nextDouble();
}
When you call, input.close() it not only closes your scanner but closes your System.in. Now you still keep iterating over the loop even when scanner is closed (and keep scanning values) which causes excpetion.
UPDATE
Your code seems to go in a infinite loop because you do not break from the loop neither do you update the value of go which at some point might terminate the loop.
Thus, the scanner will keep reading values until all the inputs are exhausted and eventually throw java.util.NoSuchElementException exception (when all the inputs are exhausted).

Parsing a quadratic equation as a command line input

The goal is to create a program that takes a quadratic equation in quadratic form and solve it. Is there a different way to go about doing so other than StringTokenizer? Or is it possible to isolate just ^2 in StringTokenizer rather than ^ and 2 like it is doing now? I realized that using the way I wrote it, it will not allow equations to use 2 at all.
This question requires me to not take individual coefficients, but rather the entire equation itself.
Sample run: ”java SolveEquation2 1.5625x∧2+2.5x+1=0”. For this input the output should be: ”x=-0.8”
import java.util.Scanner;
import java.util.StringTokenizer;
class SolveEquation2 {
public static void main(String args[]){
Scanner scan = new Scanner(System.in);
System.out.print("Input a quadratic");
String equation = scan.nextLine();
StringTokenizer st = new StringTokenizer(equation, "x^2+-");
String a,b,c;
a = st.nextToken();
b = st.nextToken();
c = st.nextToken();
double a1 = Double.parseDouble(a);
double b1 = Double.parseDouble(b);
double c1 = Double.parseDouble(c);
double x = (b1 * b1) - (4 * a1 * c1);
double var1 = (-b1 + Math.sqrt(x)) / (2*a1);
double var2 = (-b1 - Math.sqrt(x)) / (2*a1);
if (x == 0){
System.out.println("x = " + var1);
}
if (x > 0){
System.out.println("x1 = " + var1);
System.out.println("x2 = " + var2);
}
if (x < 0){
System.out.println("No Solution");
}
}
}
You want to use regular expressions to parse the command line input.
It seems that what you're trying to do has been done many times before.
See here

Categories

Resources