I am trying to make a calculator that performs the quadratic formula.
Currently if my result would be a decimal it returns NaN. (EDIT: Resolved)
Preferably I would like the result to be in an simplified radical form (i.e. √(99) = 3√(11) ).
How would I go about achieving this?
This is what I have so far.
// Do the math
private double mathCalcPlus(double varA,double varB,double varC) {
return ((-varB + Math.sqrt(varB * varB - 4 * varA * varC)) / 2 * varA);
}
private double mathCalcMinus(double varA,double varB,double varC) {
return ((-varB - Math.sqrt(varB * varB - 4 * varA * varC)) / 2 * varA);
}
Any help will be greatly appreciated.
This works great! However, I decided to add the top bar of the radical sign just for fun :D
import java.util.Scanner;
public class Radical {
public static void main(String[] args) {
System.out.print("Enter the unsimplified radical: ");
Scanner scan = new Scanner(System.in);
int input = scan.nextInt();
recurse(input);
}
public static void recurse(int x) {
System.out.println(" ______");
System.out.println("Attempting to simplify -/" + x);
int a = 0;
int b = 0;
int count = 0;
for (int i = 1; i < x; i++) {
if ((i * (x/i)) == x) {
//System.out.println(i + "<i rest>" + (x/i));
a = i;
b = x/i;
if (Math.sqrt(a)%1==0) {
if (a != 1) {
System.out.println(" ______");
System.out.println(" " + (int)Math.sqrt(a) + "-/" + b);
count = 1;
}
}
}
}
if (count>0) {
recurse(b);
} else if (count==0) {
System.out.println(" ______");
System.out.println("Cannot simplify -/" + x);
}
}
}
Here's something that might help as far as simplifying radicals go. Give it the unsimplified radical (let's say 850) and it should return the correct answer (5-/34). It also tries to recursively simplify what's left in the radical in case it needs to be broken down again.
This was written quickly so I'm sure there are edge cases I missed that will throw off the calculations but I hope it helps at least a little. Best of luck!
import java.util.Scanner;
public class Radical {
public static void main(String[] args) {
System.out.print("Enter the unsimplified radical: ");
Scanner scan = new Scanner(System.in);
int input = scan.nextInt();
recurse(input);
}
public static void recurse(int x) {
System.out.println("Attempting to simplify -/" + x);
int a = 0;
int b = 0;
int count = 0;
for (int i = 1; i < x; i++) {
if ((i * (x/i)) == x) {
//System.out.println(i + "<i rest>" + (x/i));
a = i;
b = x/i;
if (Math.sqrt(a)%1==0) {
if (a != 1) {
System.out.println((int)Math.sqrt(a) + "-/" + b);
count = 1;
}
}
}
}
if (count>0) {
recurse(b);
} else if (count==0) {
System.out.println("Cannot simplify -/" + x);
}
}
}
Related
I'm trying to compile my first major program. Unfortunately in getBestFare() I get "null" coming out all the time. And it shouldn't! I'm asking you guys for help what's wrong.
I rebuilt the entire getBestFare() method but unfortunately it keeps coming up with "null". The earlier code was a bit more messy. Now it's better, but it still doesn't work.
public class TransitCalculator {
public int numberOfDays;
public int transCount;
public TransitCalculator(int numberOfDays, int transCount) {
if(numberOfDays <= 30 && numberOfDays > 0 && transCount > 0){
this.numberOfDays = numberOfDays;
this.transCount = transCount;
} else {
System.out.println("Invalid data.");
}
}
String[] length = {"Pay-per-ride", "7-day", "30-day"};
double[] cost = {2.75, 33.00, 127.00};
public double unlimited7Price(){
int weekCount = numberOfDays/7;
if (numberOfDays%7>0){
weekCount+=1;
}
double weeksCost = weekCount * cost[1];
return weeksCost;
}
public double[] getRidePrices(){
double price1 = cost[0];
double price2 = ((cost[1]*unlimited7Price()) / (unlimited7Price() * 7));
double price3 = cost[2] / numberOfDays;
double[] getRide = {price1, price2, price3};
return getRide;
}
public String getBestFare(){
int num = 0;
for (int i = 0; i < getRidePrices().length; i++) {
if(getRidePrices()[i] < getRidePrices()[num]){
return "You should get the " + length[num] + " Unlimited option at " + getRidePrices()[num]/transCount + " per ride.";
}
}
return null;
}
public static void main(String[] args){
TransitCalculator one = new TransitCalculator(30, 30);
System.out.println(one.unlimited7Price());
System.out.println(one.getRidePrices()[2]);
System.out.println(one.getBestFare());
}
}
This is the code I atempted with the guide of external video which didnt cover expected output in terms of formatting
public class Lab3Class {
public static void main(String[] args) {
// TODO Auto-generated method stub
int table = 1;
while(table<10) {
int i = 1;
while(i<=10)
{
System.out.println(table+ " * "+i+" = "+(table*i));
i++;
}
System.out.println(" ");
table++;
}
}
}
You are just missing a check for even numbers i.e. if (table % 2 == 0).
public class Main {
public static void main(String[] args) {
int table = 1;
while (table < 10) {
if (table % 2 == 0) {
int i = 1;
while (i <= 10) {
System.out.println(table + " * " + i + " = " + (table * i));
i++;
}
}
System.out.println();
table++;
}
}
}
Alternatively, you can start table with 2 and increment it by 2 in each iteration as follows:
public class Main {
public static void main(String[] args) {
int table = 2;
while (table < 10) {
int i = 1;
while (i <= 10) {
System.out.println(table + " * " + i + " = " + (table * i));
i++;
}
System.out.println();
table += 2;
}
}
}
If you need to print it in a tabular structure, you can write the loops as follows:
public class Main {
public static void main(String[] args) {
for (int line = 1; line <= 10; line++) {
for (int i = 2; i <= 10; i += 2) {
System.out.print(i + "*" + line + "=" + (i * line) + "\t");
}
System.out.println();
}
}
}
Output:
2*1=2 4*1=4 6*1=6 8*1=8 10*1=10
2*2=4 4*2=8 6*2=12 8*2=16 10*2=20
2*3=6 4*3=12 6*3=18 8*3=24 10*3=30
2*4=8 4*4=16 6*4=24 8*4=32 10*4=40
2*5=10 4*5=20 6*5=30 8*5=40 10*5=50
2*6=12 4*6=24 6*6=36 8*6=48 10*6=60
2*7=14 4*7=28 6*7=42 8*7=56 10*7=70
2*8=16 4*8=32 6*8=48 8*8=64 10*8=80
2*9=18 4*9=36 6*9=54 8*9=72 10*9=90
2*10=20 4*10=40 6*10=60 8*10=80 10*10=100
As you can see, it looks cleaner by using a for loop. However, I recommend you also practice it with a while loop. Once you gain more confidence, I also recommend you use String::format or System.out.printf for better formatting.
This is a very small data set but if the dataset is huge, you can improve the performance by reducing the I/O operation. For this, you can append the result to a StringBuilder and print it just once at the end.
public class Main {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
for (int line = 1; line <= 10; line++) {
for (int i = 2; i <= 10; i += 2) {
sb.append(i).append('*').append(line).append('=').append(i * line).append('\t');
}
sb.append('\n');
}
System.out.println(sb);
}
}
This code uses Swing and awt to compute prime factorization, the code works, but it shows only one prime factor, for example: if i compute 56 the answer is just 7, how can i fix it?
thanks in advance
calculate6.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Get values from text fields
try {
int a = Integer.parseInt(input1.getText());
result.setText(String.valueOf(a + " "));
for (int i = 2; i <= a; i++) {
while (a % i == 0) {
result.setText(String.valueOf(i + " "));
// System.out.println(i + " ");
a = a / i;
}
}
if (a < 1)
result.setText(String.valueOf(a + " "));
// System.out.println(a + " ");
}
catch (Exception f) {
JOptionPane.showMessageDialog(rootPane, "ERROR: " + (f.getMessage()));
}
String aField = input1.getText();
if (e.getSource() == calculate6) {
if ("".equals(aField)) {
String emptyFieldWarning;
emptyFieldWarning = "One field is empty!";
JOptionPane.showMessageDialog(rootPane, emptyFieldWarning);
}
}
}
});
Edit 1: i have changed the operation part
Your Swing part is fine. If you just try to execute
int a = 56;
for(int i = 2; i< a; i++) {
while (a % i == 0) {
a = a / i;
}
}
System.out.println(a);
you get 7,so the problem is in this part, you shoul look over here
Problem is in the while loop. It is not accumulating the factors. Try this getPrimeFactors() in this sample program.
import java.util.*;
public class PrimeFactors {
public static void main(String[] args) {
System.out.println("56 -> " + PrimeFactors.getPrimeFactors(56));
System.out.println("30 -> " + PrimeFactors.getPrimeFactors(30));
System.out.println("154 -> " + PrimeFactors.getPrimeFactors(154));
}
public static List<Integer> getPrimeFactors(int input) {
List<Integer> factors = new ArrayList<>();
for (int i = 2; i <= input; i++) {
while (input%i == 0) {
input = input/i;
factors.add(i);
}
}
return factors;
}
}
public static final IntFunction<String> getPrimeFactorsAsString = num -> {
List<Integer> res = new ArrayList<>();
for (int i = 2, sqrt = (int)Math.sqrt(num); i <= sqrt; i++) {
while (num % i == 0) {
res.add(i);
num /= i;
}
}
return res.stream().map(String::valueOf).collect(Collectors.joining(" "));
};
Demo
System.out.println(getPrimeFactorsAsString.apply(56)); // 2 2 2 7
System.out.println(getPrimeFactorsAsString.apply(660)); // 2 2 3 5 11
I'm working on a project for a potential internship to take a String input of bowling scores and add them up to a final score. I'm having difficult passing one of my tests and was wondering if you could help me figure out my fault.
The test that is not working is isNinetySix and it is giving me a result of 98 instead. Please help!
public class Game {
private int roll = 0;
private int[] rolls = new int[21];
public void rolls(String scoreCard) {
for (int i=0; i< scoreCard.length(); i++) {
if (scoreCard.charAt(i) == 'X') {
rolls[roll++] = 10;
} else if (scoreCard.charAt(i) == '/') {
rolls[roll++] = 10;
} else if (scoreCard.charAt(i) == '-') {
} else {
int x = scoreCard.charAt(i);
rolls[roll++] = x - '0';
}
}
}
public int score() {
int score = 0;
int cursor = 0;
for (int frame = 0; frame < 10; frame++) {
if (isStrike(cursor)) {
score += 10 + rolls[cursor+1] + rolls[cursor+2];
cursor ++;
} else if (isSpare(cursor)) {
score += 10 + rolls[cursor+2];
cursor += 2;
} else {
score += rolls[cursor] + rolls[cursor+1];
cursor += 2;
}
}
return score;
}
private boolean isStrike(int cursor) {
return rolls[cursor] == 10;
}
private boolean isSpare(int cursor) {
return rolls[cursor] + rolls[cursor+1] == 10;
}
//Print scores for each frame
public void printFrameScore(int[] frame) {
for (int i = 1; i < frame.length; i++) {
System.out.println(i + ": " + frame[i]);
}
}
public void displayRolls() {
for (int i = 0; i < rolls.length; i++) {
System.out.print(rolls[i] + ", ");
}
}
}
Tests
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.is;
import org.junit.Before;
import org.junit.Test;
public class GameTest {
private Game game;
#Before
public void setUp(){
game = new Game();
}
#Test
public void isPerfect() {
game.rolls("X-X-X-X-X-X-X-X-X-X-XX");
assertThat(game.score(), is(300));
}
#Test
public void isGutter() {
game.rolls("00-00-00-00-00-00-00-00-00-00");
assertThat(game.score(), is(0));
}
#Test
public void isNinety() {
game.rolls("45-54-36-27-09-63-81-18-90-72");
assertThat(game.score(), is(90));
}
#Test
public void isOneFifty(){
game.rolls("5/-5/-5/-5/-5/-5/-5/-5/-5/-5/-5");
assertThat(game.score(), is(150));
}
#Test
public void isNinetySix() {
game.rolls("45-54-36-27-09-63-81-18-90-7/-5");
assertThat(game.score(), is(96));
}
}
The problem here seems to be that your isSpare() function never returns true because you assigned each / a value of 10. The result of the addition of the two rolls in a frame with a spare was more than 10. If I were you I would try to clean up the assignment of / to actually be 10 - prev_role_score. This would be cleaner than making isSpare() check for greater than 10. There are other ways to clean up the code to, you could try to refactor some to impress whoever you submit to.
} else if (scoreCard.charAt(i) == '/') {
int diff = 10 - rolls[roll - 1];
rolls[roll++] = diff;
}
Your code is failing in the below block (after your 9th frame, you're at a score of 81). You're code is looking at the index that contains the value 7 and the / which you represent as 10, thereby giving you 17 rather than 10 for the spare.
...
} else {
score += rolls[cursor] + rolls[cursor+1];
cursor += 2;
}
...
So, if I were making suggestions, and I'm not sure what the expectations are for your project, I would tell you to think about easier ways to traverse your string by splitting, searching, then adding. Below is a quick example:
public void rolls(String scorecard) {
String [] framesets = scorecard.split("-");
//hunt for special cases like spare and strikes
//do work to hold your scores
}
I am using Comb Sort to sort out a given array of Strings. The code is :-
public static int combSort(String[] input_array) {
int gap = input_array.length;
double shrink = 1.3;
int numbOfComparisons = 0;
boolean swapped=true;
//while(!swapped && gap>1){
System.out.println();
while(!(swapped && gap==1)){
gap = (int)(gap/shrink);
if(gap<1){
gap=1;
}
int i = 0;
swapped = false;
String temp = "";
while((i+gap) < input_array.length){
numbOfComparisons++;
if(Compare(input_array[i], input_array[i+gap]) == 1){
temp = input_array[i];
input_array[i] = input_array[i+gap];
input_array[i+gap] = temp;
swapped = true;
System.out.println("gap: " + gap + " i: " + i);
ArrayUtilities.printArray(input_array);
}
i++;
}
}
ArrayUtilities.printArray(input_array);
return numbOfComparisons;
}
The problem is that while it sorts many arrays , it gets stuck in an infinite loop for some arrays, particularly small arrays. Compare(input_array[i], input_array[i+gap]) is a small method that returns 1 if s1>s2, returns -1 if s1
try this version. The string array is changed to integer array (I guess you can change it back to string version). The constant 1.3 is replaced with 1.247330950103979.
public class CombSort
{
private static final int PROBLEM_SIZE = 5;
static int[] in = new int[PROBLEM_SIZE];
public static void printArr()
{
for(int i=0;i<in.length;i++)
{
System.out.print(in[i] + "\t");
}
System.out.println();
}
public static void combSort()
{
int swap, i, gap=PROBLEM_SIZE;
boolean swapped = false;
printArr();
while ((gap > 1) || swapped)
{
if (gap > 1)
{
gap = (int)( gap / 1.247330950103979);
}
swapped = false;
for (i = 0; gap + i < PROBLEM_SIZE; ++i)
{
if (in[i] - in[i + gap] > 0)
{
swap = in[i];
in[i] = in[i + gap];
in[i + gap] = swap;
swapped = true;
}
}
}
printArr();
}
public static void main(String[] args)
{
for(int i=0;i<in.length;i++)
{
in[i] = (int) (Math.random()*PROBLEM_SIZE);
}
combSort();
}
}
Please find below implementation for comb sort in java.
public static void combSort(int[] elements) {
float shrinkFactor = 1.3f;
int postion = (int) (elements.length/shrinkFactor);
do {
int cursor = postion;
for(int i=0;cursor<elements.length;i++,cursor++) {
if(elements[i]>elements[cursor]) {
int temp = elements[cursor];
elements[cursor] = elements[i];
elements[i] = temp;
}
}
postion = (int) (postion/shrinkFactor);
}while(postion>=1);
}
Please review and let me know your's feedback.