Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
I've learned to write code implementing the Diffie-Hellman key exchange algorithm below, but I feel that my code isn't at its most efficient. Can anyone correct my code please...?
import java.math.BigInteger;
import java.security.SecureRandom;
import java.security.spec.AlgorithmParameterSpec;
import java.util.Random;;
public class DH_key {
static class DHGenParameterSpec implements AlgorithmParameterSpec{
static BigInteger p;
static BigInteger g;
static int a,b;
static BigInteger A,B;
static BigInteger getPrimeP_G() {
Random rand1= new Random(System.currentTimeMillis());
Random rand2= new Random(System.currentTimeMillis()*10);
p= BigInteger.probablePrime(32, rand1);
g= BigInteger.probablePrime(32, rand2);
System.out.println(""+p+","+g);
return null;
}
static int getExponent() {
SecureRandom ranGen1 = new SecureRandom();
a= ranGen1.nextInt(1000);
b= ranGen1.nextInt(1000);
System.out.println(a+"__"+b);
return 0 ;
}
public static Object pow (){
//g.pow(a);
A = g.pow(getExponent()).mod(getPrimeP_G());
B = g.pow(b).mod(p);
return null;
}
public static void main(String[]args){
//System.out.println(DHGenParameterSpec.getPrimeP_G());
DHGenParameterSpec.getPrimeP_G();
DHGenParameterSpec.getExponent();
A = g.pow(a).mod(p);
B = g.pow(b).mod(p);
BigInteger Sa,Sb;
Sa=B.pow(a).mod(p);
Sb=A.pow(b).mod(p);
System.out.println(""+A+"__"+B);
System.out.println(""+Sa+"__"+Sb);
}
}
}
Was the code above appropriate with java rules??
You have written modular exponentiation as:
A = g.pow(getExponent()).mod(getPrimeP_G());
B = g.pow(b).mod(p);
This is inefficient because the intermediate result from the exponentiation can be a large number. You should use the modPow method instead, which does the two operations with an efficient algorithm:
A = g.modPow(getExponent(), getPrimeP_G());
B = g.modPow(b, p);
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am new to java, trying to learn by making mini projects right now. I have two classes and when I run my program I have this error : Cannot make a static reference to the non-static field Game.balance.
Not quite sure why I am getting it and wondering if anyone knows any fixes.
import java.util.Random;
import java.util.Scanner;
public class Mainone {
public static void main(String[] args) {
System.out.println("You have $1000. I hope you make good choices!");
Scanner user = new Scanner(System.in);
Game print = new Game(1000,0,0,true);
System.out.print(Game.operation);
}
}
this is the second class below (new file)
import java.util.Random;
public class Game {
int balance = 1000;
int operationAmount;
int randOperation;
boolean ad = true;
public Game(int b, int o, int r, boolean a) {
balance = b;
operationAmount = o;
randOperation = r;
ad = a;
}
}
System.out.print(Game.operation);
change to
System.out.print(print.operation);
In java, you can't access Object field values by Class directly. But you can access the static field by using Class.
public class Game {
public static String ABC = "1"; // can access by Game.ABC
int balance = 1000;
int operationAmount;
int randOperation;
boolean ad = true;
public Game(int b, int o, int r, boolean a) {
balance = b;
operationAmount = o;
randOperation = r;
ad = a;
}
}
public static void main(String[] args) {
System.out.println("You have $1000. I hope you make good choices!");
Scanner user = new Scanner(System.in);
Game print = new Game(1000,0,0,true);
System.out.print(Game.ABC); // here you can access the static field
}
you are trying to call Game.operation. Instead of this try print.operation.
I assume operation is function in class Game.
Here the state is managed by the print object of Game class.
Please call System.out.print(print.operation);
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I am getting this compilation issue, and I'm not able to figure out why. Can someone help?
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.getInt() ;
System.out.println(factorial(n)) ;
int factorial(int a){
if (a==0)
return 1;
else
return (a*factorial(a-1));
}}
Post Edit Note: I wasn't aware of the fact that another function can't be declared inside main(). On writing it outside, it worked fine.
You're trying to create a method called factorial inside your main method. It has to be next to it, not inside it.
Formatting your code readably and consistently helps make the problem clear:
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.getInt();
System.out.println(factorial(n));
int factorial(int a) { // <=== Problem
if (a == 0)
return 0;
else
return (a * factorial(a - 1));
}
}
}
Instead:
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.getInt();
System.out.println(factorial(n));
}
int factorial(int a) {
if (a == 0)
return 0;
else
return (a * factorial(a - 1));
}
}
The above still has a problem (factorial needs to be static, or you need to create an instance to call it on), but it's in the right place now.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Can you please help me to understand what I am doing wrong in this code:
package javaapplication19;
public class JavaApplication19 {
public static void main(String[] args) {
BigInteger bi1, bi2, bi3, bi4;
bi1 = new BigInteger(123456789);
bi2 = new BigInteger(0);
bi3 = new BigInteger(123456789);
bi4 = new BigInteger(0);
for (bi2 = BigInteger.valueOf(0);
bi2.compareTo(bi3) > 0;
bi2 = bi2.add(1)) {
if(bi4.compareTo(bi1) == 0) {
System.out.println("bulduk bulduk" + bi4);
}
else
{
bi4 = bi4.add(1);
}
}
}
}
This is the output:
Exception in thread "main" java.lang.UnsupportedOperationException:
Not supported yet. at
javaapplication19.BigInteger.(BigInteger.java:19) at
javaapplication19.JavaApplication19.main(JavaApplication19.java:19)
C:\Users\xxxxx\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53:
Java returned: 1 BUILD FAILED (total time: 0 seconds)
Thank you for your help
You seem to have your own custom BigInteger on the classpath throwing an UnsupportedOperationException. You could use the built-in version instead:
bi1 = new BigInteger("123456789");
According to your stack trace, it means that your class javaapplication19.BigInteger (not java.math.BigInteger) doesn't support a constructor with a int as parameter. Check your class javaapplication19.BigInteger and you will know.
You should have something like this:
class BigInteger {
...
BigInteger(int i) {
throw new UnsupportedOperationException("Not supported yet");
}
...
If you want to use java.math.BigInteger instead of javaapplication19.BigInteger, you will need to import it explicitly with import java.math.BigInteger; otherwise by default it will use the class BigInteger of your package javaapplication19.
Once you will use the correct BigInteger class, you will have to use BigInteger.valueOf(long) to create your instances and BigInteger.add(BigInteger) to add values as next:
public static void main(String[] args) throws Exception {
BigInteger bi1, bi2, bi3, bi4;
bi1 = BigInteger.valueOf(123456789L);
bi2 = BigInteger.valueOf(0L);
bi3 = BigInteger.valueOf(123456789L);
bi4 = BigInteger.valueOf(0L);
for (bi2 = BigInteger.valueOf(0L);
bi2.compareTo(bi3) > 0;
bi2 = bi2.add(BigInteger.ONE)) {
if(bi4.compareTo(bi1) == 0) {
System.out.println("bulduk bulduk" + bi4);
} else {
bi4 = bi4.add(BigInteger.ONE);
}
}
}
I don't see a BigInteger constructor that takes a single integer, or a single long.
constructor is worng. replace
bi1 = new BigInteger(123456789);
by
bi1 = BigInteger.valueOf(123456789L);
You need to study the class BigInteger in Java API.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I just accepted that all my programs I made have to start with this. Then I was looking at a example #2 here regarding generation of a random number.
import java.util.Random;
/** Generate random integers in a certain range. */
public final class RandomRange {
public static final void main(String... aArgs){
log("Generating random integers in the range 1..10.");
int START = 1;
int END = 10;
Random random = new Random();
for (int idx = 1; idx <= 10; ++idx){
showRandomInteger(START, END, random);
}
log("Done.");
}
private static void showRandomInteger(int aStart, int aEnd, Random aRandom){
if (aStart > aEnd) {
throw new IllegalArgumentException("Start cannot exceed End.");
}
//get the range, casting to long to avoid overflow problems
long range = (long)aEnd - (long)aStart + 1;
// compute a fraction of the range, 0 <= frac < range
long fraction = (long)(range * aRandom.nextDouble());
int randomNumber = (int)(fraction + aStart);
log("Generated : " + randomNumber);
}
private static void log(String aMessage){
System.out.println(aMessage);
}
}
I noticed that this had a public static void and a private static void. Why not just combine the code into one thing under public static void? More importantly, what do these mean? I did research and saw the word "class" pop up often. What is a class? I hope my question meets the guidelines, this is my first time posting here. Thanks.
I will assume you asked here because you wanted a concise answer that gives you some intuition, rather than a deep dive into OOP which you can pull from the tutorial.
A class is a template from which objects are built. However, until you understand OOP, the class is just a necessary wrapper around the imperative code you are writing because Java requires all code to live inside a class.
public means the method is publicly accessible. Methods which are defined in classes other than this one can access it. private has the opposite meaning.
static means that this is a class-level function that is not tied to any particular instance of the class.
void means the method returns nothing.
You can certainly put all the code under a single method, but that carries at least the following problems.
Code is harder to read because the intent of the code is hidden by the details of the implementation.
Code is harder to reuse because you have to copy and paste whenever you need the same functionality in multiple places.
The following is not fully correct, it is very simplified:
Mostly one class equals one file. Even so they can access each other (if in the same project/folder) Here are 3 example classes:
Class withe the main method:
package ooexample;
public class OOExample {
public static void main(String[] args) {
int min = 2;
int max = 101;
// use of static method
int randomNumberA = MyMath.generateRandomNumber(min, max);
// use of non static method
RandomNumberGenerator generator = new RandomNumberGenerator();
int randomNumberB = generator.randomNumber(min, max);
/**
* does not work, method is private, can not be accessed from an outise class
* only RandomNumberGenerator can access it
*/
// generator.printSomeNumber(123);
}
}
Class with a static method. The method can be access by writing classname.nameOfStaticMethod(...) see main method.
package ooexample;
public class MyMath {
public static int generateRandomNumber(int min, int max) {
return min + (int) (Math.random() * ((max - min) + 1));
}
}
Class without static method. You have to create the class in the main method, using the new operator and assign the created class to a variable. Then you can use the variable to access PUBLIC methods of that class. You can not access private methods anywhere else but inside of the class itself. See main method.
package ooexample;
public class RandomNumberGenerator {
public RandomNumberGenerator() {
}
public int randomNumber(int min, int max) {
int randomNumber = min + (int) (Math.random() * ((max - min) + 1));
printSomeNumber(randomNumber);
return randomNumber;
}
private void printSomeNumber(int number) {
System.out.println(number);
}
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I managed to get an error in just 3 lines of code:
import java.util.Random;
public class Test
{
private Random rnumber;
rnumber = new Random();
private int nmb = rnumber.nextInt(36);
}
The error is right after rnumber. I don't understand what is wrong.
If i change it to:
private Random rnumber = new Random();
private int nmb = rnumber.nextInt(36);
The error disappears, but when I add println:
private Random rnumber = new Random();
private int nmb = rnumber.nextInt(36);
System.out.println("" + nmb);
Same error comes back, but now right after println.
Put your code in some method, constructor or static initializer block, as required.
public class Test
{
public static void main (String[] args)
{
Random rnumber;
rnumber = new Random();
int nmb = rnumber.nextInt(36);
}
}
or
public class Test
{
private Random rnumber;
private int nmb;
public Test ()
{
rnumber = new Random();
nmb = rnumber.nextInt(36);
}
}
The only instructions you have the right to execute out of a block are declarations/initializations, that's why your code compiles when you remove some lines of code which are not declarations.
Put your logic in a method or a block and it will be fine.