I'm new to Java. The Following Code is to create a generic class to generate complex numbers from real and Imaginary Parts. The add() method in the class is throwing the following Error.
Not sure how to proceed further. I have been at this for a day. Error Prompt
import java.util.*;
class ComplexNum<T>{
T i;
T r;
public ComplexNum (T r , T i){
this.r = r;
this.i = i;
}
public ComplexNum add(ComplexNum c2)
{
return new ComplexNum (r + c2.r, i +c2.i);
}
#Override
public String toString() {
return this.r + " + " + this.i + "i";
}
}
class Main{
public static void main(String[] args) {
int n1 = 1;
int n2 = 3;
double d1 =4.4;
double d2 = 5.4;
ComplexNum<Integer> c1 = new ComplexNum<Integer>(n1, n2);
ComplexNum<Double> c2 = new ComplexNum<Double>(d1, d2);
ComplexNum<Double> c3 = c1.add(c2);
System.out.println(c1 + " + " + c2 + " = "+ c3) ;
}
}
static class ComplexNum<T extends Number> {
T i;
T r;
public ComplexNum(T r, T i) {
this.r = r;
this.i = i;
}
public ComplexNum<Double> add(ComplexNum c2) {
Double newr = r.doubleValue() + c2.r.doubleValue();
Double newi = i.doubleValue() + c2.i.doubleValue();
return new ComplexNum<>(newr, newi);
}
#Override
public String toString() {
return this.r + " + " + this.i + "i";
}
}
class Main {
public static void main(String[] args) {
int n1 = 1;
int n2 = 3;
double d1 = 4.4;
double d2 = 5.4;
ComplexNum<Integer> c1 = new ComplexNum<>(n1, n2);
ComplexNum<Double> c2 = new ComplexNum<>(d1, d2);
ComplexNum<Double> c3 = c1.add(c2);
System.out.println(c1 + " + " + c2 + " = " + c3);
}
}
Related
Assuming that the array is populated with 20 shipments, calculate the total cost of local shipments in the array.
I tried to create a for loop and then call out the method calcCost() and += it to the variable local so it would save the values I guess
I'm pretty sure the way I wrote the code is wrong so if someone could help me with it that would be great!
package question;
public class TestShipment {
public static void main(String[] args) {
Shipment r1 = new Shipment(
new Parcel("scientific calculator " , 250),
new Address("Dubai","05512345678"),
new Address("Dubai","0505432123"),
"Salim"
);
System.out.println(r1);
Shipment[] arr = new Shipment[100];
arr[5] = r1;
Shipment[] a = new Shipment[20];
double local = 0;
for (int i = 0; i < a.length; i++) {
if (a[i].isLocalShipment()) {
System.out.println(a[i].calcCost());
}
}
}
}
public class Shipment {
public Parcel item;
private Address fromAddress;
private Address toAddress;
public String senderName;
public Shipment(Parcel i, Address f, Address t, String name) {
item = i;
fromAddress = f;
toAddress = t;
senderName = name;
}
//setter
public void setFromAddress(String c, String p) {
c = fromAddress.getCity();
p = fromAddress.getPhone();
}
public boolean isLocalShipment() {
boolean v = false;
if (fromAddress.getCity() == toAddress.getCity()) {
v = true;
} else {
v = false;
}
return v;
}
public double calcCost() {
double cost = 0;
if (fromAddress.getCity() == toAddress.getCity()) {
cost = 5;
} else {
cost = 15;
}
if(item.weight > 0 && item.weight <= 200) {
cost += 5.5;
}
if(item.weight > 200) {
cost += 10.5;
}
return cost = cost * (1 + 0.5); //fix the tax
}
public String toString() {
return "From: " + senderName + "\nTo: " + toAddress
+ "\nParcel: " + item.desc+item.weight + "\ncost: " + calcCost();
}
}
I made an RSA Encrypt/Decrypt GUI program with JavaFX.
It seems works well with generating Public and Private keys, but somehow Decryption does not return the plain text I encrypted.
I dunno why this happens, maybe I am misunderstanding the RSA algorithm, so please find ANY problems my code has.
The text file Pnumlist contains the list of Prime numbers I copied from Wikipedia.
I set Private key as n, e and Public key as n, d.
As I know if we set Plain text as M and Crypted text as C, (integer).
C = M^e (mod n)
M = C^d (mod n)
Am I right?
public class Main extends Application {
static int[] arr = new int[120000];
private static int n;
private static int e;
private static int d;
private static int C;
private static int M;
private static int n1;
private static int n2;
private static void SWAPint(int a, int b) {
if(a < b) {
int tmp = a;
a = b;
b = tmp;
}
}
private static int getd() {
int D;
for(D = 1; D < n-1; D++) {
if((e * D) % (n - 1) == 1) {
break;
}
}
return D;
}
private static int GCDr(int a, int b) {
if(b == 0) {
return a;
} else {
return GCDr(b, a%b);
}
}
private static int getCoprime(int E) {
int j;
for(j = 2; j < E; j++) {
if(GCDr(E, j) == 1) {
break;
}
}
return j;
}
private static void keymaker() {
File f = new File("Pnumlist.txt");
try {
Scanner scan = new Scanner(f);
int i = 0;
while(scan.hasNext()) {
arr[i] = scan.nextInt();
i++;
}
int Pnum[] = new int[i];
for(int j = 0; j < Pnum.length; j++) {
Pnum[j] = arr[j];
}
Random slct = new Random();
n1 = Pnum[slct.nextInt(Pnum.length)];
n2 = Pnum[slct.nextInt(Pnum.length)];
SWAPint(n1, n2);
n = n1 * n2;
int Onum = (n1 - 1) * (n2 - 1);
e = getCoprime(Onum);
d = getd();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
#Override
public void start(Stage primaryStage) {
try {
// some javafx stuff...
Encrypt.setOnAction(rct -> {
String tmpP = Ptext.getText();
console.appendText("Input Integer: " + tmpP + "\n");
console.appendText("--------Process--------" + "\n");
M = Integer.parseInt(tmpP);
keymaker();
console.appendText("generated primes: " + n1 + ", " + n2 + "\n");
console.appendText("Calculated key n: " + n + "\n");
console.appendText("Calculated key e: " + e + "\n");
console.appendText("Calculated key d: " + d + "\n");
C = (int) Math.pow(M, e) % n;
console.appendText("--------Crypted Integer--------" + "\n");
console.appendText(Integer.toString(C));
});
Decrypt.setOnAction(rct -> {
String tmpP = Ctext.getText();
console.appendText("\n\nInput Integer: " + tmpP + "\n");
console.appendText("--------Process--------" + "\n");
console.appendText("--------Decrypted Integer--------" + "\n");
int cusM = (int) Math.pow(C, d) % n;
console.appendText(Integer.toString(cusM));
});
// some more javafx stuff...
} catch(Exception e) {
e.printStackTrace();
}
}
// some other javafx methods...
}
so im super stuck.. im doing my toString() method and it needs to show a bar graph with stars that correlate with the number of grades. ex.
how it should look if 5 As, 3 Bs, 3 Cs, 2 Ds, 1 F,
*****A
***B
***C
**D
*F
my teacher gave me a start, but i have no idea what to do besides concatenating the single variable thats been given. keep in mind I'm learning still and haven't learned the other ways such as string building or arrays
public class GradeDistribution {
private int mNumberAs;
private int mNumberBs;
private int mNumberCs;
private int mNumberDs;
private int mNumberFs;
public GradeDistribution(int numberOfAs, int numberOfBs,
int numberOfCs, int numberOfDs,
int numberOfFs)
{
mNumberAs = numberOfAs;
mNumberBs = numberOfBs;
mNumberCs = numberOfCs;
mNumberDs = numberOfDs;
mNumberFs = numberOfFs;
}
public GradeDistribution()
{
mNumberAs = 0;
mNumberBs = 0;
mNumberCs = 0;
mNumberDs = 0;
mNumberFs = 0;
}
public void setAllGrades(int A,int B, int C, int D, int F)
{
mNumberAs = A;
mNumberBs = B;
mNumberCs = C;
mNumberDs = D;
mNumberFs = F;
}
public void setNumberAs( int A)
{
mNumberAs = A;
}
public void setNumberBs(int B)
{
mNumberBs = B;
}
public void setNumberCs(int C)
{
mNumberCs = C;
}
public void setNumberDs(int D)
{
mNumberDs = D;
}
public void setNumberFs(int F)
{
mNumberFs = F;
}
public int getNumberOfGrades()
{
return mNumberAs + mNumberBs + mNumberCs + mNumberDs + mNumberFs;
}
public int getPercentAs()
{ double totalGrade = mNumberAs + mNumberBs + mNumberCs + mNumberDs + mNumberFs;
double averageAs = (mNumberAs / totalGrade * 100);
return (int)averageAs;
}
public int getPercentBs()
{
double totalGrade = mNumberAs + mNumberBs + mNumberCs + mNumberDs + mNumberFs;
double averageBs = (mNumberBs / totalGrade * 100);
return (int)averageBs;
}
public int getPercentCs()
{
double totalGrade = mNumberAs + mNumberBs + mNumberCs + mNumberDs + mNumberFs;
double averageCs = (mNumberCs / totalGrade * 100);
return (int) averageCs;
}
public int getPercentDs()
{
double totalGrade = mNumberAs + mNumberBs + mNumberCs + mNumberDs + mNumberFs;
double averageDs = (mNumberDs / totalGrade * 100);
return (int) averageDs;
}
public int getPercentFs()
{
double totalGrade = mNumberAs + mNumberBs + mNumberCs + mNumberDs + mNumberFs;
double averageFs = (mNumberFs / totalGrade * 100);
return (int)averageFs;
}
public String toString()
{
String output = "";
for(int a = 1; a <= mNumberAs; a++)
{
}
}
}
In your for loop you are iterating over the number of As that were given. So you can append * to your string as you iterate. output = output + "*"; When the loop is done, append an A and a new line \n, and then do the same for Bs, Cs, etc:
String output = "";
for(int a = 1; a <= mNumberAs; a++) {
output = output + "*";
}
output = output + "A\n";
// do the same for the number of Bs, Cs, etc
I am confused on the output of the code. I want to know for each call on variables i and s, which class is used to call the variables. The question involves variable shadowing. Also I want to know how s keeps on changing throughout the lines in the main method.
public class A {
public int i = 0;
public static String s = "";
public A(int i) {
System.out.println(i);
s += "x";
}
public A debug() {
if (this instanceof B) {
System.out.println("Spam");
s += "s";
}
return this;
}
}
public class B extends A {
public int i = 100;
public static String s = "s";
public B(int i, String s) {
super(i);
this.i += 5;
this.s = s;
}
public static void main(String[] argv) {
String s = "";
B b = new B(0, s);
System.out.println(b.i + " " + b.s);
s += "foo";
A a = new B(42, s);
System.out.println(a.i + " " + a.s);
System.out.println(b.debug().s + " " + b.i + " " + b.s);
System.out.println(a.debug().s + " " + a.i + " " + a.s);
}
}
Here is the output of that code:
0
105
42
0 xx
Spam
xxs 105 foo
Spam
xxss 0 xxss
public class A {
public int i = 0; //not changed, because it is not overrided
public static String s = "";
public A(int i) {
System.out.println(i); //1. 0, 3. 42
s += "x"; //After second run s="xx", because it is static
}
public A debug() {
if (this instanceof B) {
System.out.println("Spam"); //5, 7. Spam
s += "s"; //s = "xxs", than "xxss" because it is static
}
return this;
}
}
public class B extends A {
public int i = 100;
public static String s = "s";
public B(int i, String s) {
super(i);
this.i += 5; //First run: i=105, Second run: i=47
this.s = s; //First run: public static String s="", Second run: public static String a.s="foo"
}
public static void main(String[] argv) {
String s = "";
B b = new B(0, s);
System.out.println(b.i + " " + b.s); //2. 105
s += "foo"; //B.s is now foo
A a = new B(42, s);
System.out.println(a.i + " " + a.s); //3. 0 xx
System.out.println(b.debug().s + " " + b.i + " " + b.s); //1. because of (A)b.s = xxs, 2. b.i = 105, 3. b.s = foo
System.out.println(a.debug().s + " " + a.i + " " + a.s); //(A)a.s = "xxss", (A)a.i = 0, (A)a.s = "xxss"
}
}
I have written a program to solve Diophantine equations in the form
A5 + B5 + C5 + D5 + E5 = 0;
It should run in N3long(N) time, but it usually takes about 10 minutes for an input size of 100. Can anyone tell me whats wrong?
public class EquationSolver {
//Solves Equations of type: A^5 + B^5 + C^5 + D^5 + E^5 = F^5
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a max value: ");
int N = input.nextInt();
long START_TIME = System.nanoTime();
SLinkedList test = new SLinkedList();
SLinkedList test2 = new SLinkedList();
test = setupLeftList(N);
test2 = setupRightList(N);
System.out.println("Note: This program takes about 7 minutes to complete for input of 100");
test = mergeSort(test);
test2 = mergeSort(test2);
long END_TIME2 = System.nanoTime() - START_TIME;
System.out.println("Total Time:" + END_TIME2/1000000000.0);
checkEquality(test, test2);
long END_TIME3 = System.nanoTime() - START_TIME;
System.out.println("Total Time:" + END_TIME3/1000000000.0);
}
public static SLinkedList setupLeftList(long boundary)
{
//Creates and returns an linkedList of all possible A,B,C values and their sums
SLinkedList leftSums = new SLinkedList();
for(long c = 0; c < boundary; c++)
{
for(long b = 0; b < c; b++)
{
for(long a = 0; a < b; a++)
{
long sum = (long)(Math.pow(a+1,5)) + (long)(Math.pow(b+1, 5)) + (int)(Math.pow(c+1, 5));
Node current = new Node (sum, a+1, b+1, c+1, null);
//System.out.println(sum);
leftSums.addLast(current);
}
}
}
return leftSums;
}
public static SLinkedList setupRightList(long boundary)
{
//Creates and returns an linkedList of all possible D,E,F values and their sums
SLinkedList rightSums = new SLinkedList();
for(int f = 0; f < boundary; f++)
{
for(int e = 0; e < f; e++)
{
for(int d = 0; d < e; d++)
{
long sum = (long)(Math.pow(f+1, 5)) - ((long)(Math.pow(d+1, 5)) + (long)(Math.pow(e+1,5)));
Node current = new Node (sum, d+1, e+1, f+1, null);
//System.out.println(current.getSum());
rightSums.addLast(current);
}
}
}
return rightSums;
}
public static SLinkedList mergeSort(SLinkedList sums)
// Sorts each list by the value of the sum
{
if (sums.length() > 1 )
{
SLinkedList[] splitList = split(sums);
SLinkedList s1 = mergeSort(splitList[0]);
SLinkedList s2 = mergeSort(splitList[1]);
sums = merge(s1, s2);
}
return sums;
}
public static SLinkedList[] split(SLinkedList sums)
{
// Splits a linked list into two (somewhat) equal halves
long midpoint = sums.length()/2;
Node midPoint = sums.elementAt(midpoint);
SLinkedList s1 = new SLinkedList(sums.head, midPoint, midpoint);
SLinkedList s2 = new SLinkedList(midPoint, sums.tail, midpoint);
SLinkedList[] both = new SLinkedList[]{s1, s2};
return both;
}
public static SLinkedList merge(SLinkedList s1, SLinkedList s2)
{
// Merges two sorted lists of elements
SLinkedList sMerged = new SLinkedList();
while(!s1.isEmpty() && !s2.isEmpty())
{
if (s1.getFirst().getSum() < s2.getFirst().getSum())
{
sMerged.addLast(s1.removeFirst());
}
else
{
sMerged.addLast(s2.removeFirst());
}
}
while(!s1.isEmpty())
{
sMerged.addLast(s1.removeFirst());
}
while(!s2.isEmpty())
{
sMerged.addLast(s2.removeFirst());
}
return sMerged;
}
public static void checkEquality(SLinkedList left, SLinkedList right)
{
// Checks two linked lists for nodes that contain the same Sum value
boolean ans = false;
while (left.isEmpty() == false && right.isEmpty() == false)
{
long currentLeft = left.getFirst().getSum();
long currentRight = right.getFirst().getSum();
if (currentLeft > currentRight)
{
right.removeFirst();
}
else if(currentLeft < currentRight)
{
left.removeFirst();
}
else
{
if (left.getFirst().getC() <= right.getFirst().getA())
{
System.out.println("Answer Found: " + "A: " + left.getFirst().getA() + " B: " + left.getFirst().getB() + " C: "
+ left.getFirst().getC() + " D: " + right.getFirst().getA() + " E: " + right.getFirst().getB() + " F: " + right.getFirst().getC());
ans = true;
}
Node temp = left.getFirst().getNext();
while (temp.getSum() == currentRight)
{
if (temp.getC() <= right.getFirst().getA())
{
System.out.println("Answer Found: " + "A: " + left.getFirst().getA() + " B: " + left.getFirst().getB() + " C: "
+ left.getFirst().getC() + " D: " + right.getFirst().getA() + " E: " + right.getFirst().getB() + " F: " + right.getFirst().getC());
ans = true;
}
temp = temp.getNext();
}
right.removeFirst();
left.removeFirst();
}
}
if (ans == false)
{
System.out.println("No answer found.");
}
}
}
The definitive answer is: use a profiler and see what causes a bottleneck...
But I see you have Math.pow() calls, all with longs, and their 5th power.
You could do it quicker, while even detecting the overflow:
public static long pow5(long base) {
if(base <=6208 && base >=-6208) {
return base*base*base*base*base;
} else {
throw new IllegalArgumentException("Overflow!");
}
}
(Magic number disclaimer: 62085 is ~263, is a number is bigger than that, the 5th power won't fit into 64 bits...)
Math.pow uses doubles, which means a lot of conversion in itself...
Also, #Floris pointed out that it is not even worth computing this over and over again - it could be put into a nice array, and just index that
public static long[] pow5 = getPow5(100);
public static long[] getPow5(long numElements) {
long[] toReturn = new long[numElements];
for(long i=0;long<numElements;long++) {
toReturn[i] = i*i*i*i*i;
}
return toReturn;
}
And where needed, instead of Math.pow(x, 5) just use pow5[x]