This question already has answers here:
Why can't I do assignment outside a method?
(7 answers)
Closed 5 years ago.
class example{
int[] quiz = new int[] { 10 , 20 }; //location 1
public static void main(String[] args) {
int[] test = new int[2]; // location 2
test[0] = 2;
test[1] = 3;
// other code
}
The above code run correctly. However the code below causes an error. My reasoning for the error is since quiz is declared outside the method it needs to be initialized immediately. However I am not sure if this is a correct explanation.
class example{
int[] quiz = new int[2]; //location of error
quiz[0] = 10;
quiz[1] = 20;
public static void main(String[] args) {
int[] test = new int[2]; // location 2
test[0] = 2;
test[1] = 3;
//other code
}
You would need an initialization block to do it the second way,
int[] quiz = new int[2];
{
quiz[0] = 10;
quiz[1] = 20;
}
Related
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 is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I've been trying to work around this NullPointerException issue:
Exception in thread "main" java.lang.NullPointerException
at LinearSearcher.<init>(LinearSearcher.java:12)
at DemoSearches.main(DemoSearches.java:4)
through researching, I found that this exception occurs when you declare a reference type but don't create an object. In my case it is when I am trying to declare LinearSearcher
I've tried to understand this with my code but i'm having difficulties
Code for LinearSearcher:
public class LinearSearcher implements Searcher {
private int[] numbers;
public LinearSearcher() {
numbers[0] = 1; // Line 12 Here
numbers[1] = 10;
numbers[2] = 20;
numbers[3] = 30;
numbers[4] = 40;
numbers[5] = 50;
numbers[6] = 60;
numbers[7] = 70;
numbers[8] = 80;
numbers[9] = 90;
}
public int searchFor(int key) {
for (int i = 0; i < numbers.length; i++){
if (numbers[i] == key) {
return i;
}
}
return NOT_FOUND;
}
public void display() {
for (int i = 0; i < numbers.length; i++){
}
}
}
Class where LinearSearcher is declared:
public class DemoSearches {
public static void main(String args[]) {
LinearSearcher search = new LinearSearcher(); // Line 4 Here
search.display();
search.searchFor(50);
search.searchFor(100);
}
}
numbers is null because you haven't initialized it. You can change
private int[] numbers;
to
private int[] numbers = { 1, 10, 20, 30, 40, 50, 60, 70, 80, 90 };
and eliminate the problem. Other solution, add
numbers = new int[10];
Before your current assignments.
You never initialize the numbers array so when you try to access it in the LinearSearcher constructor you are trying to access a nonexistent array. So an exception is thrown.
You need to do numbers = new int[10]; before doing numbers[0] etc. This will create the object so it can be used.
This question already has answers here:
Java - generate Random range of specific numbers without duplication of those numbers - how to?
(6 answers)
Closed 6 years ago.
So I am trying to make a program that produces an array of 20 random numbers, that does not have duplicates (to the end user). Here is my code so far
import java.util.*;
public class randomprog
{
public static void main(String args[])
{
Random rand = new Random();
int[] list = new int[20];
boolean generating=true;
int counting=0;
while(generating)
{
int testNum= rand.nextInt(30)+1;
if (Arrays.asList(list).contains(testNum))
{}
else
{
list[counting]=testNum;
counting++;
System.out.println(testNum);
}
if(counting>=20)
{
generating=false;
}
}
}}
So as you can see I have already tried using Arrays.asList(list).contains(mynumber) however I still recieve duplicates in my output like
29
4
4
1
20
30
20
23
30
11
6
7
27
14
16
8
4
19
7
15
Any suggestions?
Use a HashSet to keep track of the numbers you have used.
For example
int[] result = new int[20];
HashSet<Integer> used = new HashSet<Integer>();
for (int i = 0; i < 20; i++) {
int add = (int)(Math.random() * 30); //this is the int we are adding
while (used.contains(add)) { //while we have already used the number
add = (int) (Math.random() * 30); //generate a new one because it's already used
}
//by this time, add will be unique
used.add(add);
result[i] = add;
}
This ensures that you will have no duplicates, and is also much faster than searching in an ArrayList, which will perform a number of operations equivalent to the size of the ArrayList each time you search for a number. A HashSet only performs 1 operation when you check if a number is contained.
The reason why your code doesn't work is that Arrays.asList(int[] list) returns an ArrayList<int[]> of size 1, and not an ArrayList<Integer>. So when you call contains, it's not checking against the integer elements of the original list, and is always returning false.
I would recommend using an ArrayList and do not use empty if blocks.
This should work.
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Main {
static List list = new ArrayList<>(20);
public static void main(String args[])
{
Random rand = new Random();
boolean generating=true;
int counting=0;
while(generating)
{
int testNum= rand.nextInt(30)+1;
if (!list.contains(testNum))
{
list.add(testNum);
counting++;
System.out.println(testNum);
}
if(counting>=20)
{
generating=false;
}
}
}
}
Use Collections.Shuffle
class Ideone{
public static void main(String[] args) {
Integer[] arr = new Integer[20];
for (int i = 0; i < arr.length; i++) {
arr[i] = i;
}
Collections.shuffle(Arrays.asList(arr));
System.out.println(Arrays.toString(arr));
}}
This question already has answers here:
NullPointerException when Creating an Array of objects [duplicate]
(9 answers)
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I get a NullPointerException at line 14 the one that says:
points[i].x = new Random().nextInt(30);
My full Code:
import java.util.Random;
public class RandomPoints {
public class Point {
public int x;
public int y;
}
public static void main(String[] args) {
Point[] points = new Point[100];
for(int i = 0; i < points.length; i++) {
points[i].x = new Random().nextInt(30);
points[i].y = new Random().nextInt(30);
System.out.println(points[i].x + " " + points[i].y);
}
}
}
When you say Point[] points = new Point[100]; it only allocates an array with room for 100 Point references (it doesn't allocate any Point instances). You need to allocate an instance for the index before you can access it, something like
Point[] points = new Point[100];
for(int i = 0; i < points.length; i++) {
points[i] = new Point(); //<-- like so.
Also, it would be better to reuse one Random created outside your array.
Random rand = new Random();
otherwise you reseed (twice) on every iteration. Meaning your numbers won't be very random.
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...