Finding GCD java - java

Good Day! I have a problem on my code. It has an error and here's is the picture:
Here is my code:
private static int gcd(int a, int b, int c) {
return gcd(gcd(a,b),c);
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
//DecimalFormat fmt = new DecimalFormat("+##");
int x1 , y1, x2, y2, gcd,
inverted_x1, inverted_y1, inverted_x2, inverted_y2,
x1Times2, x2Times2, y1Times2, y2Times2,
x1raised, y1raised, x2raised, y2raised,
computeX, computeY, computeS,
x2inverted, y2inverted, invertedx2times2, invertedy2times2;
try{
x1 = Integer.parseInt(jTextField1.getText());
y1 = Integer.parseInt(jTextField2.getText());
x2 = Integer.parseInt(jTextField3.getText());
y2 = Integer.parseInt(jTextField4.getText());
int[] array = new int[4];
array[0] = x1;
array[1] = x2;
array[2] = y1;
array[3] = y2;
inverted_x1 = x1 *= -1;
inverted_y1 = y1 *= -1;
inverted_x2 = x2 *= -1;
inverted_y2 = y2 *= -1;
jTextField5.setText("= (x" + formatSign(inverted_x1) + ")² + (y" + formatSign(inverted_y1) + ")²"
+ " = (x" + formatSign(inverted_x2) + ")² + (y" + formatSign(inverted_y2) + ")²" );
x1Times2 = inverted_x1*2;
y1Times2 = inverted_y1*2;
x2Times2 = inverted_x2*2;
y2Times2 = inverted_y2*2;
x1raised = inverted_x1*inverted_x1;
y1raised = inverted_y1*inverted_y1;
x2raised = inverted_x2*inverted_x2;
y2raised = inverted_y2*inverted_y2;
jTextField9.setText("= x²" + formatSign(x1Times2) + "x" + formatSign(x1raised) + "+y²" + formatSign(y1Times2)
+ "y" + formatSign(y1raised) + "= x²" + formatSign(x2Times2) + "x" + formatSign(x2raised) + "+y²"
+ formatSign(y2Times2) + "y" + formatSign(y2raised));
x2inverted = x2raised *= -1;
y2inverted = y2raised *= -1;
invertedx2times2 = x2Times2 *= -1;
invertedy2times2 = y2Times2 *= -1;
computeX = x1Times2 + invertedx2times2;
computeY = y1Times2 + invertedy2times2;
computeS = x2inverted + y2inverted + x1raised + y1raised;
jTextField17.setText("= " + formatSign(computeX) + "x" + formatSign(computeY) + "y" + formatSign(computeS) + "= 0");
gcd = gcd(computeX, computeY, computeS);
jTextField18.setText("= " + formatSign(computeX/gcd) + "x" + formatSign(computeY/gcd) + "y" + formatSign(computeS/gcd) + "= 0");
jTextField6.setText("= " + formatSign(10/gcd));
XYLineChart_AWT chart = new XYLineChart_AWT("Locus of Point Graph", "", array);
chart.pack();
RefineryUtilities.centerFrameOnScreen( chart );
chart.setVisible( true );
}catch(Exception e){
JOptionPane.showMessageDialog(null, "Please fill necessary inputs");
}
}
the error shows at my return gcd(gcd(a,b),c);
I want to get the GCD of 3 numbers and later on divide it to my variables. Is there any other way? Or is there a way to solve the error?
Thanks in advance!

Because gcd(...) takes 3 arguments
private static int gcd(int a, int b, int c) {
return gcd(gcd(a,b),c);
}
In return, you are passing only 2. Also, with the code you have shown, if you pass 3 params, it will be infinite recursion. Thanks to #eis for pointing that out. I forgot to mention it :)

Related

ThreadLocalRandom random integer not in range

I executed this bunch of code:
int newOrderLow = ThreadLocalRandom.current().nextInt(50, shipCapacity / 3);
int newOrderUp = ThreadLocalRandom.current().nextInt(newOrderLow, shipCapacity + 1); // not lower than lower value
int newOrderMid = ThreadLocalRandom.current().nextInt(newOrderLow, newOrderUp + 1); // in between
Log.d(TAG, "New Order: {" + newOrderLow + ", " + newOrderMid + ", " + newOrderUp + "}");
and started debugging it. For example, when I set shipCapacity as 600, I got these figures logged in my console:
New Order: {493, 772, 672}
One thing is that upper range is not within [lower value; shipCapacity + 1],
the other one is the middle value result. So what is the issue? How to generate random integers properly using ThreadLocalRandom?
You might want to consider running following test code:
#Test
public void test1() {
final int shipCapacity = 600;
for (int i = 0; i < 1000000; i++) {
int newOrderLow = ThreadLocalRandom.current().nextInt(50, shipCapacity / 3);
int newOrderUp = ThreadLocalRandom.current().nextInt(newOrderLow, shipCapacity + 1); // not lower than lower value
int newOrderMid = ThreadLocalRandom.current().nextInt(newOrderLow, newOrderUp + 1); // in between
System.out.println("numbers= " + newOrderLow + " " + newOrderUp + " " + newOrderMid);
assertThat(newOrderLow).isBetween(50, shipCapacity / 3);
assertThat(newOrderUp).isBetween(newOrderLow, shipCapacity + 1);
assertThat(newOrderMid).isBetween(newOrderLow, newOrderUp + 1);
}
I've done that and on my machine none of the rules that you mentioned seem to be violated.
In my opinion the problem is somewhere else, not in the code that you provided, but test it yourself.

logic error? diving 2 int that result in a float

I am writing a combat simulator. My attacker class initiates an attack and my defender class is supposed to block it. manager is my main class that computes and prints the results. My problem is with my highRatio, mediumRatio and lowRatio variables. If they are not equal to 1 all of them are set to zero. Any ideas as to what may be going?
//defender class
public int defenseSelector(int highAtkCounter, int mediumAtkCounter, int lowAtkCounter, int rounds, int roundCounter)
{
Random defenseTypeGenerator;
int defense = 0;
float highRatio;
float mediumRatio;
float lowRatio;
defenseTypeGenerator = new Random();
int defenseType = defenseTypeGenerator.nextInt(MAX_ROUNDS) + 1;
highRatio = highAtkCounter/roundCounter;
mediumRatio = mediumAtkCounter/roundCounter;
lowRatio = lowAtkCounter/roundCounter;
if(roundCounter > 3 && roundCounter <= rounds) //AI portion
{
if (highRatio > mediumRatio && highRatio > lowRatio)
{
defense = HIGH;
}
else if (mediumRatio > highRatio && mediumRatio > lowRatio)
{
defense = MEDIUM;
}
else if (lowRatio > highRatio && lowRatio > mediumRatio)
{
defense = LOW;
}
else
{
System.out.println("AI ERROR ratios " + highRatio + " " + mediumRatio + " " + lowRatio);
System.out.println("AI ERROR atkCounters " + highAtkCounter + " " + mediumAtkCounter + " " + lowAtkCounter);
System.out.println("AI ERROR rCounters " + roundCounter);
//manager class
while(roundCounter <= rounds)
{
int attack = theAttacker.attackSelector(high, medium, low);
int highAtkTracker = theAttacker.countHighAtks(attack);
System.out.println("DEBUG " + attack);
System.out.println("DEBUG " + highAtkTracker);
int mediumAtkTracker = theAttacker.countMediumAtks(attack);
System.out.println("DEBUG " + attack);
System.out.println("DEBUG " + mediumAtkTracker);
int lowAtkTracker = theAttacker.countLowAtks(attack);
System.out.println("DEBUG " + attack);
System.out.println("DEBUG " + lowAtkTracker);
highAtkCounter = highAtkCounter + highAtkTracker;
mediumAtkCounter = mediumAtkCounter + mediumAtkTracker;
lowAtkCounter = lowAtkCounter + lowAtkTracker;
int defense = theDefender.defenseSelector(highAtkCounter, mediumAtkCounter, lowAtkCounter, rounds, roundCounter);
In java any arithmetic operation with an integer results in an integer.
Therefore you must cast the integer into the floating point type explicitly:
highAtkCounter = highAtkCounter + (float)highAtkTracker;
mediumAtkCounter = mediumAtkCounter + (float)mediumAtkTracker;
lowAtkCounter = lowAtkCounter + (float)lowAtkTracker;

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

Method calculations wrong when used in JTable, but correct when printed out in console

I have a triangle program that I wrote as an assignment for my intro to JAVA class. Everything seems to work great, except that a) some of my numbers are showing up as squares in the table, and b) my getPerimeter() method that is being called in the table is not producing the same results as the same method called in a System.out.println; statement. Maybe the two problems stem from the same issue, I'm not sure.
Here is what I believe is the relevant code from my Triangle.java:
public String getAngleA()
{
double a = sideA;
double b = sideB;
double c = sideC;
angleA = Math.toDegrees(Math.acos((c*c + b*b - a*a) / (2 * b * c)));
return df.format(angleA);
}
public String getAngleB()
{
double a = sideA;
double b = sideB;
double c = sideC;
angleB = Math.toDegrees(Math.acos((a*a + c*c - b*b) / (2 * a* c)));
return df.format(angleB);
}
public String getAngleC()
{
angleC = 180 - (angleA + angleB);
return df.format(angleC);
}
public String getPerimeter()
{
perimeter = sideA + sideB + sideC;
return df.format(perimeter);
}
And, here is all the code from my TriangleTester.java, as I have no clue where the problem lies:
Scanner in = new Scanner(System.in);
System.out.println("Enter X coordinate for the first corner of the triangle: ");
int x1 = in.nextInt();
System.out.println("Enter Y coordinate for the first corner of the triangle: ");
int y1 = in.nextInt();
System.out.println("Enter X coordinate for the second corner of the triangle: ");
int x2 = in.nextInt();
System.out.println("Enter Y coordinate for the second corner of the triangle: ");
int y2 = in.nextInt();
System.out.println("Enter X coordinate for the third corner of the triangle: ");
int x3 = in.nextInt();
System.out.println("Enter Y coordinate for the third corner of the triangle: ");
int y3 = in.nextInt();
Triangle myTri = new Triangle(x1, y1, x2, y2, x3, y3);
JFrame frame = new JFrame();
String[] columnName = {"SIDES", "ANGLES", "PERIMETER", "AREA"};
Object[][] data = {
{"The length your triangle on side A is: " + myTri.getSideA(),
"Angle A = " + myTri.getAngleA() + "\u00b0",
"The perimeter of your triangle is: " + myTri.getPerimeter(),
"The area of your triangle is: " + myTri.getArea()},
{"The length your triangle on side B is: " + myTri.getSideB(),
"Angle B = " + myTri.getAngleB() + "\u00b0",
" ", " "},
{"The length your triangle on side C is: " + myTri.getSideC(),
" Angle C = " + myTri.getAngleC() + "\u00b0",
" ", " "},
};
JTable table = new JTable(data, columnName);
DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
centerRenderer.setHorizontalAlignment( JLabel.LEFT );
table.getColumnModel().getColumn(1).setCellRenderer(centerRenderer);
centerRenderer.setHorizontalAlignment( JLabel.CENTER );
table.getColumnModel().getColumn(2).setCellRenderer(centerRenderer);
table.getColumnModel().getColumn(3).setCellRenderer(centerRenderer);
frame.setSize(950,107);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Your Triangle");
frame.add(table.getTableHeader(),BorderLayout.PAGE_START);
frame.add(table);
System.out.println(myTri.getP1() + "\n" + myTri.getP2() + "\n" + myTri.getP3() + "\n");
System.out.println("The length of triangle on side A is: " + myTri.getSideA());
System.out.println("The length of triangle on side B is: " + myTri.getSideB());
System.out.println("The length of triangle on side C is: " + myTri.getSideC() + "\n");
System.out.println("Angle A is: " + myTri.getAngleA() + "\u00b0");
System.out.println("Angle B is: " + myTri.getAngleB() + "\u00b0");
System.out.println("Angle C is: " + myTri.getAngleC() + "\u00b0" + "\n");
System.out.println("Perimeter is: " + myTri.getPerimeter() +"\n");
System.out.println("Area is: " + myTri.getArea());
}
}
And lastly, here is a pic showing the table with the squares and the wrong perimeter output, and below that, you can see the console print out with the right numbers, so I know that my methods are correct.
My problem was that the getAngle() methods were being called in my table before the getSides() methods were being run, so there were no values for the getAngle() methods to use. The all worked in my command line print out because all the methods were being run in "order," so the getSides() methods had all run before I called the first getAngle() method. Here's the fixed relevant code:
double sideA = myTri.getSideA();
double sideB = myTri.getSideB();
double sideC = myTri.getSideC();
double angleA = myTri.getAngleA();
double angleB = myTri.getAngleB();
double angleC = myTri.getAngleC();
double perim = myTri.getPerimeter();
double area = myTri.getArea();
String[] columnName = {"SIDES", "ANGLES", "PERIMETER", "AREA"};
Object[][] data = {
{"Side A = " + df.format(sideA),
"Angle A = " + df.format(angleA) + "\u00b0",
"Perimeter = " + df.format(perim),
"Area = " + df.format(area)},
{"Side B = " + df.format(sideB),
"Angle B = " + df.format(angleB) + "\u00b0",
" ", " "},
{"Side C = " + df.format(sideC),
"Angle C = " + df.format(angleC) + "\u00b0",
" ", " "}
};
And, the reason I mixed command line output with a GUI output was because my GUI output wasn't working, and I needed a way to tell if my numbers were being calculated correctly. Clearly, I would not turn in or release a program that ran that way.

Cannot find symbol while loop

Hello I am creating an algorithm to take int x and convert it to the desired base being int y.
example 7 base 3 = 21.
void printXBaseY(int x, int y) {
boolean active = true;
while(x >= y) {
int a = x % y;
int b = x / y;
String first = "" + a;
String second = "" + b;
String answer = "" + first + second;
}
String answer = "" + first + second;
println(x + " base " + y + " is " + answer);
}
}
at String answer it has error cannot find symbol - variable first, can anyone explain why it cannot find it? and provide a solution.
thank you in advance
Those variable's are out of scope.
In java the scope is restricted to {}.
Just move them to top, so that they're available further.
void printXBaseY(int x, int y) {
boolean active = true;
String first=""; // or null
String second=""; // or null
while(x >= y) {
int a = x % y;
int b = x / y;
first = "" + a;
second = "" + b;
String answer = "" + first + second;
}
String answer = "" + first + second;
System.out.println(x + " base " + y + " is " + answer);
}
You might be a beginner :Read more about block and statements
It is out of scope. You declared it within the while loop. it is gone afterwards.
To solve this, declare first and second before the while loop starts.
The scope of variable "first" is bounded by while block. So it cannot be accessed outside it.
Your first and second variables are declared inside while loop. So the scope of them are inside while loop only you can not use them outside while loop.
void printXBaseY(int x, int y) {
boolean active = true;
String first = null;
String second = null
while(x >= y) {
int a = x % y;
int b = x / y;
first = "" + a;
second = "" + b;
String answer = "" + first + second;
}
String answer = "" + first + second;
println(x + " base " + y + " is " + answer);
}
while(x >= y) {
int a = x % y;
int b = x / y;
String first = "" + a; // here is the problem. You declared first and second within the while loop.
String second = "" + b;
String answer = "" + first + second;
}
Corrected code below
while(x >= y) {
int a = x % y;
int b = x / y;
String first = "" + a;
String second = "" + b;
String answer = "" + first + second;
String answer = "" + first + second;
println(x + " base " + y + " is " + answer);
}
Your variables first and second as well are declared inside your while loop, therefore its lifetime is bound within that loop.
If it is not clear for you what a scope is, you should read this interesting slide
http://classes.soe.ucsc.edu/cmps012a/Winter03-01/notes/Lecture27-4perpage.pdf
void printXBaseY(int x, int y) {
boolean active = true;
String first="";
String second="";
String answer="";
while(x >= y) {
int a = x % y;
int b = x / y;
first = "" + a;
second = "" + b;
// answer = "" + first + second;
}
answer = "" + first + second;
println(x + " base " + y + " is " + answer);
}

Categories

Resources