Value of the Array elements is always zero - java

public int X1[]=new int[1001];
public int X2[]=new int[1001];
public int Xj;
public double R[]=new double[1001];
public double[] Generate(int seed1,int seed2)
{
X1[0]=seed1;
X2[0]=seed2;
for(int j=0;j<2;j++)
{
X1[j+1]=(40014*X1[j])%(2147483563);
X2[j+1]=(40629*X2[j])%2147483399;
System.out.println(X1[j+1]+" "+X2[j+1]);
Xj=Math.abs(X1[j+1]-X2[j+1]);
Xj=Xj%2147483562;
System.out.println(Xj+" "+j);
if(Xj>0)
{ R[j]=Xj/2147483563;}
else if(Xj==0)
{ R[j]=2147483562/2147483563;}
System.out.println(R[j]+" "+j);
}
In the above code when i try to print the elements of R[],it just prints 0.Can someone tell me whats wrong?I've put i out.println statements as a way of debugging the code.However they print the desired value.

It's because you're performing integer divisions. For example, change this:
Xj/2147483563
... to this:
Xj/2147483563.0
Do the same with all the other divisions. Notice that in Java, int/int will always return an int. To get a result with decimals, one of the two operands (or both) must be a decimal number.

Related

Java Int(Why returning 0 when number is within range)

Thank you for your time!
for value upto 2147483641 code is working fine after that it is returning 0(why)..
as per my understanding program should return 0 only when overflow occurs.. (for -2147483648 and 2147483647 ) not for value falling in the range.
Also please share any link for leading zero number reversal.. I could not find any online.
public class ReverseDigit {
public int reverse(int integer) {
boolean negflag=false;
if(integer<0){
negflag=true;
integer=integer*-1;
}
int rev=0;
int rem=0;
while(integer!=0){
rem=integer%10;
int newrev= rev*10+rem;
if((newrev-rem)/10!=rev){
return 0;
}
else{
rev=newrev;
}
integer=integer/10;
}
return rev = negflag?rev*-1:rev;
}
public static void main(String[] args) {
ReverseDigit rd = new ReverseDigit();
System.out.println(rd.reverse(**2147483642**));
}
}
This is happens because the reversed number of 2147483642 is 2463847412, and this number is greater then Intrgre.MAX_VALUE which is 2147483647, so the number became less than 0.
This is happens to 2147483623 too, because his reversed number is 3263847412, and this number is greater then Intrgre.MAX_VALUE.
To fix that, I see two possible solutions:
Use long instead of int.
Rewrite the method to work with String, because you aren't really do any calculations (You can use string.charAt(int index) to get the digits one bt one).

I have trouble calculating by adding the specific value of each element of the array

I'm sure there is a lot if things missing, but I'm ready to listen and learn. I just cant figure how to count numbers that I put in system.out.println.
My code:
public static void main(String[]args) {
int[] m = {-3,12,1,51,2,-21,4,-2,42,0,-6,-56};
getNumbers(m );
}
public static void getNumbers(int[]m) {
for(int i=0; i<m.length;i++) {
if(m[i]<=12&&m[i]>=0) { //All positive numbers up to 12 give a special value of 1;
System.out.println("+"+1);
}else if(m[i]<=99&&m[i]>=13) { // All numbers from 13 to 99 give special value 2
System.out.println("+"+2);
}else if(m[i]<-10) { //Negative numbers greater than -10 give a special value of -1;
System.out.println("-"+1);
}else if(m[i]<0&&m[i]>-9) { //For all other numbers, the specific value is the same as the number itself
System.out.println(m[i]);
}
}
}
}
Declaring a variable globally and setting its default value to zero can help you.
After all, do not forget to increment it at the line before your first if (but inside of for)
If I did not misunderstand you

Avoid matching the same value twice in string.matches() method in Java

Okay, I'm totally rewriting this question because this works and I want to know why it works.
Suppose I have a number, testNumber with a value of 567.
I want to know if the next two numbers (shouldPassTest and shouldFailTest) the same digits, but in different 10s places.
So here's the code:
int testNumber = 567;
int num1 = 5;
int num2 = 6;
int num3 = 7;
int shouldPassTest = 756;
int shouldFailTest = 777;
if(Integer.toString(shouldPassTest).matches("[5,6,7][5,6,7][5,6,7]")
{
//Do some cool stuff
}
if(Integer.toString(shouldFailTest).matches("[5,6,7][5,6,7][5,6,7]")
{
//Do some cool stuff
}
What happens when you run that, is that each digit is tested from the range of available digits (5, 6, and 7). Theoretically, shouldFailTest should actually pass the test seeing as how 7 matches one of my three criteria, albeit 3 times.
But what happens is that 777 returns false, when tested. This is precisely the result I wanted in my code, but I want to know why it happened. Does the matches method test to make sure that each number is only matched once?
Thanks!
This post was highly edited. After running my code, I found that the method does exactly what I want, but now I want to know why. Thanks.
I would use the following as regex is not a good solution to this problem:
public class Count {
private int value;
public Count() {
value=0;
}
void increment() {
value++;
}
void decrement() {
value--;
}
public int getValue() {
return value;
}
}
public static boolean isAnagram(int val1, int val2) {
Map<Character, Count> characterCountMap=new HashMap<>();
for(char c:Integer.toString(val1).toCharArray()) {
Count count=characterCountMap.get(c);
if(count==null) { count=new Count(); characterCountMap.put(c, count);}
count.increment();
}
for(char c:Integer.toString(val2).toCharArray()) {
Count count=characterCountMap.get(c);
if(count==null) { return false; }
else { count.decrement(); }
if(count.getValue()==0) {
characterCountMap.remove(c);
}
}
return characterCountMap.size()==0;
}
Please run:
System.out.println(Integer.toString(shouldFailTest).matches("[5,6,7][5,6,7][5,6,7]"));
to view the actual return value.
Theoretically, shouldFailTest should actually pass the test seeing as
how 7 matches one of my three criteria, albeit 3 times.
But what happens is that 777 returns false, when tested. This is
precisely the result I wanted in my code, but I want to know why it
happened. Does the matches method test to make sure that each number
is only matched once?
No, "777" does match the pattern you have specified "[5,6,7][5,6,7][5,6,7]"
Following condition in your code will evaluate to true.
if(Integer.toString(shouldFailTest).matches("[5,6,7][5,6,7][5,6,7]"))

Storing the result of a method in a variable

For the past few months, I switched to programming in a functional language (Racket), and recently restarted coding in Java, so I'm a bit confused regarding a few concepts.
The following (simplified version) code is an implementation of euclid's algorithm. It works just fine. My problem with it is the return statement. Is it possible in java to store the results of a method in a variable? For example,in my code, I initialized the variable result to store the gcd of two numbers. But that returns an incorrect value. However, if I remove the variable result, I get the correct value for the gcd, which brings me to my 2nd question: return statements. I don't quite understand what the return statement is doing here. The only reason I have it in the 1st place was because I was aiming to store the result of the method Recursion in a variable. But as far as I've tried it, and seems to be only messing up my code.
Primary objective: To store the result of the gcd of two numbers in a variable, so I can re-use it elsewhere.
Is there is a way to make this possible?
Any suggestions would be appreciated!
import java.util.*;
public class StoringResults
{
public static void main(String[]args)
{
int big,small,remainder,gcd; //Variables declared.
Scanner sc=new Scanner(System.in);
/* Use enters input */
//Big is the larger number.
//Small is the smaller of the two.
remainder=big%small;
int result=recursion(big,small,remainder);
System.out.println("FINAL RESULT:"+result);
}
//recursive method.
public static int recursion(int big,int small,int remainder)
{
remainder=big%small;
if(remainder==0)
{
System.out.println(small);
}
else
{
int dummyvar=remainder;
big=small;
small=dummyvar;
recursion(big,small,remainder);
}
return remainder;
}
}
As my comment already stated your logic is faulty.
And your statement if I remove the variable result,I get the correct value for the gcd is plain wrong. You get the correct result printed but not returned. And that is caused by the fact that you return the wrong value.
remove the remainder from the method signature since your first statement is assigning something to it
return the correct value: smaller instead of remained
return in the else branch
That will result in the following code:
public static int recursion(int big,int small)
{
int remainder=big%small;
if(remainder==0)
{
System.out.println(small);
}
else
{
big=small;
small=remainder;
return recursion(big,small);
}
return small;
}
Shortening results in
public static int recursion(int big, int small) {
int remainder = big % small;
if(remainder == 0) {
return small;
} else {
return recursion(small,remainder);
}
}
Adding to TDG's answer, your code should be more like this:
//recursive method.
public static int recursion(int big, int small, int remainder) {
remainder = big%small
if (remainder==0) {
System.out.println(small);
return small;
} else {
Int dummyvar = remainder;
big = small;
small = dummyvar;
return recursion(big, small, remainder);
}
}

Converting Binary Number to Decimal using recursion technique

As the title says i was trying to convert binary to decimal using recursive technique in java but i cannot get the desire output
here's what i did
public class deci {
public static void main(String args[]){
hexa s1=new deci();
s1.spawn(11000);
}
void spawn(int a){
int p=0;int x=0;int k=0;
if(a>0){
p=a%10;
x=x+p*(int)Math.pow(2,k);
k++;
spawn(a/10);
} else {
System.out.print(x);
}
}
}
The problem is you ar not using the result of spawn, either returning or printing it.
If you want to return it, you need the shifting or power, but it you want to print it.
I suggest you step through the code in your debugger so you can see what it is doing.
Here is a working program.
Parameters are (binary code, size of code-1) e.g. for (111, 2) this will return 7
int binaryToDecimal(int binary,int size){
if(binary==0) return 0;
return binary%10*(int)Math.pow(2,size)+binaryToDecimal((int)binary/10,size-1);
}

Categories

Resources