Exception Java main ArrayList error with java - 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().

Related

I don't know how to set up object array

class Account {
int accountNumber;
int balance;
Account(int accountNumber, int balance) {
this.accountNumber = accountNumber;
this.balance = balance;
}
Account() {
int accountNumber = 0;
int balance = 0;
}
}
public class HW2 {
public static void main(String[] args) {
Account[] oneH = new Account[100];
accountNumberGenerator(oneH);
balanceGenerator(oneH);
for(int i = 0; i < oneH.length; i++){
System.out.println(oneH[i].accountNumber + " " + oneH[i].balance);
}
}
public static void accountNumberGenerator(Account[] arr){
Account one = new Account();
for(int i = 0; i < arr.length; i++){
arr[i] = one;
arr[i].accountNumber = i+1;
}
}
public static void balanceGenerator(Account[] arr){
int min = 100;
int max = 100000;
for(int i = 0; i < arr.length; i++){
Random rand = new Random();
int random_int = (int)Math.floor(Math.random()*(max-min+1)+min);
arr[i].balance = random_int;
}
}
}
I'm making an object array but it's not working.
Whenever I print each values of the Account array it just shows the 100 and random number that generated last for all values.
I'm not sure what is the problem.
public static void accountNumberGenerator(Account[] arr){
Account one = new Account();
for(int i = 0; i < arr.length; i++){
arr[i] = one;
arr[i].accountNumber = i+1;
}
}
In this method you are only creating one single instance of Account and assigning it to every element of the array.
You need to create a brand new object each iteration of your loop.
public static void accountNumberGenerator(Account[] arr){
for(int i = 0; i < arr.length; i++){
Account one = new Account();
arr[i] = one;
arr[i].accountNumber = i+1;
}
}
Here's a simple way to create 100 accounts.
public class Main {
public static void main(String[] args) {
java.util.Random r = new java.util.Random();
Account[] oneH = new Account[100];
for(int i=0; i<oneH.length; i++)
oneH[i] = new Account(i, r.nextInt(99900)+100);
for(int i = 0; i < oneH.length; i++)
System.out.printf("%3d%7d\n", oneH[i].accountNumber, oneH[i].balance);
}
}

Run Time Error on Java: "Null Pointer Exception" [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
I am getting this run time error which says there is a null pointer exception. I am just a beginner at Java and don't understand what this means.
Error message is as follows:
Exception in thread "main" java.lang.NullPointerException
at MyLongArray.insert(MyLongArray.java:26)
at MyLongArray.main(MyLongArray.java:69)
import java.util.*;
public class MyLongArray
{
private long a[];
private int nElems;
public MyLongArray(int size)
{
long[] a = new long[size];
nElems = a.length;
}
public int find(long searchKey) {
int m =0;
for(int i=0; i < nElems; i++)
if(searchKey == a[i])
m = i;
return m;
}
public void insert(long value) {
#SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
System.out.print("At what index do you want to insert? "); int i = sc.nextInt();
a[i] = value;
}
public long getElem(int index) {
return a[index];
}
public boolean delete(long value) {
long[] temp = new long[nElems];
int f = 0;
int o = 0;
for(int i=0; i < nElems; i++)
{
if(value != a[i])
{
temp[o++] = a[i];
}
else
f = 1;
}
for(int j=0; j < nElems; j++)
a[j] = temp[j];
for(int i=0; i < nElems; i++)
System.out.print(a[i] + " ");
if (f==1)
return true;
else
return false;
}
public void display()
{
for(int i =0; i < nElems; i++)
System.out.print(a[i] + " ");
}
public static void main(String[] args)
{
MyLongArray m = new MyLongArray(5);
m.insert(5);
m.find(21);
m.getElem(2);
m.delete(3);
m.display();
}
}
In constructor MyLongArray with long[] a = new long[size], you are declaring new local array a, instead of initializing your class variable array. After that in the insert method, you are trying to set elements in a non-initialized array a.
Use a = new long[size] instead of long[] a = new long[size].
You need to use a = new long[size] or this.a = new long[size] to initialize the instance field instead of declaring a local variable a inside the constructor.

How can I compile this program?

I have a problem with compilation of this program I don't know how can I solve this problem
class ArrayTester{
public void arrayTester(ArrayDeque arrayDeque) {
List evenlist = new ArrayList();
List oddlist = new ArrayList();
for (int n = 0; n < arrayDeque.size(); n++) {
if (arrayDeque.Length() % 2 == 0) {
arrayDeque.addAll(evenlist);
} else {
arrayDeque.addAll(oddlist);
}
System.out.println(evenlist);
System.out.println(oddlist);
}
}
}
class Kodilla {
public static void main(String[] args) {
ArrayDeque<String> arrayDeque = new ArrayDeque<>();
Random random = new Random();
String text = "";
int howLong = random.nextInt(50) + 1;
while (text.length() < howLong) {
text = text + "a";
for (int i = 0; i < 50; i++) {
arrayDeque.add(text);
System.out.println(arrayDeque);
System.out.println(arrayDeque.size());
arrayTester tester = new ArrayTester();
tester.arrayTester(arrayDeque);
System.out.println(arrayTester);
}
}
}
}
what I see is that in this line
arrayTester tester = new ArrayTester();
there is typo in the variable definition. (lowercase a)

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);
}
}
}

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

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]);
}
}
}

Categories

Resources