How can I change this if-statement to switch? - java

//is the following code about quadratic formulas convertible to switch method?
Public class blah blah
Public static void main(String[] args) {
System.out.println("enter letter a");
New Scanner= System.in
Int a = input.nextint()
//same thing repeated for letters b and c.
//int d is for discriminant.
Int d= math.pow(b^2 -4ac, 0.5);
Int r1= (-(b) - (d))/2(a)
Int r2= (-(b) + (d))/2(a)
If(d>0){
System.out.println("2 solutions: r1; " + r1+ " and r2" + r2);
}else if(d=0){
System.out.println("1 solutions: r1; " + r1+ " and r2" + r2);
}else{
System.out.println("no real solution");
}

If you really really really wanna use a switch case
private static void switchOnIntegerPolarity() {
int a = 1;
int b = 2;
int c = 3;
int d = (int) Math.pow(b ^ 2 - 4 * a * c, 0.5);
int r1 = (-(b) - (d)) / 2 * (a);
int r2 = (-(b) + (d)) / 2 * (a);
switch ((int) Math.signum(d)) {
case 0: // Zero
System.out.println("1 solutions: r1; " + r1 + " and r2" + r2);
break;
case 1: // 'd' is Positive
System.out.println("2 solutions: r1; " + r1 + " and r2" + r2);
break;
case -1: // 'd' is Negative
System.out.println("no real solution");
break;
}
}

Related

I ned a while loop statment that makes the calculations loop and ask again

im not too sure how you add a loop statement to this. I want it to be a while loop that makes it do that the calculations repeat after finishing. I've tried but it just keeps on giving me errors. ive tried doing While statements but just will not work im not sure how you set it up as my teacher did not explain very well
import com.godtsoft.diyjava.DIYWindow;
public class Calculator extends DIYWindow {
public Calculator() {
// getting number one
double number1 = promptForDouble("Enter a number");
//getting number2
int number2 = promptForInt("Enter an integer");
//getting what to do with operation
print("What do you want to do with these numbers?\nAdd\tSubtract\tMultiply\tDivide");
String operation = input();
//declaring variable here so the same one can be used
double answer = 0;
switch(operation) {
case "add":
answer = number1 + number2;
print(number1 + " + " + number2 + " = " + answer);
break;
case "subtract":
answer = number1 - number2;
print(number1 + " - " + number2 + " = " + answer);
break;
case "multiply":
answer = number1 * number2;
print(number1 + " * " + number2 + " = " + answer);
break;
case "divide":
try {
answer = number1 / number2;
}
catch(ArithmeticException e) {
print("A number cannot be divided by 0.");
}
print(number1 + " / " + number2 + " = " + answer);
break;
}
double double1 = promptForDouble("Enter a number");
double double2 = promptForDouble("Enter another number");
double double3 = promptForDouble("Enter one last number");
print("What do you want to do with these numbers?\nAdd\tSubtrack\tMultiply\tDivide");
String operation2 = input();
double answer2 = 0;
switch(operation2) {
case "add":
answer2 = double1 + double2 + double3;
print(double1 + " + " + double2 + " + " + double3 + " = " + answer2);
break;
case "subtract":
answer2 = double1 - double2 - double3;
print(double1 + " - " + double2 + " - " + double3 + " = " + answer2);
break;
case "multiply":
answer2 = double1 * double2 * double3;
print(double1 + " * " + double2 + " * " + double3 + " = " + answer2);
break;
case "divide":
try {
answer2 = double1 / double2 / double3;
}
catch(ArithmeticException e) {
print("A number cannot be divided by 0.");
}
print(double1 + " / " + double2 + " / " + double3 + " = " + answer2);
break;
}
want it to loop after the code on top
}
private double promptForDouble(String prompt) {
double number1 = 0;
print(prompt);
String number = input();
try {
number1 = Double.parseDouble(number);
}
catch(NumberFormatException e){
print("That is not a number. Please enter a number.");
number1 = promptForDouble(prompt);
}
return number1;
}
private int promptForInt(String prompt) {
int number2 = 0;
print(prompt);
String number = input();
try {
number2 = Integer.parseInt(number); }
catch(NumberFormatException e) {
print("That is not an integer. Enter an integer.");
number2 = promptForInt(prompt); }
return number2;
}
public static void main(String[] args) {
new Calculator();
}
}
Put this in your main method:
while (true)
{
Thread.sleep(1000); // optional, make some deplay for more nature
new Calculator();
}
Or you can wrap all body blocks of the constructor inside the above while statement.

ArithmeticException with Mixed Fractions calculator

This program correctly calculates mixed fractions. I want the while loop to terminate once I enter two zeros. However, when I entered two zeros separated by a space, I get " Exception in thread "main" java.lang.ArithmeticException: / by zero at MixedFractions.main etc. I just want the user to not be able to input a value for a and be once they enter 0 for both variables. Thank you
import java.util.Scanner;
public class MixedFractions {
public static void main (String [] args)
{
Scanner scan = new Scanner(System.in);
int a = scan.nextInt(); int b = scan.nextInt();
int c = Math.abs(a / b);
int d = c * b;
int e = c * b;
int f = a - e;
while ( a != 0 && b!= 0)
{
if(c == 0)
{
System.out.println(c + " " + a + " / " + b);
}
else if(d == a)
{
a = 0;
System.out.println(c + " " + a + " / " + b);
}
else if( c != a)
{
e = c * b;
f = a - e;
System.out.println(c + " " + f + " / " + b);
}
a = scan.nextInt(); b = scan.nextInt();
c = Math.abs(a/b);
}
}
}
Try with this:
public static void main (String [] args) {
Scanner scan = new Scanner(System.in);
int a = scan.nextInt();
int b = scan.nextInt();
while ( a != 0 && b!= 0) {
int c = Math.abs(a / b);
int d = c * b;
if(c == 0) {
System.out.println(c + " " + a + " / " + b);
} else if(d == a) {
a = 0;
System.out.println(c + " " + a + " / " + b);
} else if( c != a) {
int e = c * b;
int f = a - e;
System.out.println(c + " " + f + " / " + b);
}
a = scan.nextInt();
b = scan.nextInt();
}
}

Solving quadratic equation USING METHODS, java

I have a java program written for solving the quadratic equation but the assignment requires me to have methods for each of the tasks: displaying the equation, determining if the equation has real solutions, calculating a solution, and displaying the solutions if they exist. I have methods for everything except for checking if the solutions are real except my methods are saying that they are undefined. Can someone please help me format my methods, I don't quite know how to implement them? here is the code I have thus far:
import java.util.Scanner;
public class QuadraticFormula {
public static void main(String[] args)
{
//Creating scanner and variables
Scanner s = new Scanner(System.in);
System.out.println("Insert value for a: ");
double a = Double.parseDouble(s.nextLine());
System.out.println("Insert value for b: ");
double b = Double.parseDouble(s.nextLine());
System.out.println("Insert value for c: ");
double c = Double.parseDouble(s.nextLine());
//Display format for negatives
displayEquation(double a, double b, double c);{
if (b > 0 && c > 0 ){
System.out.println(a + "x^2 + " + b + "x + " + c + " =0");}
if (b < 0 && c > 0 ){
System.out.println(a + "x^2 " + b + "x + " + c + " =0");}
if (b > 0 && c < 0 ){
System.out.println(a + "x^2 + " + b + "x " + c + " =0");}
if (b < 0 && c < 0 ){
System.out.println(a + "x^2 " + b + "x " + c + " =0");}
s.close();
}
//The work/formula
private static double calculateSolution(double a, double b, double c);
{
double answer1 = (-b + Math.sqrt(Math.pow(b, 2) - (4 * a * c))) / (2 * a);
return answer1;
}
private static double calculateSolution(double a, double b, double c);
{
double answer2 = (-b - Math.sqrt(Math.pow(b, 2) - (4 * a * c))) / (2 * a);
return answer2;
}
//Display results and check if the solution is imaginary (real or not)
private static void displaySolutions(double answer1, double answer2); {
if (Double.isNaN(answer1) || Double.isNaN(answer2))
{
System.out.println("Answer contains imaginary numbers");
} else System.out.println("The values are: " + answer1 + ", " + answer2);
}
}
}
Your methods need to be defined outside your main method. You can then call them in your main method like this:
displayEquation(a, b, c);
You also should remove the semicolons after your method definitions. It should look like this:
public class QuadraticFormula {
public static void main(String[] args)
{
//Creating scanner and variables
Scanner s = new Scanner(System.in);
System.out.println("Insert value for a: ");
double a = Double.parseDouble(s.nextLine());
System.out.println("Insert value for b: ");
double b = Double.parseDouble(s.nextLine());
System.out.println("Insert value for c: ");
double c = Double.parseDouble(s.nextLine());
s.close();
}
//Display format for negatives
public static void displayEquation(double a, double b, double c) {
if (b > 0 && c > 0 ){
System.out.println(a + "x^2 + " + b + "x + " + c + " =0");}
if (b < 0 && c > 0 ){
System.out.println(a + "x^2 " + b + "x + " + c + " =0");}
if (b > 0 && c < 0 ){
System.out.println(a + "x^2 + " + b + "x " + c + " =0");}
if (b < 0 && c < 0 ){
System.out.println(a + "x^2 " + b + "x " + c + " =0");}
}
private static double calculateSolution(double a, double b, double c) {
double answer2 = (-b - Math.sqrt(Math.pow(b, 2) - (4 * a * c))) / (2 * a);
return answer2;
}
//Display results and check if the solution is imaginary (real or not)
private static void displaySolutions(double answer1, double answer2) {
if (Double.isNaN(answer1) || Double.isNaN(answer2))
{
System.out.println("Answer contains imaginary numbers");
}
else System.out.println("The values are: " + answer1 + ", " + answer2);
}
}

Hanging token from user input is not allowing me to proceed in my program

My program is not allowing me to enter user input if i do not enter a number and i want to go through the program again, it think its due to a hanging token somewhere but i cannot seem to find it.
import java.util.Scanner;
public class LessonTwo {
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args) {
char answer = ' ';
do {
System.out.print("Your favorite number: ");
if (userInput.hasNextInt()) {
int numberEntered = userInput.nextInt();
userInput.nextLine();
System.out.println("You entered " + numberEntered);
int numEnteredTimes2 = numberEntered + numberEntered;
System.out.println(numberEntered + " + " + numberEntered
+ " = " + numEnteredTimes2);
int numEnteredMinus2 = numberEntered - 2;
System.out.println(numberEntered + " - 2 " + " = "
+ numEnteredMinus2);
int numEnteredTimesSelf = numberEntered * numberEntered;
System.out.println(numberEntered + " * " + numberEntered
+ " = " + numEnteredTimesSelf);
double numEnteredDivide2 = (double) numberEntered / 2;
System.out.println(numberEntered + " / 2 " + " = "
+ numEnteredDivide2);
int numEnteredRemainder = numberEntered % 2;
System.out.println(numberEntered + " % 2 " + " = "
+ numEnteredRemainder);
numberEntered += 2; // *= /= %= Also work
numberEntered -= 2;
numberEntered++;
numberEntered--;
int numEnteredABS = Math.abs(numberEntered); // Returns the
int whichIsBigger = Math.max(5, 7);
int whichIsSmaller = Math.min(5, 7);
double numSqrt = Math.sqrt(5.23);
int numCeiling = (int) Math.ceil(5.23);
System.out.println("Ceiling: " + numCeiling);
int numFloor = (int) Math.floor(5.23);
System.out.println("Floor: " + numFloor);
int numRound = (int) Math.round(5.23);
System.out.println("Rounded: " + numRound);
int randomNumber = (int) (Math.random() * 10);
System.out.println("A random number " + randomNumber);
} else {
System.out.println("Sorry you must enter an integer");
}
System.out.print("Would you like to try again? ");
answer = userInput.next().charAt(0);
}while(Character.toUpperCase(answer) == 'Y');
System.exit(0);
}
}
Yes you are right you need to consume the characters first after the user inputted character in the nextInt before allowing the user to input data again
just add this in your else block and it will work:
else {
System.out.println("Sorry you must enter an integer");
userInput.nextLine(); //will consume the character that was inputted in the `nextInt`
}
EDIT:
change this:
answer = userInput.next().charAt(0);
to:
answer = userInput.nextLine().charAt(0);

Finding roots of quadratic equation

I have this code so far but every time i run and put the three numbers in a get the roots are NaN can some one please help or point me to where i went wrong.
import java.util.Scanner;
class Quadratic {
public static void main(String[] args) {
System.out.println("Enter three coefficients");
Scanner sc = new Scanner(System.in);
double a = sc.nextDouble();
double b = sc.nextDouble();
double c = sc.nextDouble();
double root1= (-b + Math.sqrt( b*b - 4*a*c ) )/ (2*a);
double root2= (-b - Math.sqrt( b*b - 4*a*c ) )/ (2*a);
System.out.println("The roots1 are: "+ root1);
System.out.println("The roots2 are: " + root2);
}
}
You have to remember that not every quadratic equation has roots that can be expressed in terms of real numbers. More specifically, if b*b - 4*a*c < 0, then the roots will have an imaginary part and NaN will be returned, since Math.sqrt of a negative number returns NaN, as specified in the documentation. This works for coefficients such that b*b - 4*a*c >= 0, however:
Enter three coefficients
1
5
6
The roots1 are: -2.0
The roots2 are: -3.0
If you wanted to account for non-real roots as well, you could do something like
double d = (b * b - 4 * a * c);
double re = -b / (2 * a);
if (d >= 0) { // i.e. "if roots are real"
System.out.println(Math.sqrt(d) / (2 * a) + re);
System.out.println(-Math.sqrt(d) / (2 * a) + re);
} else {
System.out.println(re + " + " + (Math.sqrt(-d) / (2 * a)) + "i");
System.out.println(re + " - " + (Math.sqrt(-d) / (2 * a)) + "i");
}
Hope this helps--
import java.util.Scanner;
class QuadraticCalculator
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
double a,b,c,quad_dis,quad_11,quad_1,quad_21,quad_2;
System.out.println("Enter the value of A");
a=s.nextDouble();
System.out.println("\nEnter the value of B");
b=s.nextDouble();
System.out.println("\nEnter the value of C");
c=s.nextDouble();
quad_dis=b*b-4*a*c;
quad_11=(-1*b)+(Math.sqrt(quad_dis));
quad_1=quad_11/(2*a);
quad_21=(-1*b)-(Math.sqrt(quad_dis));
quad_2=quad_21/(2*a);
int choice;
System.out.println("\n\nWhat do you want to do with the numbers you entered ?\n(1) Calculate Discriminant\n(2) Calculate the values\n(3) Find the nature of roots\n(4) All of the above");
choice=s.nextInt();
switch(choice)
{
case 1: System.out.println("\nDiscriminant: "+quad_dis);
break;
case 2: System.out.println("\nValues are: "+quad_1+", "+quad_2);
break;
case 3: if(quad_dis>0)
{
System.out.println("\nThe roots are REAL and DISTINCT");
}
else if(quad_dis==0)
{
System.out.println("\nThe roots are REAL and EQUAL");
}
else
{
System.out.println("\nThe roots are IMAGINARY");
}
break;
case 4: System.out.println("\nDiscriminant: "+quad_dis);
System.out.println("\nValues are: "+quad_1+", "+quad_2);
if(quad_dis>0)
{
System.out.println("\nThe roots are REAL and DISTINCT");
}
else if(quad_dis==0)
{
System.out.println("\nThe roots are REAL and EQUAL");
}
else
{
System.out.println("\nThe roots are IMAGINARY");
}
break;
}
System.out.println("\n\nThank You for using this Calculator");
}
}
You could use the following code. First, it will check whether input equation is quadratic or not. And if input equation is quadratic then it will find roots.
This code is able to find complex roots too.
public static void main(String[] args) {
// Declaration of variables
float a = 0, b = 0, c = 0, disc, sq_dis;
float[] root = new float[2];
StringBuffer number;
Scanner scan = new Scanner(System.in);
// Input equation from user
System.out.println("Enter Equation in form of ax2+bx+c");
String equation = scan.nextLine();
// Regex for quadratic equation
Pattern quadPattern = Pattern.compile("(([+-]?\\d*)[Xx]2)+((([+-]?\\d*)[Xx]2)*([+-]\\d*[Xx])*([+-]\\d+)*)*|((([+-]?\\d*)[Xx]2)*([+-]\\d*[Xx])*([+-]\\d+)*)*(([+-]?\\d*)[Xx]2)+|((([+-]?\\d*)[Xx]2)*([+-]\\d*[Xx])*([+-]\\d+)*)*(([+-]?\\d*)[Xx]2)+((([+-]?\\d*)[Xx]2)*([+-]\\d*[Xx])*([+-]\\d+)*)*");
Matcher quadMatcher = quadPattern.matcher(equation);
scan.close();
// Checking if given equation is quadratic or not
if (!(quadMatcher.matches())) {
System.out.println("Not a quadratic equation");
}
// If input equation is quadratic find roots
else {
// Splitting equation on basis of sign
String[] array = equation.split("(?=[+-])");
for (String term : array) {
int len = term.length();
StringBuffer newTerm = new StringBuffer(term);
// If term ends with x2, then delete x2 and convert remaining term into integer
if (term.endsWith("X2") || (term.endsWith("x2"))) {
number = newTerm.delete(len - 2, len);
a += Integer.parseInt(number.toString());
}
// If term ends with x, then delete x and convert remaining term into integer
else if (term.endsWith("X") || (term.endsWith("x"))) {
number = newTerm.deleteCharAt(len - 1);
b += Integer.parseInt(number.toString());
}
// If constant,then convert it into integer
else {
c += Integer.parseInt(term);
}
}
// Display value of a,b,c and complete equation
System.out.println("Coefficient of x2: " + a);
System.out.println("Coefficient of x: " + b);
System.out.println("Constent term: " + c);
System.out.println("The given equation is: " + a + "x2+(" + b + ")x+(" + c + ")=0");
// Calculate discriminant
disc = (b * b) - (4 * a * c);
System.out.println(" Discriminant= " + disc);
// square root of discriminant
sq_dis = (float) Math.sqrt(Math.abs(disc));
// conditions to find roots
if (disc > 0) {
root[0] = (-b + sq_dis) / (2 * a);
root[1] = (-b - sq_dis) / (2 * a);
System.out.println("Roots are real and unequal");
System.out.println("Root1= " + root[0]);
System.out.println("Root2= " + root[1]);
}
else if (disc == 0) {
root[0] = ((-b) / (2 * a));
System.out.println("Roots are real and equal");
System.out.println("Root1=Root2= " + root[0]);
}
else {
root[0] = -b / (2 * a);
root[1] = Math.abs((sq_dis) / (2 * a));
System.out.println("Roots are complex");
System.out.println("ROOT1= " + root[0] + "+" + root[1] + "+i");
System.out.println("ROOT2= " + root[0] + "-" + root[1] + "+i");
}
}
else {
if ((Math.sqrt(-d) / (2*a)) > 0) {
System.out.println(r + " + " + (Math.sqrt(-d) / (2*a)) + " i");
System.out.println(r + " - " + (Math.sqrt(-d) / (2*a)) + " i");
}
else if ((Math.sqrt(-d) / (2*a)) == 0){
System.out.println(r);
}
else {
System.out.println(r + " - " + (Math.sqrt(-d) / (2*a)) + " i");
System.out.println(r + " + " + (Math.sqrt(-d) / (2*a)) + " i");
}

Categories

Resources