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);
}
}
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...
}
I am having trouble getting my java code to properly output the required results. Not to mention that my System.out.Println isn't prompting for input. All my code is good with no errors. However it just doesn't seem to output anything or request an input.
//Author Adam Duffy
package test1;
import java.util.Scanner;
public class Employee {
public static void main(String [ ] args){}
public String DEF_EMP_NUM = "NO_EMP_NUM";
public double DEF_RATE_PER_HOUR = 20.0;
public double DEF_OVER_TIME_RATE = 40.0;
public double DEF_RATE_HOURS_PER_WEEK = 1.5;
private String empNum;
private double ratePerHour;
private double baseHrsPerWeek;
private double overTimeRate;
// no arg constructor setting width and length to default of 1
public Employee() {
empNum = DEF_EMP_NUM;
ratePerHour = DEF_RATE_PER_HOUR;
baseHrsPerWeek = DEF_RATE_HOURS_PER_WEEK;
overTimeRate = DEF_OVER_TIME_RATE;
}
// all arg constructor
public Employee(String empNum, float ratePerHour, float baseHrsPerWeek, int overTimeRate) {
this.empNum = empNum;
this.ratePerHour = ratePerHour;
this.baseHrsPerWeek = baseHrsPerWeek;
this.overTimeRate = overTimeRate;
}
//setters
public void setempNum(String empNum) {
this.empNum = empNum;
}
public String getempNum() {
return this.empNum;
}
//methods
public double getratePerHour() {
return ratePerHour;
}
public void setratePerHour(float ratePerHour) {
this.ratePerHour = ratePerHour;
}
public double getoverTimeRate() {
return overTimeRate;
}
public int setoverTimeRate(int overTimeRate) {
this.overTimeRate = overTimeRate;
return overTimeRate;
}
public double getbaseHrsPerWeek() {
return baseHrsPerWeek;
}
public void setbaseHrsPerWeek(float baseHrsPerWeek) {
this.baseHrsPerWeek = baseHrsPerWeek;
}
#Override
public String toString() {
return super.toString()
+ "\n["
+ "\nbaseHrsPerWeek = " + baseHrsPerWeek
+ "\noverTimeRate = " + overTimeRate
+ "\nratePerHour = " + ratePerHour
+ "\nempNum = " + empNum
+ "\n]";
}
public double calcWeeksPay(int hours) {
return this.ratePerHour * this.baseHrsPerWeek;
/*#param hours
#return
*/
}
{
Scanner scan = new Scanner(System.in);
int myNum[] = new int[5];
int i;
int sum = 0;
for (i = 0; i < myNum.length; i++) {
System.out.print("Enter the number " + (i + 1) + " : ");
myNum[i] = scan.nextInt();
}
for (i = 0; i < myNum.length; i++) {
System.out.print("The number " + (i + 1) + " : ");
System.out.print(myNum[i] + "\n+");
for (int e = 1; e <= i; e++) {
sum = sum + e;
}
System.out.println(sum);
}
}
}
I just can't seem to get it to work. I'm sure I'm missing something obvious. If I could get some advice, I would be very appreciative.
Updated peice of code , which will accept and print the number on console.
public class Employee {
public static void main(String [ ] args){
Scanner scan = new Scanner(System.in);
int myNum[] = new int[5];
int i;
int sum = 0;
for (i = 0; i < myNum.length; i++) {
System.out.print("Enter the number " + (i + 1) + " : ");
myNum[i] = scan.nextInt();
}
for (i = 0; i < myNum.length; i++) {
System.out.print("The number " + (i + 1) + " : ");
System.out.print(myNum[i] + "\n+");
for (int e = 1; e <= i; e++) {
sum = sum + e;
}
System.out.println(sum);
}
}
public String DEF_EMP_NUM = "NO_EMP_NUM";
public double DEF_RATE_PER_HOUR = 20.0;
public double DEF_OVER_TIME_RATE = 40.0;
public double DEF_RATE_HOURS_PER_WEEK = 1.5;
private String empNum;
private double ratePerHour;
private double baseHrsPerWeek;
private double overTimeRate;
// no arg constructor setting width and length to default of 1
public Employee() {
empNum = DEF_EMP_NUM;
ratePerHour = DEF_RATE_PER_HOUR;
baseHrsPerWeek = DEF_RATE_HOURS_PER_WEEK;
overTimeRate = DEF_OVER_TIME_RATE;
}
// all arg constructor
public Employee(String empNum, float ratePerHour, float baseHrsPerWeek, int overTimeRate) {
this.empNum = empNum;
this.ratePerHour = ratePerHour;
this.baseHrsPerWeek = baseHrsPerWeek;
this.overTimeRate = overTimeRate;
}
//setters
public void setempNum(String empNum) {
this.empNum = empNum;
}
public String getempNum() {
return this.empNum;
}
//methods
public double getratePerHour() {
return ratePerHour;
}
public void setratePerHour(float ratePerHour) {
this.ratePerHour = ratePerHour;
}
public double getoverTimeRate() {
return overTimeRate;
}
public int setoverTimeRate(int overTimeRate) {
this.overTimeRate = overTimeRate;
return overTimeRate;
}
public double getbaseHrsPerWeek() {
return baseHrsPerWeek;
}
public void setbaseHrsPerWeek(float baseHrsPerWeek) {
this.baseHrsPerWeek = baseHrsPerWeek;
}
#Override
public String toString() {
return super.toString()
+ "\n["
+ "\nbaseHrsPerWeek = " + baseHrsPerWeek
+ "\noverTimeRate = " + overTimeRate
+ "\nratePerHour = " + ratePerHour
+ "\nempNum = " + empNum
+ "\n]";
}
public double calcWeeksPay(int hours) {
return this.ratePerHour * this.baseHrsPerWeek;
/*#param hours
#return
*/
}
}
Problem was that you were not having anything in the psvm method and below piece of code
Scanner scan = new Scanner(System.in);
int myNum[] = new int[5];
int i;
int sum = 0;
for (i = 0; i < myNum.length; i++) {
System.out.print("Enter the number " + (i + 1) + " : ");
myNum[i] = scan.nextInt();
}
for (i = 0; i < myNum.length; i++) {
System.out.print("The number " + (i + 1) + " : ");
System.out.print(myNum[i] + "\n+");
for (int e = 1; e <= i; e++) {
sum = sum + e;
}
System.out.println(sum);
}
Which takes the input and print it on console was not having any calling code. it was just a inside the block of code. i just moved it inside the main method and it worked.
I am creating a program that automates creation of player characters. Below is my PlayerCharacter class. I have noticed that I repeat many operations on different variables.
public class PlayerCharacter {
int strength, dexterity, constitution, intelligence, wisdom, charisma;
int[] strRolls, dexRolls, conRolls, intRolls, wisRolls, charRolls;
public void generateAbilityScoresMethod1() {
strRolls = new int[3];
dexRolls = new int[3];
conRolls = new int[3];
intRolls = new int[3];
wisRolls = new int[3];
charRolls = new int[3];
for(int i = 0; i < 3; i++) {
strRolls[i] = dice.Dice.D6.getNewRoll();
strength += strRolls[i];
dexRolls[i] = dice.Dice.D6.getNewRoll();
dexterity += dexRolls[i];
conRolls[i] = dice.Dice.D6.getNewRoll();
constitution += conRolls[i];
intRolls[i] = dice.Dice.D6.getNewRoll();
intelligence += intRolls[i];
wisRolls[i] = dice.Dice.D6.getNewRoll();
wisdom += wisRolls[i];
charRolls[i] = dice.Dice.D6.getNewRoll();
charisma += charRolls[i];
}
}
public int getStrength() {
return strength;
}
public void printStrRolls() {
System.out.println("Str: roll 1 = " + strRolls[0]);
System.out.println("Str: roll 2 = " + strRolls[1]);
System.out.println("Str: roll 3 = " + strRolls[2]);
}
public int getDexterity() {
return dexterity;
}
public void printDexRolls() {
System.out.println("Dex: roll 1 = " + dexRolls[0]);
System.out.println("Dex: roll 2 = " + dexRolls[1]);
System.out.println("Dex: roll 3 = " + dexRolls[2]);
}
public int getConsitution() {
return constitution;
}
public void printConRolls() {
System.out.println("Con: roll 1 = " + conRolls[0]);
System.out.println("Con: roll 2 = " + conRolls[1]);
System.out.println("Con: roll 3 = " + conRolls[2]);
}
public int getIntelligence() {
return intelligence;
}
public void printIntRolls() {
System.out.println("Int: roll 1 = " + intRolls[0]);
System.out.println("Int: roll 2 = " + intRolls[1]);
System.out.println("Int: roll 3 = " + intRolls[2]);
}
public int getWisdom() {
return wisdom;
}
public void printWisRolls() {
System.out.println("Wis: roll 1 = " + wisRolls[0]);
System.out.println("Wis: roll 2 = " + wisRolls[1]);
System.out.println("Wis: roll 3 = " + wisRolls[2]);
}
public int getCharisma() {
return charisma;
}
public void printCharRolls() {
System.out.println("Char: roll 1 = " + charRolls[0]);
System.out.println("Char: roll 2 = " + charRolls[1]);
System.out.println("Char: roll 3 = " + charRolls[2]);
}
public void printAbilities() {
System.out.println("Str = " + getStrength());
System.out.println("Dex = " + getDexterity());
System.out.println("Con = " + getConsitution());
System.out.println("Int = " + getIntelligence());
System.out.println("Wis = " + getWisdom());
System.out.println("Char = " + getCharisma());
}
}
How can I accomplish the same tasks in a more efficient way?
You may declare a class Ability and make strength, dexterity, ... instances thereof. The following snippet might be a start:
class Ability {
private final int[] rolls;
private int value;
public Ability(int dice) {
rolls = new int[dice];
}
public int roll() {
value = 0;
for (int i = 0; i < rolls.length; i++) {
rolls[i] = dice.Dice.D6.getNewRoll();
value += rolls[i];
}
return value;
}
public int getValue() {
return value;
}
public void printRolls() {
// ... tbd ...
}
}
You can the use the abilities like ...
Ability strength;
strength = new Ability(3);
strength.roll(); // get new value
System.out.println(strength.getValue()); // e.g. print
strength.printRolls(); // e.g. print rolls
How about this:
public void printRolls( String label, int[] rolls) {
System.out.println(label + ": roll 1 = " + rolls[0]);
System.out.println(label + ": roll 2 = " + rolls[1]);
System.out.println(label + ": roll 3 = " + rolls[2]);
}
You can cut down repeated code line this
enum Attribute {
Str, Con, Dex, Int, Wis, Cha
}
class PlayerCharacter {
static final Random rand = new Random();
static final Attribute[] ATTRS = Attributes.values();
final int[] attr = new int[ATTRS.length];
PlayerCharacter() {
for(int i = 0; i < attr.length; i++)
attr[i] = rand.nextInt(6) + rand.nextInt(6) + rand.nextInt(6) + 3;
}
public int getAttr(Attribute attr) {
return attrs[attr.ordinal()];
}
public void printAbilities() {
for(int i = 0; i < ATTRS.length; i++)
System.out.println(ATTRS[i]+ " = " + attrs[i]);
}
Note: you may want any other attributes like HP, AC, Max HP, Level, XP, etc.
The only thing I would do there is to create a static dice rolling method which returns the array you need, so you can generate dice roll arrays for any type of dice:
public static int[] roll(int numberOfDice, int sidesOnEachDie) {
int[] result = new int[numberOfDice];
for(int i = 0; i < numberOfDice; ++i) {
result[i] = 1 + (int) Math.floor(Math.random() *
(double) sidesOnEachDie);
}
return result;
}
Then you can call, for example:
intRolls = roll(3, 6);
which will give the result of rolling 3D6 in an int array.
You could keep all your properties in an int[]. So rather than having strength, dexterity, constitution, intelligence, wisdom, charisma as separate variables have one
int[] characteristics;
then 0 would be strength; 1 would be dexterity and so on.
To keep the roll values you would need a int[][].
This is less code; it is not "more efficient" in CPU use or memory use, but makes the code shorter to write and read. I assume dice rolls are random regardless of their order.
package example;
public class PlayerCharacter
{
int strength, dexterity, constitution, intelligence, wisdom, charisma;
int[] strRolls, dexRolls, conRolls, intRolls, wisRolls, charRolls;
private int getScore(Dice d, int[] storage)
{
for (int i=0; i<storage.length; i++)
{
storage[i] = d.getNewRoll();
}
int result = 0;
for (int i=0; i<storage.length; i++) { result += storage[i]; }
}
public void generateAbilityScoresMethod1()
{
strRolls = new int[3];
dexRolls = new int[3];
conRolls = new int[3];
intRolls = new int[3];
wisRolls = new int[3];
charRolls = new int[3];
for (int i = 0; i < 3; i++)
{
strength = getScore(dice.Dice.D6, strRolls);
dexterity = getScore(dice.Dice.D6, dexRolls);
constitution = getScore(dice.Dice.D6, conRolls);
intelligence = getScore(dice.Dice.D6, intRolls);
wisdom = getScore(dice.Dice.D6, wisRolls);
charisma = getScore(dice.Dice.D6, charRolls);
}
}
public int getStrength()
{
return strength;
}
private void printArrayRolls(String label, int[] rolls)
{
for (int i=0; i < rolls.length; i++)
{
System.out.println(label + ": roll " + rolls[i]);
}
}
public void printStrRolls()
{
printArrayRolls("Str", strRolls);
}
public int getDexterity()
{
return dexterity;
}
public void printDexRolls()
{
printArrayRolls("Dex", dexRolls);
}
public int getConsitution()
{
return constitution;
}
public void printConRolls()
{
printArrayRolls("Con", conRolls);
}
public int getIntelligence()
{
return intelligence;
}
public void printIntRolls()
{
printArrayRolls("Int", intRolls);
}
public int getWisdom()
{
return wisdom;
}
public void printWisRolls()
{
printArrayRolls("Wis", wisRolls);
}
public int getCharisma()
{
return charisma;
}
public void printCharRolls()
{
printArrayRolls("Char", charRolls);
}
public void printAbilities()
{
System.out.println("Str = " + getStrength());
System.out.println("Dex = " + getDexterity());
System.out.println("Con = " + getConsitution());
System.out.println("Int = " + getIntelligence());
System.out.println("Wis = " + getWisdom());
System.out.println("Char = " + getCharisma());
}
}
This is less code; it is not "efficient" in CPU use or memory use, but makes the code shorter to write and read. I assume dice rolls are random regardless of their order.
package example;
public class PlayerCharacter
{
int strength, dexterity, constitution, intelligence, wisdom, charisma;
int[] strRolls, dexRolls, conRolls, intRolls, wisRolls, charRolls;
private int getScore(Dice d, int[] storage)
{
for (int i=0; i<storage.length; i++)
{
storage[i] = d.getNewRoll();
}
int result = 0;
for (int i=0; i<storage.length; i++) { result += storage[i]; }
}
public void generateAbilityScoresMethod1()
{
strRolls = new int[3];
dexRolls = new int[3];
conRolls = new int[3];
intRolls = new int[3];
wisRolls = new int[3];
charRolls = new int[3];
for (int i = 0; i < 3; i++)
{
strength = getScore(dice.Dice.D6, strRolls);
dexterity = getScore(dice.Dice.D6, dexRolls);
constitution = getScore(dice.Dice.D6, conRolls);
intelligence = getScore(dice.Dice.D6, intRolls);
wisdom = getScore(dice.Dice.D6, wisRolls);
charisma = getScore(dice.Dice.D6, charRolls);
}
}
public int getStrength()
{
return strength;
}
private void printArrayRolls(String label, int[] rolls)
{
for (int i=0; i < rolls.length; i++)
{
System.out.println(label + ": roll " + rolls[i]);
}
}
public void printStrRolls()
{
printArrayRolls("Str", strRolls);
}
public int getDexterity()
{
return dexterity;
}
public void printDexRolls()
{
printArrayRolls("Dex", dexRolls);
}
public int getConsitution()
{
return constitution;
}
public void printConRolls()
{
printArrayRolls("Con", conRolls);
}
public int getIntelligence()
{
return intelligence;
}
public void printIntRolls()
{
printArrayRolls("Int", intRolls);
}
public int getWisdom()
{
return wisdom;
}
public void printWisRolls()
{
printArrayRolls("Wis", wisRolls);
}
public int getCharisma()
{
return charisma;
}
public void printCharRolls()
{
printArrayRolls("Char", charRolls);
}
public void printAbilities()
{
System.out.println("Str = " + getStrength());
System.out.println("Dex = " + getDexterity());
System.out.println("Con = " + getConsitution());
System.out.println("Int = " + getIntelligence());
System.out.println("Wis = " + getWisdom());
System.out.println("Char = " + getCharisma());
}
}