Getting random verbiage while printing array variable in Java - java

I'm learning basics of Java and there seems to be an observation I'm not able to get my head around.
Below is the code that is supposed to print the binary implementation of a base10 number. There are no errors or warnings but logical anomalies I'm looking for answers.
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;
public class Main
{
private static final Scanner scanner = new Scanner(System.in);
public static void main(String args[]) {
int n = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
int remainder, quotient, i=0;
int[] binary=new int[n];
/* Binary division -Extracting the 1's and 0's out of the base10 number and storing it in binary[] */
while(n!=0){
remainder=n%2;
quotient=n/2;
binary[i]=remainder;
n=quotient;
i++;
}
int k=i; // For storing the length of array till I want my bits to be reversed since all other bits are initialized to 0.
/*Reversing the binary[] to get the coreect binary value.*/
for(int j=0; j<=i; j++){
int temp=binary[j];
binary[j]=binary[i];
binary[i]=temp;
i--;
}
/*Printing out all the bits of binary number. */
for(int l=1;l<=k;l++){
System.out.print(binary[l]);
}
System.out.println(binary); /*Prints a garbage looking value: For ex- for 25 i get: [I#33909752 */
scanner.close();
}
}
Concerns for my code:
1. I am not able to comprehend possible reasoning as to why I am getting random garbage looking verbiage when I try to print the array variable - binary. Is this something expected? If so what is this?
For example:
In my code when I provide an input of 25 I get [I#33909752 while printing the binary variable. I expected something like an [1,1,0,0,1,0,....,0]
2. I get an extra 0 in front of my binary value if I start my for-loop to print the binary from 0 instead of 1
For example:
for(int l=1;l<=k;l++)
{
System.out.print(binary[l]);
}
Prints 11001 for 25 but if I start the loop from 0, I get 011001. I checked all other places of the code by putting SOPLn statements and nowhere the 0 index of array is getting 0. I wonder why?

Don't import arbitrary stuff coming into you mind. You don't use anything from the packages java.io, java.math, java.security, java.text, java.util.concurrent, or java.util.regex. The only thing needing an import in your code so far is java.util.Scanner
You don't need a construct like scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"). If you are going to read another token, which does not happen in you code anyway, the scanner will already skip white-space, including line breaks, by default. There's also scanner.nextLine(), but you don't need it here.
Do not close System.in. While a Scanner created around a resource allocated by yourself should be closed, you are not responsible for System.in.
System.out.println(Object) prints the result of calling toString() on the object. For classes not providing an implementation, like arrays, the method inherited from java.lang.Object produces getClass().getName() + "#" + Integer.toHexString(hashCode()). The int[] array's class name is [I, that's why you see [I# plus some hex number.
Use System.out.println(Arrays.toString(binary)); instead. But this will print the entire array, including the unused elements.
Instead of modifying an existing variable in a loop, creating the need for a new variable in the outer scope, you should introduce a new changeable, temporary variable in the loop. Further, you have to become familiar with the standard loop idiom, start at index zero and exclude the end index (use < rather than <=).
The loop variable will contain the excluded end index after the loop, when the condition evaluated to false. This logic also applies to your first while loop; afterwards, i will contain the first unused the index or the used length, both interpretations are valid. Subsequent uses must exclude it, using <, which is, as said, the usual pattern. For your reversal loop, this also implies that the end index must be decremented before being used.
Fixing the loop logic will fix your issue with the leading zero.
import java.util.Arrays;
import java.util.Scanner;
public class Main {
private static final Scanner scanner = new Scanner(System.in);
public static void main(String args[]) {
int n = scanner.nextInt();
int remainder, quotient, i=0;
int[] binary=new int[n];
/* Binary division -Extracting the 1's and 0's
out of the base10 number and storing it in binary[] */
while(n!=0) {
remainder=n%2;
quotient=n/2;
binary[i]=remainder;
n=quotient;
i++;
}
/*Reversing the binary[] to get the correct binary value.*/
for(int j=0, k=i-1; j<k; j++,k--) {
int temp=binary[j];
binary[j]=binary[k];
binary[k]=temp;
}
/*Printing out all the bits of binary number. */
for(int l=0; l<i; l++) {
System.out.print(binary[l]);
}
System.out.println();
System.out.println(Arrays.toString(binary));
}
}
25
11001
[1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

Related

I made code to calculate greatest common divisor but there is issue

Hi people I made code to calculate greatest common divisor of 2 number.
It work good but I get many outputs. I want the greatest output but I don't know how to fix it?
What my code do is this here: You enter 2 integer. The first integer must be greater than the second. Now code check second integer first. Is it dividable by 1, 2, 3, 4, 5, .. Then code check all working numbers with first number. In the end we have greatest common divisor.
And before code does all it, it check if second number divide first (in case second is the gcd).
Now my problem: Let's take input 36 and 14. My code will give output
1
2
But how can I avoid code also print all other working numbers? I only want printed the greatest working number but no idea how to implement this in my code? I also don't want copy other code because I did all myself till here and proud:
import java.util.Scanner;
public class Testit{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
double x = input.nextDouble();
double y = input.nextDouble();
double first=0;
first=x/y;
if(first==(int)first){
System.out.println((int)y);
return;
}
else{
for(double i=1; i<x && i<y; i++){
double sum=0;
sum=y/i;
if(sum==(int)sum){
double temp=0;
temp=x/i;
if(temp==(int)temp){
System.out.println((int)i);
}
}
}
}
}
}
Instead of printing, save the result in a temporary variable
double first=0;
int greatestCommonDivisor = 1;
...
if(temp==(int)temp){
greatestCommonDivisor = Double.valueOf(i).intValue();
}
...
System.out.println("Greatest common divisor:" + greatestCommonDivisor);
That said, there are a lot of places your algorithm and code could be improved. For a start you should think about starting at the largest possible number and just stopping when you found the first common divisor (because that would be the greatest) instead of looping through all possible numbers starting from the smallest possible number. And you should have a look at the modulo operation and use integers instead of doubles for your values.
You have to change your code; for example like this:
Currently, your code is simply printing each time it finds a "match".
Instead of printing immediately, you push that value into a helper variable. And in the end; when your loop has ended, you simply print that helper variable!
Then you automatically print the last number that your algorithm computed and stored.
( I am not giving you any code here; just an idea - as you will learn more by writing the code yourself! )

hackerrank xor in arrays

I am trying to solve this problem on hackerrank and it took me a while to get to the trick.
The trick lies in property of xor and the number of times a number appears in a subset of array where a subset is contiguous one (kindly note).
So if we have 1,2,3 the subsets will be:
1
1,2
1,2,3
2
2,3
3
The number of times a value at index i appears in these subsets is (n-i)*(i+1) as it can be seen that 1 appears (3-0)*(0+1) = 3 times. n is the length of the array.
Second trick is XOR of a number is 0 with itself if we take that number even number of times and if it appears odd number of times the answer is the number itself, also the important thing to note is XOR operation is associative.
The problem asks us to xor the subsets and then take XOR of each resultant value.
So rather than brute force approach, I counted the number of times each number appears in array and checked out whether it occurs even number of times or odd number of times but 8 testcases passed and 4 failed. The test case are too long to debug or dry run.
My question is why 4 testcase failed. Here is the Java code.
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class J {
static int []arr=new int[100000];
static int an;
public static void main(String[] args)throws IOException {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
int t,i,j,n;String []s;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
t=Integer.parseInt(br.readLine());
int []ans=new int[t];
for(i=0;i<t;++i)
{
n = Integer.parseInt(br.readLine());
s=br.readLine().split(" ");
j=0; an=0;
for(String str:s)
arr[j++]=Integer.parseInt(str);
for(j=0;j<n;++j)
{
if(((j+1)*(n-j))%2==1)
an=an^arr[j];
}
ans[i]=an;
}
for(i=0;i<t;++i)
System.out.println(ans[i]);
}
}
The reason is overflow in
(j+1)*(n-j)
The product may be ~10^10 cause the total size of array is up to 10^5.
So you need to calculate this product using long.
I tested your code with this dummy change:
long a = j + 1;
long b = (n - j);
if((a*b)%2==1) {
an=an^arr[j];
}
And program passed all tests successfully.

Trying to display the two dimmensional array contents in java

I'm a new to java.I'm looking to print the contents in the two dimmensional array namely myPoints.However,when i'm printing the code.it is throwing up the following error.
mypoints4
i value is 0
2
i value is 1
5
i value is 2
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
2 at perceptron.main(perceptron.java:37)
import java.util.*;
import java.io.*;
import java.text.*;
import java.math.*;
import java.awt.*;
class perceptron{
public static void main(String[] args){
int[][] myPoints = {{2,3},{4,5},{7,8},{9,10}};
int [][] myplot = {{3,4},{5,6},{5,5},{5,3}};
int sum=0;
int i=0;
System.out.println("mypoints"+myPoints.length);
while(i<=myPoints.length){
System.out.println("i value is"+i);
System.out.println(myPoints[i][i]);
i = i+1;
}
}
}
You need to use nested loops for that.
The reason you get the ArrayIndexOutOfBoundsException is because you're using myPoints[i][i], so when i is 2 it is looking for the third element of the third inner array (ie {7,8}) when it doesn't exist
This is because of while(i<=myPoints.length) need to be while(i<myPoints.length).. In case of array in size 5, your i should be i=0, i=1, i=2, i=3, i=4.. Exclude 5.
Another issue is:
System.out.println(myPoints[i][i]);
should be : System.out.println(myPoints[i][0] + " " + myPoints[i][1]);
Because the second dimensional of youre array is only 2 size.. and not 5
Your condition on the while loop must be "less" not "less or equal".
This is because the array index is zero based and hence the index range is always from 0 to (length - 1).
You're going up to (and including) the length of the outer array. This is an array index out of bounds because the indices of an array of length n are 0 ... (n-1). So trying to access index n is out of bounds.
You're accessing the sub array at index i, which is out of bounds for later sub arrays. This would work for a square matrix (you'd read down the diagonal), but your matrix is 4*2, so myPoints[2][2] is OOB, because you can't access index 2 of the length 2 array {7,8}.
The simplest way to iterate over every element in a 2-D array is to have to have a nested loop, like such:
for(int i = 0; i < myPoints.length; i++){
for(int j = 0; j < myPoints[i].length; j++){
System.out.println(myPoints[i][j]);
}
}
An even more concise way of doing this is by using a for-each loop, which gets rid of indices entirely and just gives you each element in the array, in order:
for(int[] row : myPoints){
for(int val : row){
System.out.println(val);
}
}
An even more concise way is to use the method Arrays.deepToString(...):
System.out.println(Arrays.deepToString(myPoints));

I am having Problems with Arrays

I am having issues with this array code. It needs to have a number count that displays the numbers that are entered by the user. So for instance, if the user enters three four's it will say "4 3." I already have the majority of the code done, but it is just returning the first number that's entered.
import java.util.Scanner;
public class NumberCounts
{
public static void main(String args[])
{
int[] answer = new int [100];
inputArray(answer);
}
public static void inputArray(int[] Numbercounts)
{
System.out.println("This Program is written by Benjamin Barcomb\n");
Scanner kb = new Scanner(System.in);
System.out.print("How many numbers will you enter? : ");
kb.nextInt();
//int[] answer = new int[100];
int arryNum[] = new int[] {};
System.out.println("\nEnter numbers in [0, 100] range separated by a space:");
int input = kb.nextInt();
System.out.println("Number Count");
int[] counter = new int[] {input};
for (int i = 0; i < arryNum.length; i++) {
System.out.println(" " + (i + 1) + " " + counter[i]);
}
for (int i = 0; i < counter.length; i++) {
System.out.println(" " + (i + 1) + " " + counter[i]);
}
}
}
Where to start...
1) You create an array answer of length 100, pass it to your method, then never use it anywhere.
2) You ask the user to tell you how many numbers they are going to enter, you get that input with kb.nextInt(), then do nothing with it. You never assign that int to a variable.
3) You create an array arryNum and leave it empty. You never put anything into it, ever.
4) You ask the user to input numbers separated by spaces. You then take only the first int they enter.
Since it seems like you are just learning I will leave the coding to you. Hopefully if you can now see what certain parts of your code are doing you will be able to move on from there. My one tip would be to use more descriptive variable names. It makes it easier for you to read what is going on when you look at your code.
Some Solutions
1) Unless the requirements say you must pass an array into the inputArray() method, I would just remove it all together since you are doing all the other work in the method. I would remove int[] answer = new int [100]; call the method with no parameters inputArray() and change the signature of the method to just
public static void inputArray() { ... }
2) When you ask the user how many numbers they are going to enter you are basically asking them "How long should my array be?" When you get this int you should use it to make your new array. Something like
System.out.print("How many numbers will you enter? ");
int usersNumbers = new int[kb.nextInt()];
Notice I have changed the name of arrayNum to usersNumbers. It's more descriptive and makes reading your code easier.
3) Now you want to get all those numbers and put them into that array. Since you need to get multiple numbers you will need a loop. Again, unless the requirements say you have to, I would do this a bit differently. Instead of entering all the numbers on one line separated by spaces, I would ask for the numbers individually. Since we know the length of the array (how many numbers they are going to enter), we know how many times to prompt them.
System.out.println("\nEnter numbers in [0, 100] range.\n");
for (int i = 0; i < usersNums.length; i++) {
System.out.println("Enter Your Number:");
usersNums[i] = kb.nextInt();
}
4) Now onto counting the number of occurrences of each int entered. Since the user can enter their numbers in any random order it makes things tougher. Again, I'm not sure what exactly your requirements allow or not, but here is what I did. First I want to get a list of the unique numbers. For example, if the array is {2, 4, 2, 5, 2, 4} I want to get a list with {2, 4, 5}. Once I have that I can look at each of those numbers and go through the array counting how many times I see each one. An easy way to get a list of unique numbers is to put them into a Set. It is a data structure which doesn't allow duplicates. A TreeSet is a Set which puts the numbers in order, just to make it easier to read.
Set<Integer> uniqueNumbers = new TreeSet<Integer>();
for (int i : usersNums) { uniqueNumbers.add(i); }
Now that I have the list of unique numbers I can start counting. I start count at 0. Then for every number in the set, I look at every number in the array and see if they are the same. If they are, count goes up by 1. Once I get to the end of the array I print my results for that number, then reset count to 0.
int count = 0;
for (Integer i : uniqueNumbers) { //For every number in the Set
for (int j = 0; j < usersNums.length; j++) { //Look at every number in the array
if (i == usersNums[j]) { count++; } //If the same, count++
}
System.out.print(i + " - " + count + "\n"); //Print results
count = 0; //Reset Count
}
It seems you're only getting the first value because you only called nextInt() on your scanner once. You should ideally have a while loop to keep gathering user input. Also, I think you're trying to store your answers in an array, which really isn't ideal since you don't know how big your input will be. You should really use a list. Something along the lines of
List<Integer> data = new ArrayList<Integer>();
while (kb.hasNext()) {
data.add(kb.next());
}
Explain your code hope you understand how to fix it.
First, I assume you want your user to enter more than one number but you use nextInt which means
The java.util.Scanner.nextInt() method Scans the next token of
the input as an int.An invocation of this method of the form
nextInt() behaves in exactly the same way as the invocation
nextInt(radix), where radix is the default radix of this scanner.
Suggestion: try to use to while loop to read more number and quite when your user enter -999999 for example as a termination for your while loop.
Second, use Array is not right data structure to use because you do not know the size of array.
There are 2 ways to fix this issue:
1. first to ask the size of array from the user like how many numbers the user wants to input which is not what you want.
2. use another data structure that shrinks and expands by itself which is ArrayList
Third, you did not say whether you gonna have different numbers in your input like
1 1 2 3 3 4 4 5 or unsorted like `1 2 1 4 3 4 5`
or just your input includes the same numbers like
2 2 2 2 2 2 2
More info for third point is here

Arrays and read and write text files issue - Java

Here is what I have to do...
Input File: dishin.txt
Output File: dishout.txt
Time Limit: 1 second
You do not like statisticians, and statisticians do not like you. Ever since that life actuary kicked sand into your ice cream when you were four, you have waged a slowly escalating war against those number-crunching jerks. But all that is about to change.
After many sleepless nights you have conceived the ultimate revenge: beating them at their own game. Using your computer programming skills, you will write a freeware statistics package so thorough, so complete, that statisticians all around the world will be out of a job. It will be able to predict weather patterns, calculate life expectancies, and even play the perfect poker game.
First, though, you must implement word wrap. However, this task is rather finnicky, not very mathematical in nature, and ultimately not very important. More urgently, you also need to implement some basic data analysis. Specifically, you decide to write a test program that takes a data set (a list of integers) and calculates the following measures of spread:
Minimum - the smallest value in the list. For example, the minimum of the numbers {5, 6, 5, 3} is 3.
Maximum - the largest value in the list. For example, the maximum of the numbers {5, 6, 5, 3} is 6.
Mean (or average) - defined as the sum of everything in the list divided by the number of items in the list. For example, the mean of the numbers {5, 6, 5, 3} is (5+6+5+3)/4 = 19/4 = 4.75. However for simplicity you are asked to round all answers down to the nearest whole number. So the mean of the numbers {5, 6, 3, 3}, rounded down, is 4.
Input:
The first line of input will consist of a single integer n (1 <= n <= 1,000), the size of your data set. The following n lines will describe the data set. Each of these lines contains an integer between 0 and 1,000,000 inclusive.
Output
The output file should consist of three integers separated by spaces: the minimum, maximum and mean of the data set.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Solution {
public static void main(String[] args) throws IOException {
///home/sebastian/workspace/Informatics Competition/src/
Scanner input = new Scanner(new File("/home/sebastian/workspace/Informatics Competition/src/dishin.txt"));
BufferedWriter output = new BufferedWriter(new FileWriter("/home/sebastian/workspace/Informatics Competition/src/dishout.txt"));
ArrayList<Integer> numbers = new ArrayList<Integer>();
while(input.hasNextInt()) {
numbers.add(input.nextInt());
}
numbers.remove(0);
Object max = Collections.max(numbers);
Object min = Collections.min(numbers);
System.out.println(numbers);
int sum = 0;
for (int i = 0; i<=numbers.size(); i++) {
sum += (int)(numbers.get(i));
}
int mean = (int)(sum / numbers.size());
output.write(String.valueOf(min+" "+max+" "+mean));
input.close();
output.close();
}
}
Here is the error:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 4, Size: 4
at java.util.ArrayList.rangeCheck(ArrayList.java:638)
at java.util.ArrayList.get(ArrayList.java:414)
at Solution.main(Solution.java:35)
It should be
for (int i = 0; i<numbers.size(); i++)
instead of
for (int i = 0; i<=numbers.size(); i++)
index must be less than the size of the numbers. Index starts from 0 till (size - 1)
Use The For-Each Loop to avoid such issues if you are interested to iterate each and every item of the array.
For-each loop (Advanced or Enhanced For loop):
The for-each loop introduced in Java5. It is mainly used to traverse array or collection elements. The advantage of for-each loop is that it eliminates the possibility of bugs and makes the code more readable
Syntax of for-each loop:
for(data_type variable : array | collection){}

Categories