Java BigInteger Comparison [closed] - java

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.

Related

How to get Integer#parseInt to return a value in case of overload [duplicate]

This question already has answers here:
How can I parse String to int with the default value? [duplicate]
(8 answers)
Good way to encapsulate Integer.parseInt()
(27 answers)
Closed 3 years ago.
Trying to run something like below will throw a NumberFormatException:
int i = Integer.parseInt("99999999999999999999999999999999999");
I want this to return Integer.MAX_VALUE instead such that:
int i = foobar("99999999999999999999999999999");
assert(i == Integer.MAX_VALUE);
What is the best way to accomplish this?
You could use BigInteger
BigInteger bi = new BigInteger("99999999999999999999999999");
BigInteger mv = new BigInteger(String.valueOf(Integer.MAX_VALUE));
System.out.println(bi.compareTo(mv));
if (bi.compareTo(mv) > 0)
return Integer.MAX_VALUE;
else
return bi.intValue();
You can try to parse the number using Integer.parseInt, if it fails, you try to parse it using Long.parseLong. Then you have two ways, if it fails, you try to parse using new BigInteger(stringVal), if it succeeds, you return MAX_INT.
Then do the same using BigInteger.
You can't just return max_int if you got a NumberFormatException after attempting to parse it using Integer.parseInt because this exception can be thrown if the text is not a number (or contain characters with numbers).
import java.util.regex.Pattern;
public class ForExample {
public static void main(String[] args) {
var strInt = "99999999999999999999999999999999999";
//
//
int i = parseToInt(strInt);
//
//
System.out.println(i == Integer.MAX_VALUE);
}
private static final Pattern PLUS_MINUS_ONLY_DIGITS = Pattern.compile("[+-]?\\d+");
public static int parseToInt(String strInt) {
try {
return Integer.parseInt(strInt);
} catch (NumberFormatException e) {
if (PLUS_MINUS_ONLY_DIGITS.matcher(strInt).matches()) {
return strInt.startsWith("-") ? Integer.MIN_VALUE : Integer.MAX_VALUE;
}
throw e;
}
}
}

NullPointerException with an ArrayList inside of a HashMap [closed]

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 8 years ago.
Improve this question
I am attempting to use an arraylist inside of a hashmap to create and iterate counters for different characters fed to the processLine method. I think I have declared all of the variables and the catch statements should handle the cases in which there isn't an entry in the hashmap, but I am still getting a NullPointerException on the curCounts.set(i, 1); line in the second catch statement. I've probably made some dumb mistake, but I can't figure out what it is.
HashMap<Character, ArrayList<Integer>> charCounts;
public DigitCount() { charCounts = new HashMap<>(); }
public void processLine (String curLine) {
int length = curLine.length();
char curChar;
ArrayList<Integer> curCounts;
Integer curCount;
for(int i = 0; i < length; i++){
curChar = curLine.charAt(i);
try {
curCounts = charCounts.get(i);
} catch (NullPointerException ex) {
curCounts = new ArrayList<>();
}
try {
curCount = curCounts.get(i);
curCount++;
curCounts.set(i, curCount);
} catch (NullPointerException ex) {
curCounts.set(i, 1);
}
charCounts.put(curChar, curCounts);
}
linesProcessed++;
System.out.println("---------------------------" + linesProcessed);
}
Edit: Yes, I did call DigitCount.
public static void main(String args[]) throws Exception
{
//creates an instance of the digitCount object and starts the run method
DigitCount counter = new DigitCount();
counter.run(args[0]);
}
if charConts doesn't contain i (as in charCounts.get(i)), then it won't throw a NullPointerException, it will return null. Therefore you should be using an if and not a trycatch as in:
curCounts = charCounts.get(i);
if(curCounts==null)
curCounts = new ArrayList<>();
Edit: Alternatively if you are using java 8 you can do
curCounts = charCounts.getOrDefault(i,new ArrayList<Integer>());
and it will automatically default to creating a new ArrayList if it doesn't contain one

Is the code I wrote for my exercise efficient? [closed]

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

How can I instantiate the class DefaultHashMap [closed]

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 8 years ago.
Improve this question
I'm trying to access the DefaultHashMap class but getting error in the main method. Could anyone please tell me what is the problem?
import java.util.Random;
import java.util.*;
public class PythonToJava {
public static void main(String[] args) {
Random rm = new Random();
int i = rm.nextInt(1000);
HashMap<Integer,Integer> stats = new HashMap<Integer,Integer>();
DefaultHashMap<K,V> default = new DefaultHashMap<K,V>();
System.out.println("Random Number Generated is: " + i);
for (int j = 0; j<i; j++){
int value = rm.nextInt(500);
System.out.println("The value of VALUE is " + value);
}
}
}
class DefaultHashMap<K,V> extends HashMap<K,V> {
protected V defaultValue;
public DefaultHashMap(V defaultValue) {
this.defaultValue = defaultValue;
}
#Override
public V get(Object k) {
V v = super.get(k);
return ((v == null) && !this.containsKey(k)) ? this.defaultValue : v;
}
}
Please help me in rectifying the errors I'm encountering at the line with the code:
DefaultHashMap<K,V> default = new DefaultHashMap<K,V>();
The K and V are type parameters, and here, you need to use concrete types to substitute them, the same as when you are using HashMap.
K,V has to be objects
You cannot use variable default. Its a java reserve word.
You should read about java generics
http://docs.oracle.com/javase/tutorial/java/generics/why.html

Null Pointer Exception [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Improve this question
I am working on some project in java.
Here I'm stuck at this problem and not able to figure out where I am going wrong.
I have made two classes: Test and Child.
When I run the code I am get a NullPointerException.
package com.test;
public class Test {
child newchild = new child();
public static void main(String[] args) {
new Test().method();
}
void method() {
String[] b;
b = newchild.main();
int i = 0;
while (i < b.length) {
System.out.println(b[i]);
}
}
}
package com.test;
public class child {
public String[] main() {
String[] a = null;
a[0] = "This";
a[1] = "is";
a[2] = "not";
a[3] = "working";
return a;
}
}
Here's the problem:
String[] a = null;
a[0]="This";
You're immediately trying to dereference a, which is null, in order to set an element in it. You need to initialize the array:
String[] a = new String[4];
a[0]="This";
If you don't know how many elements your collection should have before you start populating it (and often even if you do) I would suggest using a List of some sort. For example:
List<String> a = new ArrayList<String>();
a.add("This");
a.add("is");
a.add("not");
a.add("working");
return a;
Note that you have another problem here:
int i=0;
while(i<b.length)
System.out.println(b[i]);
You're never changing i, so it will always be 0 - if you get into the while loop at all, you will never get out of it. You want something like this:
for (int i = 0; i < b.length; i++)
{
System.out.println(b[i]);
}
Or better:
for (String value : b)
{
System.out.println(value);
}
This is the problem:
String[] a = null;
a[0]="This";
They highlighted the problem of your probably the definition of null pointer exception would give you an idea what and where to find the problem in future. From java api doc, it defined what is npe and under what situation it will be thrown. Hope it help you.
Thrown when an application attempts to use null in a case where an object is required. These include:
* Calling the instance method of a null object.
* Accessing or modifying the field of a null object.
* Taking the length of null as if it were an array.
* Accessing or modifying the slots of null as if it were an array.
* Throwing null as if it were a Throwable value.
package test;
public class Test {
child newchild = new child();
public static void main(String[] args) {
new Test().method();
}
void method()
{
String[] b;
b = newchild.main();
int i=0;
while(i<b.length){
System.out.println(b[i]);
i++;
}
}
}
package test;
public class child {
public String[] main() {
String[] a = {"This","is","not","Working"};
return a;
}

Categories

Resources