This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 5 years ago.
I am trying to find a way to print the contents of the array, while using a for loop. This is a fairly new section in java to me, as I am a beginner. Any help is appreciate in concerns to my question. My question is would I move the "Random" assessor method into the mutator method or am I just completely wrong and have to do something else.
import java.util.Random;
public class ArrayPractice {
private int[] arr;
private final int MAX_ARRAY_SIZE = 300;
private final int MAX_VALUE = 100;
public ArrayPractice() {
// initialize array
arr = new int[MAX_ARRAY_SIZE];
// randomly fill array with numbers
Random rand = new Random(1234567890);
for (int i = 0; i < MAX_ARRAY_SIZE; ++i) {
arr[i] = rand.nextInt(MAX_VALUE) + 1;
}
}
public void printArray( ) {
}
public static void main(String[] args) {
ArrayPractice ap = new ArrayPractice();
System.out.println("The contents of my array are: ");
ap.printArray();
System.out.println("");
}
}
My question is would I move the "Random" assessor method into the
mutator method or am I just completely wrong and have to do something
else.
You don't have to. Just use a loop to iterate through the array which is already filled in the constructor.
public void printArray( ) {
for (int i = 0; i < MAX_ARRAY_SIZE; ++i) {
System.out.println(arr[i]);
}
}
By the way, with Java 8, you can write less lines of code to achieve the same result:
Arrays.stream(arr).forEach(System.out::println);
public void printArray() {
//Print array
System.out.println(Arrays.toString(arr));
//another method with for loop
for (int i = 0; i < arr.length; i++)
{
System.out.println(arr[i])
}
}
Note there is plenty of other techniques
In terms of writing clean code, it would probably be good to move this bit of code into its own private method within the class, and calling that within the constructor.
public ArrayPractice() {
// initialize array
arr = new int[MAX_ARRAY_SIZE];
populateArray();
}
private void populateArray() {
// randomly fill array with numbers
Random rand = new Random(1234567890);
for (int i = 0; i < MAX_ARRAY_SIZE; ++i) {
arr[i] = rand.nextInt(MAX_VALUE) + 1;
}
}
Then in your printArray() method you can loop through the array and call System.out.println( ) for each item.
public void printArray( ) {
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
If you come from a more functional background, I can show you how to write this more functionally using Java 8 lambdas. Let me know.
This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 7 years ago.
Hello fellow Stackoverflowers,
How do I print out the numbersArray so that I can see the numbers?
When I sysout the numbersArray, it shows me:
[I#677327b6
[I#677327b6
Thank you for your time and help!
package AlgoExercises;
public class InsertionSort {
static int[] numbersArray = { 5, 2, 4, 6, 1, 3 };
static void swap(int a, int b) {
int temp = a;
a = b;
b = temp;
// a and b are copies of the original values.
// The changes we made here won't be visible to the caller.
}
static void insertionSort(int[] numbersArray) {
for (int i = 1; i < numbersArray.length; i++) {
int j = i;
while ((j > 0) && (numbersArray[j] < numbersArray[j - 1])) {
swap(numbersArray[j], numbersArray[j - 1]);
j = j - 1;
System.out.println(numbersArray);
}
}
}
public static void main(String args[]) {
insertionSort(numbersArray);
}
}
System.out.println(numbersArray); You are printing an array instead of values. you should print the value by numbersArray[i]
For printing out arrays use java.lang.Arrays.toString() method:
System.out.println(Arrays.toString(numbersArray));
For example if I enter inRange(1,6) then it must print {2,2,2,3,5} for the below array. I am not sure if my logic is right. Is there a better way to do this? I am also not sure of how to construct my return statement. I want to do this without using arraylist or array.
public class AgeCount {
static int[] a=new int[]{1,2,45,6,3,2,1,2,5,6,65,45,43,21,34,34};
public AgeCount(){
}
public static int inRange(int b,int e)
{
int store[]=new int[a.length];
int count=0;
for (int i = 0; i < a.length; i++) {
if(a[i]>b && a[i]<e)
{
return a[i];
}
}
return 0;
}
If your method only has to print the numbers of the given range, it doesn't have to return anything :
public static void inRange(int b,int e)
{
int count=0;
System.out.print('{');
boolean first = true;
for (int i = 0; i < a.length; i++) {
if(a[i]>=b && a[i]<=e)
{
if (!first) {
System.out.print(',');
} else {
first = false;
}
System.out.print(a[i]);
}
}
System.out.print('}');
}
This is assuming the order of the output doesn't matter. If it does matter, sort the input array prior to the loop.
Java 8 approach:
int[] arr = new int[] {1,2,45,6,3,2,1,2,5,6,65,45,43,21,34,34};
int res[] = Arrays.stream(arr).filter(n -> n >= b && n <= e).toArray();
System.out.println(Arrays.toString(res));
I'm not sure why you don't want to use arrays or some kind of a list. If it's for homework purposes, then instead of returning a value from the method, print it if you only want to display the result. Otherwise, you should consider using List.
Java8:
public static void main(String[] args) {
int[] arrayToFilter = new int[]{1, 2, 45, 6, 3, 2, 1, 2, 5, 6, 65, 45, 43, 21, 34, 34};
int upperLimit = 5;
inRange(arrayToFilter, upperLimit);
}
private static void inRange(int[] arrayToFilter, int upperLimit) {
String sortedAndLimitedString = Arrays.stream(arrayToFilter)
.sorted()
.filter(value -> value < upperLimit)
.mapToObj(String::valueOf)
.collect(Collectors.joining(",", "{", "}"));
System.out.println(sortedAndLimitedString);
}
Output:
{1,1,2,2,2,3}
This sounds like a homework question. Still here goes.
Your return being a single int it has to be something like 122235 which represents all the ints satisfying your range condition.
So you use BitSet class and set the bits when found in range, which you can convert to an int like above and return.
I assumed that the result must be sorted.
public static int[] inRange(int b,int e) {
return IntStream.of(a)
.filter(n -> n > b && n < e)
.sorted()
.toArray();
}
System.out.println(Arrays.toString(AgeCount.inRange(1, 6)));
// -> [2, 2, 2, 3, 5]
```
Here is the simple & the shortest solution.
import java.util.*;
public class AgeCount
{
static int[] a=new int[]{1,2,45,6,3,2,1,2,5,6,65,45,43,21,34,34};
public AgeCount()
{
}
public static void inRange(int b,int e)
{
int store[]=new int[a.length];
Arrays.sort(a);
for (int i = b; i < e; i++)
{
System.out.print(a[i+1]+",");
}
}
}
And this is how you return a value for the same.
//sort an array, get a defined index values, and print it on the screen.
import java.util.*;
public class AgeCount
{
static int[] a=new int[]{1,2,45,6,3,2,1,2,5,6,65,45,43,21,34,34};
public AgeCount()
{
}
public static int[] inRange(int b,int e)
{
int store[]=new int[a.length];
int[] myRange = new int[e-b];
Arrays.sort(a);
for (int i = b; i < e; i++)
{
for (int j = 0; j < (e-b); j++)
{
myRange[j] = a[i+1];
}
System.out.print(a[i+1]+",");
}
return myRange;
}
}
Nice start so far! Even though you said you didn't want to use array or ArrayList, it makes the most sense here to use one. I would use an ArrayList of Integers instead of just an array, because we don't know the length yet. Instead of saying return a[i];, you would say store.append(a[i]);. I haven't tested this code, so there may be an error or two, so please correct me if I'm wrong, but here's the fixed version:
public class AgeCount {
static int[] a=new int[]{1,2,45,6,3,2,1,2,5,6,65,45,43,21,34,34};
public AgeCount(){
}
public static void inRange(int b,int e)
{
ArrayList<Integer> store = new ArrayList<Integer>();
int count=0;
for (int i = 0; i < a.length; i++) {
if(a[i]>=b && a[i]<=e)
{
store.append(a[i]);
}
}
println(store);
}
}
Well first things first, it seems like you aren't fully clear on what you are trying to do. And that's okay! Sometimes a problem can seem overwhelming and confusing if we're not really sure what's supposed to happen.
I recommend when you're starting a new task you take some time to decompose the task. Take a piece of paper and try and break it down into its smallest and simplest parts and go from there, coding and testing it bit by bit. The basics of the SDLC (try googling the software development lifecycle) could help you here too - it's all about figuring out what you are trying to achieve and what are the various things you need to implement to get there.
And please, Don't panic and throw code you don't understand down! You'll only sink deeper into the confusion!
This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 8 years ago.
[after edit 1] I have seen the other answers here in SO, and from looking at my code, I find that I am adhering to the principle of Java's pass-by-value-of-reference. But still my array is not getting sorted. Please can someone point out any errors I am making in my code?
[after edit 2] Found the problem. It was nothing to do with array passing. In my merge method, it should be if (end-start<=0) not the other way round!
I am trying to implement mergesort. However, I am unable to display values of my array and am unsure of how to pass my arrays in Java such that the original array can be modified.
How can I modify my current code to display the values of the sorted array?
I understand java passes the copy of the array's reference around, but doesnt this mean that the original array gets modified?
CODE:
I am calling mergesort method from my main method.
public static void main(String[] args) {
int[] qn = {10,22,33,4,5,6,1};
qn= mergesort(qn,0,qn.length-1);
for (int i=0;i<qn.length;i++){ //print to see values if sorted/not
System.out.print(qn[i]+ " ");
}
}
public static int[] mergesort(int[] arr,int start,int end){
int mid = (end+start)/2;
if (end - start<=0){
return arr;
}
else if (end-start>=1){
arr=mergesort(arr,start,mid);
arr=mergesort(arr,mid+1,end);
}
arr=merge(arr,start,end);
for (int i=0;i<arr.length;i++){
System.out.print(arr[i]+ " ");
}
System.out.println();
return arr;
}
public static int[] merge(int[] arr,int start,int end){
int mid= (start+end)/2;
if(start-end<=0){
return arr;
}
int a= start; int b = mid+1;
while (a<=mid && b <=end){
if (arr[b]<arr[a]){
int tmp = arr[b++];
for(int i=++mid;i>a;i--){
arr[i]=arr[i-1];
}
arr[a++]=tmp;
}
else if (arr[b]>arr[a]){
a++;
}
else{ //arr[b]=arr[a]
if(a==mid && b == end){
break; //all between mid and end will be equal too
}
int tmp= arr[b++];
a++;
for (int i=++mid;i>a;i--){
arr[i]=arr[i-1];
}
arr[a++]=tmp;
//a++;
//b++;
}
}
return arr;
}
}
modified my answer based on Manu's below. but it's still not working. Attaching code below:
public static void mergesort(int[] arr,int start,int end){
int mid = (end+start)/2;
if (end - start<=0){
return;
}
else if (end-start>=1){
mergesort(arr,start,mid);
mergesort(arr,mid+1,end);
}
merge(arr,start,end);
for (int i=0;i<arr.length;i++){
System.out.print(arr[i]+ " ");
}
System.out.println();
return;
}
public static void merge(int[] arr,int start,int end){
int mid= (start+end)/2;
if(start-end<=0){
return;
}
int a= start; int b = mid+1;
while (a<=mid && b <=end){
if (arr[b]<arr[a]){
int tmp = arr[b++];
for(int i=++mid;i>a;i--){
arr[i]=arr[i-1];
}
arr[a++]=tmp;
}
else if (arr[b]>arr[a]){
a++;
}
else{ //arr[b]=arr[a]
if(a==mid && b == end){
break; //all between mid and end will be equal too (pearl)
}
int tmp= arr[b++];
a++;
for (int i=++mid;i>a;i--){
arr[i]=arr[i-1];
}
arr[a++]=tmp;
//a++;
//b++;
}
}
return;
}
}
You are right, in Java, the copy of the reference of the array gets passed to the function. However, both references point to the same object (the array in your case). This means if you change the values of the array in your merge-method, the values of the array in your mergesort-method changes too. Reqrite your code to this:
public static void mergesort(int[] arr, ...
public static void merge(int[] arr, ...
and simply call
merge(arr, start, mid);
This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 9 years ago.
I tried a program where I take an integer array and randomise values in it. but I am not able to understand why but am getting a crazy output which displays special characters and all. what's wrong with my question. Here is my code:
import java.util.Random;
public class Q2d {
public static void shuffle(int[] arr) {
int n = arr.length;
Random random = new Random();
random.nextInt();
for (int i = 0; i < n; i++) {
int change = i + random.nextInt(n - i);
int temp = arr[i];
arr[i] = arr[change];
arr[change] = temp;
}
}
public static void main(String args[]) {
int[] arr = { 1, 2, 3, 4, 5, 6 };
shuffle(arr);
System.out.println(arr);
}
}
You are attempting to print the array object. Arrays are objects too, but they don't override Object's toString() method, which is responsible for the "crazy output".
Use Arrays.toString():
System.out.println(Arrays.toString(arr));
I'm pretty sure you asked this question like 20 minutes ago and in it instead of
System.out.println(arr);
you had
for(int i:arr){
System.out.println(i);
}
which is correct...