Getting error by using Queue[] queues = new Queue[10]; - java

This is my code:
import java.util.*;
import unit4.collectionsLib.*;
public class Page255Project_class
{
static Scanner reader = new Scanner (System.in);
/**
* #param args
*/
public static void radixSort(int[] numbers){
Queue[] queues = new Queue[10];
for(int i=0; i<numbers.length; i++){
if(numbers[i]%10 == i)
{
queues[i].insert(numbers[i]);
System.out.println(queues[i]);
}
}
}
public static void main(String[] args)
{
int[] numbers = new int[10];
numbers[0] = 170;
numbers[1] = 45;
numbers[2] = 75;
numbers[3] = 90;
numbers[4] = 2;
numbers[5] = 24;
numbers[6] = 802;
radixSort(numbers);
}
}
And I’m getting this error:
Exception in thread "main" java.lang.NullPointerException
at Page255Project_class.radixSort(Page255Project_class.java:15)
at Page255Project_class.main(Page255Project_class.java:33)
Please help to solve that error

In your function radixSort you have defined array of size 10 holds 10 "empty slots", but you forgot to initialize all of the slots.
The change in your code will be like the following:
public static void radixSort(int[] numbers) {
Queue[] queues = new Queue[10];
Arrays.fill(queues, new Queue()); // Queue is interface you need to implement it
// or you need to choose specific type of
// queues [PriorityQueue, LinkedBlockingQueue, ...]
for(int i = 0; i < numbers.length; i++) {
if(numbers[i] % 10 == i) {
queues[i].insert(numbers[i]);
System.out.println(queues[i]);
}
}
}

Related

Modify the java program so that it works for the numbers in range between -25 and 25

I've started learning java some time ago. I'm reading through the Java Foundations book and doing exercises from the book to practice.
Just come across this one "Modify the java program so that it works for the numbers in the range between -25 and 25." and I wonder if you have any different solutions to it or is it really that simple? :)
Here's the original code:
public class BasicArray
{
public static void main(String[] args)
{
final int LIMIT = 15;
final int MULTIPLE = 10;
int[] list = new int[LIMIT];
// Initialize the array values
for(int index = 0; index < LIMIT; index++)
list[index] = index * MULTIPLE;
list[5] = 999; // change one array value
// Print the array values
for(int value : list)
System.out.println(value + "");
}
}
And here's my solution to it:
public class BasicArray
{
public static void main(String[] args)
{
final int LIMIT = 51;
final int MULTIPLE = 1;
int[] list = new int[LIMIT];
// Initialize the array values
for(int index = 0; index < LIMIT; index++)
list[index] = (index - 25) * MULTIPLE;
list[5] = 999; // change one array value
// Print the array values
for(int value : list)
System.out.println(value + "");
}
}
Yes, basically it's really simple exercise.
Regarding to your solution we actually don't need MULTIPLE in code.
public class BasicArray {
public static void main(String[] args) {
final int LIMIT = 51;
int[] list = new int[LIMIT];
// Initialize the array values
for(int index = 0; index < LIMIT; index++) {
list[index] = (index - 25);
}
list[5] = 999; // change one array value
// Print the array values
for(int value : list) {
System.out.println(value + "");
}
}
}
If you are ready for a bit of advanced java, you can try following:
public class BasicArray {
public static void main(String[] args) {
IntStream.rangeClosed(-25, 25)
.forEach(System.out::println);
}
}
Or this if you need to replace one value:
public class BasicArray {
public static void main(String[] args) {
IntStream.rangeClosed(-25, 25)
.forEach(i -> {
if (i == -20) { // change one array value
System.out.println(999);
} else {
System.out.println(i);
}
});
}
}

Exception Java main ArrayList error with java

public class DecimalToBinaryExample2{
public static void toBinary(int decimal){
int binary[] = new int[40];
int index = 0;
while(decimal > 0){
binary[index++] = decimal%2;
decimal = decimal/2;
}
}
public static void main(String[] args) {
Random rand = new Random();
int n = rand.nextInt(100);
ArrayList arry = new ArrayList();
arry.add(n);
System.out.println(Integer.toBinaryString(n));
for (int i = 0; i <= n; i++) {
arry.add(Integer.toBinaryString(i));
System.out.println(arry);
int arrayStore = ((CharSequence) arry).length();
if (arrayStore == 100) {arry.subList(50, 100);}
}
}
}
I keep getting this error:
Exception in thread "main" java.lang.ClassCastException: class java.util.ArrayList cannot be cast to class java.lang.CharSequence.
You can't cast that in that way. Instead of ((CharSequence) arry).length() you can just use arry.size().

Queue does not take parameters in java

I have a problem in my code
I'm not being able to add Queue
When I tried to add this code
Queue<Integer> myqu = new LinkedList<>();
for (int i = 0; i <= mySecondArray.length + 1; i++){
myqu.add(mySecondArray[i]);
}
To this code
import java.util.LinkedList;
import java.util.Queue;
import java.util.*;
class test{
static class Queue{
static Stack<Integer> s1 = new Stack<Integer>();
Queue<Integer> myqu = new LinkedList<>();
static int[] intArray = new int[]{ 1,2,3,4,5,6,7,8,9,10 };
static int[] mySecondArray = new int[10];
static void enQueue(){
for (int i = 0; i < intArray.length; i++){
s1.push(intArray[i]);
}
System.out.printf("\nBefore multiply operation\n");
System.out.printf("%s \n",s1);
System.out.printf("\nAfter multiply operation\n");
Integer edit = s1.pop();
System.out.printf("[");
for (int i = 1; i <= s1.size() + 1; i++){
mySecondArray[i] = i * 2;
edit = Integer.valueOf(i) * 2;
System.out.printf("%s",edit);
System.out.printf(", ");
}
System.out.printf("]");
for (int i = 0; i <= mySecondArray.length + 1; i++){
myqu.add(mySecondArray[i]);
}
}
};
public static void main(String[] args)
{
Queue q = new Queue();
q.enQueue();
}
}
It says " error: type Queue does not take parameters
Queue myqu = new LinkedList();"
Could you correct the code, Please
You are geeting this issue because your class name and interface Queue name is same.
Change you class name and this issue will resolve like:
static class SampleQueue{
..your code
}
And change your main method for new name:
public static void main(String[] args)
{
SampleQueue q = new SampleQueue();
q.enQueue();
}
If you're trying to use java.util.Queue, why are you creating your own inner static class called Queue? Rename your Queue class, and it's also declared static, so you can't instantiate it with new
Also you myqu is not declared static, so you need to fix that as well, I renamed it myQueue in the code below as per naming conventions
public class test {
static class QueueUtil {
static Stack<Integer> s1 = new Stack<Integer>();
static Queue<Integer> myQueue = new LinkedList<>();
static int[] intArray = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
static int[] mySecondArray = new int[10];
static void enQueue() {
for (int value : intArray) {
s1.push(value);
}
System.out.print("\nBefore multiply operation\n");
System.out.printf("%s \n", s1);
System.out.print("\nAfter multiply operation\n");
Integer edit = s1.pop();
System.out.print("[");
for (int i = 1; i <= s1.size() + 1; i++) {
mySecondArray[i] = i * 2;
edit = i * 2;
System.out.printf("%s", edit);
System.out.print(", ");
}
System.out.print("]");
for (int i = 0; i <= mySecondArray.length + 1; i++) {
myQueue.add(mySecondArray[i]);
}
}
}
public static void main(String[] args) {
QueueUtil.enQueue();
}
}
This code should fix your issue that you asked about, but I think you're not going to get the results you're expecting...
I recommend reading up on how, when and why to use static, there are a lot of great posts on here.

Printing a random string from my ArrayList to the console

Here's my code:
public static void main(String[] args) {
ArrayList<String> eMinor = new ArrayList<String>();
eMinor.add("E");
eMinor.add("F#");
eMinor.add("G");
eMinor.add("A");
eMinor.add("B");
eMinor.add("C");
eMinor.add("D");
}
What do I need to add in order to generate a random string from the list and print it in the console?
You can randomly select a value from the list with something like:
int index = new java.util.Random().nextInt(eMinor.size());
String value = eMinor.get(index);
and then print it to the console with:
System.out.println(value);
public static void main(String[] args) {
ArrayList<String> eMinor = new ArrayList<String>();
eMinor.add("E");
eMinor.add("F#");
eMinor.add("G");
eMinor.add("A");
eMinor.add("B");
eMinor.add("C");
eMinor.add("D");
Random rand = new Random()
int random = rand.nextInt(eMinor.size());
String note = eMinor.get(random);
System.out.println(note);
}
e minor is one of my favorite keys, so I'll answer. You need a random number generator:
Random ran = new Random();
int x = ran.nextInt(eMinor.size() - 1)
System.out.println(eMinor.get(x));
You could generate multiple notes with a loop:
Random ran = new Random();
for (int i = 0, i < 10; i++) {
int x = ran.nextInt(7)
System.out.println(eMinor.get(x));
}
You could do something like this:
int min = 3;
int range = 3;
Random random = new Random();
int length = min + random.nextInt(range);
String randomString = "";
for (int i = 0; i < length; ++i)
{
randomString += eMinor.get(random.nextInt(eMinor.size() - 1));
}
System.out.println(randomString);
You can use a simple model, but to complex application is necessary more attention with Random class;
enter code here
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Main {
public static void main(String[] args) {
ArrayList<String> eMinor = new ArrayList<String>();
eMinor.add("E");
eMinor.add("F#");
eMinor.add("G");
eMinor.add("A");
eMinor.add("B");
eMinor.add("C");
eMinor.add("D");
for (int f = 0; f < 3; f++) {
System.out.printf("------------ list %s ------------\n",f);
for (String value : generateList(eMinor)) {
System.out.println(value);
}
}
}
private static List<String> generateList(ArrayList<String> eMinor) {
List<String> tempList = new ArrayList<>();
Random random = new Random();
while (tempList.size() != eMinor.size()) {
String value = eMinor.get(random.nextInt(eMinor.size()));
if (!tempList.contains(value)) {
tempList.add(value);
}
}
return tempList;
}
}
You may use the below complete example:
/*
* Created by Mohammed.Kharma on 2/9/2016.
*/
import java.util.Random;
import java.util.ArrayList;
public class Scrambler {
public static int[] Scramble(final int key, final int elementsCount) throws NegativeArraySizeException {
if (elementsCount < 0) {
NegativeArraySizeException ex = new NegativeArraySizeException("scrambler elementCount");
throw ex;
}
Random rand = new Random(key);
int[] order = new int[elementsCount];
for (int i = 0; i < elementsCount; i++) {
order[i] = i;
}
int count = elementsCount;
while (--count > 0) {
int nextRandom = rand.nextInt(count + 1); // 0 <= k <= count (!)
int temp = order[count];
order[count] = order[nextRandom];
order[nextRandom] = temp;
}
return order;
}
public static void main(String[] args) {
ArrayList<String> eMinor = new ArrayList<String>();
eMinor.add("E");
eMinor.add("F#");
eMinor.add("G");
eMinor.add("A");
eMinor.add("B");
eMinor.add("C");
eMinor.add("D");
for (int numOFRandoStrings = 0; numOFRandoStrings < 10; numOFRandoStrings++) {
int[] randomList = Scramble(new Long(System.currentTimeMillis()).intValue() * numOFRandoStrings, 7); //numOFRandoStrings or any seed,7 means give me 7 random numbers from zero to 6
StringBuffer randomString = new StringBuffer();
for (int ind = 0; ind < randomList.length; ind++) {
randomString.append(eMinor.get(randomList[ind] ));
}
System.out.println("New Random String: " + randomString);
}
}
}

Adding results from loop into Array?

I am currently just mocking about with Java. To get some learning in, and of course the easiest way to learn is by asking.
In this section I've created a loop to give me 50 random numbers. What I want to do, is to compare these numbers later on. That's why I want to move all the numbers into an array. I have no clue how. I've tried different stuff, but my syntax is wrong. Can somebody tell me how to do this?
Code:
package project.main;
import java.util.Random;
public class Main {
public static int numbers[];
public static final void main(String []args) {
getRandom();
recheckNumbers();
}
public static void getRandom() {
Random RandomNumber = new Random();
for(int i = 1; i <= 50; ++i){
int randomInt = RandomNumber.nextInt(100);
System.out.println("Generated : " + randomInt);
}
}
public static void recheckNumbers() {
if(numbers[0] < numbers[1]) {
System.out.println("numbers[0] is biggest");
} else {
System.out.println("numbers[1] is biggest");
}
}
}
I just rewrote it a bit. Im now running into another issue at line 14. which is the numbers[i] = randomInt part.
Heres the new code..
package project.main;
import java.util.Random;
public class Main {
public static int numbers[];
public static final void main(String []args) {
Random RandomNumber = new Random();
for(int i = 0; i <= 49; ++i){
int randomInt = RandomNumber.nextInt(100);
numbers[i] = randomInt;
}
}
}
for(int i = 0; i <= 49; ++i){
int randomInt = RandomNumber.nextInt(100);
numbers[i] = randomInt;
System.out.println("Generated : " + randomInt);
}
After that you can loop through to get number
for(int i = 0; i <= 49; ++i){
System.out.println("Generated : " + numbers[i]);
}
Solution to new question
import java.util.Random;
public class Main {
public static int[] numbers = new int[50];
public static void main(String[] args) {
Random RandomNumber = new Random();
for(int i = 0; i <= 49; ++i){
int randomInt = RandomNumber.nextInt(100);
numbers[i] = randomInt;
}
}
}
The solution lemon provided is correct.
Additionally I want to point you to a mistake you did in your recheckNumbers method. You check if numbers[0] is smaller than numbers[1] and print out that numbers[0] is the biggest in the if block. You should switch the output from the if and else block to return the correct answer.
You need to say the size of the array. Here is my solution to your problem:
public class Main {
public static int numbers[] = new int[50];
public static void main(String[] args) {
getRandom();
recheckNumbers();
}
public static void getRandom(){
Random randomNumber = new Random(); // variables should start with lower case
for(int i = 0; i < 50; i++){
int randomInt = randomNumber.nextInt(100); // generate a random integer in the (0-99) interval
System.out.println("Generated: " + randomInt); // print the generated number
numbers[i] = randomInt; // put it in the array
}
}
public static void recheckNumbers(){
if(numbers[0] > numbers[1]){
System.out.println("numbers[0] is bigger");
} else {
System.out.println("numbers[1] is bigger");
}
}
}
Hope it helps :)

Categories

Resources