How to make my code output more decimal places - java

I have an homework assignment to:
Write a program to calculate the result of one of three operations (minimum, L1 norm, L2 norm) on a vector of three numbers.
All my code is right, I think, but I need my outputs to have 2 decimal places. How would I do this?
import java.io.*;
import java.util.*;
import java.lang.*;
public class LA3a {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter three numbers: ");
double a = sc.nextDouble();
double b = sc.nextDouble();
double c = sc.nextDouble();
System.out.print("Enter operation: ");
String opr = sc.next();
if (opr.equals("min")) {
System.out.print("min(" , a , ", " , b , ", " , c , ")=");
if (a < b) {
if (a < c) {
System.out.print(a);
System.out.println();
}
else {
System.out.print(c);
System.out.println();
}
}
else {
if (b < c) {
System.out.print(b);
System.out.println();
}
else {
System.out.print(c);
System.out.println();
}
}
}
else if (opr.equals("l1")) {
double sum = Math.abs(a) + Math.abs(b) + Math.abs(c);
System.out.println("l1(" + a + ", " + b + ", " + c + ")=" + sum);
}
else if (opr.equals("l2")) {
double sum = a * a + b * b + c * c;
System.out.println("l2(" + a + ", " + b + ", " + c + ")=" + String.format("%.2f", Math.sqrt(sum)));
}
else {
System.out.println("Invalid operation!");
}
}
}

you can use printf to have a formatted print of a decimal number with 2 decimal places.
System.out.printf("%.2f", b);
the %.2f syntax tells Java to return your variable (b) with 2 decimal places. if you want more decimal places just increase it like: %.3f for 3 decimal places or %.4f for 4 decimal places.

I updated my code to:
if (a < b) {
if (a < c) {
System.out.printf("%.2f", a);
System.out.println();
}
else {
System.out.printf("%.2f", c);
System.out.println();
}
}
else {
if (b < c) {
System.out.printf("%.2f", b);
System.out.println();
}
else {
System.out.printf("%.2f", c);
System.out.println();
}
}
}
and my output is still only coming out as:
Enter three numbers: 1 2 3
Enter operation: min
min(1.0, 2.0, 3.0) = 1.00 - I still need this line to come out with 2 decimal places for each number.

For this part, there is an error:
System.out.print("min(" , a , ", " , b , ", " , c , ")=");
You put a bunch of commas instead of addition operators, your code should look like this:
System.out.print("min(" + a + ", " + b + ", " + c + ")=");
Also you have a common print statement in the following if/else statement:
if (a < c) {
System.out.print(a);
System.out.println();
}
else {
System.out.print(c);
System.out.println();
}
You should extract the print statement and use a call to Math.min() instead of an if statement to make it look something like this:
System.out.print(Math.min(a, c));
System.out.println();
As for having your output display two decimal places, Java has a class called DecimalFormat which can be imported with java.text.DecimalFormat; Create a new DecimalFormat like this:
DecimalFormat df = new DecimalFormat("#0.00"); //#0.00 means that we have two zeros after the decimal place
This makes a new DecimalFormat object that we can use to convert our numbers to Strings. For example, your print statement for the l1 operation should look something like this:
System.out.println("l1(" + df.format(a) + ", " + df.format(b) + ", " + df.format(c) + ")=" + df.format(sum));

Related

Getting error Exception in thread "main" java.util.IllegalFormatConversionException: d != java.lang.String [duplicate]

This question already has answers here:
Exception in thread "main" java.util.IllegalFormatConversionException: d != java.lang.String
(3 answers)
Closed 3 years ago.
I have encountered this error "Exception in thread "main" java.util.IllegalFormatConversionException: d != java.lang.String". I see that this is a fairly common question amongst Java newbies, and while I've attempted to apply the advice to my code, but I haven't had any success. I am hoping to get some feedback and suggestions on how to hopefully get this running properly. I am able to get it functioning properly using println, but having the output formatted is required for an assignment. Any advice would be appreciated.
Thanks.
import javax.swing.JOptionPane;
public class UserIO {
public static void main(String[] args) {
// initialize coefficients.
double a;
double b;
double c;
// int counter = 0;
String userInput; // take a String for input.
// display message. returns null.
JOptionPane.showMessageDialog(null,
"Welcome. Input positive a real number for a, b, and c. Numbers must range between 1.0 -10.0");
userInput = JOptionPane.showInputDialog("Input a real number for a.");
a = Double.parseDouble(userInput);// convert String userInput to real
// numbers.
System.out.println("Number for a = " + userInput); // print a
userInput = JOptionPane.showInputDialog("Input a real number for b. ");
b = Double.parseDouble(userInput);
System.out.println("Number for b = " + b); // print b
userInput = JOptionPane.showInputDialog("Input a real number for c.");
c = Double.parseDouble(userInput);
System.out.println("Number for c = " + c); // print c
// calculate quadratic equation 5 times, store in xValues then, print to
// screen.
double product;
double[] xValues = new double[5]; // array index of 5.
for (int i = 4; i >= 0; i--) {
xValues[i] = i + 1; // fills array with numbers 1-5.
// raise x to the i'th degree.
product = a * Math.pow(xValues[i], 2) + b * xValues[i] + c;
// System.out.println("[" + i + "]"+ " " + xValues[i] + " " +// product);
System.out.printf("%d , i " + "%1.2f ", xValues[i] + " " + "%1.3f ", product);
} // end loop
}
}
I guess this line causes theproblem:
System.out.printf("%d , i " + "%1.2f ", xValues[i] + " " + "%1.3f ", product);
which can be simplified to:
System.out.printf("%d , i %1.2f ", xValues[i] + " %1.3f ", product);
Here you can clearly see that you try to replace %d with the string xValues[i] + " %1.3f ".
I thinky you intended somethig different.
Look into the API, it should be like shown below.
System.out.printf("%d , %1.2f , %1.3f ", i, xValues[i], product);

I am trying to build a basic calculator using if statements

I am trying to make a basic calculator for class.
I came up with the code below but all it does it addition.
Even if I use -, *, or /.
Any tips?
Scanner input = new Scanner(System.in);
String num1, num2, operation, function;
System.out.println("Enter a simple equation: ");
function = input.nextLine();
int firstspace = function.indexOf(" ");
num1 = (function.substring(0,firstspace));
int lastspace = function.lastIndexOf(" ");
operation = (function.substring(firstspace,lastspace));
num2= (function.substring(lastspace+1,function.length()));
double n1 = Double.parseDouble(num1);
double n2 = Double.parseDouble(num2);
if (operation.equals(" + "));
{
System.out.println("your answer is " + (n1 + n2));
}
if (operation.equals(" - "))
{
System.out.println("your answer is " + (n1 - n2));
}
if (operation.equals(" / "))
{
System.out.println("your answer is " + (n1 / n2));
}
if (operation.equals(" * "))
{
System.out.println("your answer is " + ( n1*n2));
}
}
}
From what I see your code has this issue
if (operation.equals(" + "));
{
System.out.println("your answer is " + (n1 + n2));
}
Here you are putting a semi colon, which means when you run the code,it will execute this condition by default, so that means addition will always execute whether you like it or not.
So basically your code should be like this
if (operation.equals("+" ))
{
System.out.println("your answer is " + (n1 + n2));
}
if (operation.equals("-"))
{
System.out.println("your answer is " + (n1 - n2));
}
if (operation.equals("/"))
{
System.out.println("your answer is " + (n1 / n2));
}
if (operation.equals("*"))
{
System.out.println("your answer is " + ( n1*n2));
}
Hope this helps

Cannot Print Number of Digits Correctly

For my current programming project I am supposed to format my testOne & testTwo like "000". While the average is supposed to be "000.0". I have used DecimalFormat to no avail. Furthermore for my letterGradeArray the letter won't display even though the letter grade is in the actual array. Here is my code:
import java.util.Scanner;
//import java.text.NumberFormat;
import java.text.DecimalFormat;
public class GradeArray
{
#SuppressWarnings({ "unused", "resource" })
public static void main(String[] args)
{
//Setup all the variables
Scanner scan = new Scanner(System.in);
int[] testOne = new int[4]; // Students’ test one grades
int[] testTwo = new int[4]; // Students’ test two grades
double[] average = new double[4]; // Students’ average grades
double z = 002.00;
char letterGrade = 0;
char[] letterGradeArray = new char[4];
DecimalFormat fmt1 = new DecimalFormat("000");
DecimalFormat fmt2 = new DecimalFormat("000.0");
//Begin asking for scores
System.out.println("For test 1,");
for (int i=0;i<testOne.length;i++)
{
System.out.print("Enter score " + (i + 1) + ":");
testOne[i] = scan.nextInt();
fmt1.format(testOne[i]);
}
System.out.println("\nFor test 2,");
for (int i=0;i<testTwo.length;i++)
{
System.out.print("Enter score " + (i + 1) + ":");
testTwo[i] = scan.nextInt();
fmt1.format(testTwo[i]);
}
//Compute average
for(int i=0;i<average.length;i++)
{
{
average[i] = (testOne[i]+testTwo[i])/z;
fmt2.format(average[i]);
}
}
//Compute letter grade
for(int i=0;i<average.length;i++)
{
if (average[i]>= 90 )
{
letterGrade = 'A';
} else if (average[i] >= 80) {
letterGrade = 'B';
} else if (average[i] >= 70) {
letterGrade = 'C';
} else if (average[i] >= 60) {
letterGrade = 'D';
} else {
letterGrade = 'F';
}
//Put the letterGrade into the letterGradeArray
for(int x=0;i<letterGradeArray[x];x++)
{
letterGradeArray[x]=letterGrade;
}
}
//Print it out
System.out.println("Test 1 Test 2 Average Grade");
System.out.println("______ ______ _______ _____");
System.out.println(testOne[0] + " " + testTwo[0] + " " + average[0] +" " + letterGradeArray[0]);
System.out.println(testOne[1] + " " + testTwo[1] + " " + average[1] +" " + letterGradeArray[1]);
System.out.println(testOne[2] + " " + testTwo[2] + " " + average[2] +" " + letterGradeArray[2]);
System.out.println(testOne[3] + " " + testTwo[3] + " " + average[3] +" " + letterGradeArray[3]);
}
}
If anyone has any ideas on how to make this code cleaner do tell me, I feel with all the fors it is clunky.
You are calling fmt1.format(testOne[i]); but you are not doing anything with the result. Calling format returns a String, it does not affect the thing being passed as a parameter, so when you later print testOne[0] etc. you are printing the plain, original, values.
If you want the formatted values you will have to assign the return of .format() to something, keep it around, and print it instead of the original integer values. For example, patterned after how the rest of your code works...
String[] formattedOne = new String[4];
// ... later
formattedOne[i] = fmt1.format(testOne[i]);
// ... still later
System.out.println(formattedOne[0] + " " ..........

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);
}
}

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