Please help I can not see the error [duplicate] - java

This question already has answers here:
How can I convert List<Integer> to int[] in Java? [duplicate]
(16 answers)
Closed 4 years ago.
I am using Intellj Idea and I am playing with ArrayLists, Arrays and a sorting algorithm I want to generate 5 random grades put them into an ArrayList convert the values of the ArrayList into an Array. Sort the Array values from least to greatest and print to screen the grades before and after sort here is what I have:
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Arrays;
public class Grades {
public static void main(String args[])
{
ArrayList <Integer> scores = new ArrayList<Integer>();
for(int i = 0; i < 5; i++)
{
scores.add((int) (Math.random() * 30 + 1));
}
for (int i =0; i < scores.size();i++)
{
System.out.println(scores.get(i));
}
int arrayOne[] = new int[scores.size()];
arrayOne = scores.toArray(new int[scores.size()]);
The last line is where I have the problem. Intellij says: no suitable method found for toArray(int[]).
Is my syntax wrong?
Did I forget to import a library?
Is it possible for ArrayLists and Arrays to interact in this way?
Please help.
int first,second, temp=0;
for(first=0; first < arrayOne.length -1; first++)
{
for (second = 0; second < arrayOne.length - 1 - first; second++)
{
if(arrayOne[second] < arrayOne[second +1])
{
temp = arrayOne[second];
arrayOne[second] = arrayOne[second + 1];
arrayOne[second+1] = temp;
}
}
}
I haven't been able to run this bit to see if it sorts the way I want it too yet.
for(int i = 0; i < arrayOne.length; i++)
{
System.out.println(arrayOne[i]);
}
}
}

As you can see from toArray(T[]) contract it takes an array containing a reference type and int is not a reference type.
Change your code as to arrayOne is of type Integer[]
Integer[] arrayOne = scores.toArray(new Integer[scores.size()]);

Related

Unable to make array with 25 integers populated with random numbers from 10 to 99. /java [duplicate]

This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Array Printing Java
(3 answers)
Closed 2 years ago.
I have to use the math.random to populate my array with 25 random integers between the range 10 and 99. I'm also having problems trying to print the array. Instead of the full array being printed, only the memory location is printed. How to I write the command for it to print? This is how I've written my code and I know there's something wrong with it but just done know how to iron it out.
public class Proj5COMP110
{
public static void main(String args[])
{
System.out.println ("Project 5: Quick Sort");
int i;
int mSample [] = new int[25];
for ( i= 0; i< mSample.length ; i++)
{
mSample[25] = (int)(Math.random ()* (99-10)+10);
}
System.out.print(mSample[25]);
}
}
The problem as already mentioned in comments is that you have to change
mSample[25] = (int)(Math.random ()* (99-10)+10);
to
mSample[i] = (int)(Math.random ()* (99-10)+10);
I would like to prefer below code, which is less erroneous and doesn't have any warning.
public static void main(String[] args) {
int[] mSample = new int[25];
for (int loop = 0; loop < mSample.length; loop++)
mSample[loop] = new Random().nextInt(90) + 10;
for (int element : mSample)
System.out.println(element);
}
You are storing values into wrong index. use mSample[i] instead of mSample[25] to store value at index i.
mSample[i] = (int)(Math.random ()* (99-10)+10);
Also don't forget to change this line: System.out.print(mSample[25]); This will give you an indexOutOfBounds exception. Learn why this exception occurred.
public class Proj5COMP110
{
public static void main(String args[])
{
System.out.println ("Project 5: Quick Sort");
int i;
int mSample [] = new int[25];
for ( i= 0; i< mSample.length ; i++)
{
mSample[i] = (int)(Math.random ()* (99-10)+10);
}
for ( i= 0; i< mSample.length ; i++)
{
System.out.print(mSample[i]);
}
}
}
In an array the index starts from 0, therefore you should be able to store from mSample[1-24], mSample[25] would be out of bounds. When you are trying to print mSample[25], it is printing garbage value and not memory address.

Counting triangles in Java [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
What is a debugger and how can it help me diagnose problems?
(2 answers)
Closed 2 years ago.
question i am trying to solve.
You are given n triangles.
You are required to find how many triangles are unique out of given triangles. For each triangle you are given three integers a,b,c , the sides of a triangle.
sample input:
5
7 6 5
5 7 6
8 2 9
2 3 4
2 4 3
here is my code:
class TestClass {
public static void main(String args[]) throws Exception {
Scanner scanner = new Scanner(System.in);
int testCases = scanner.nextInt();
int arr[][]=new int[testCases][3];
int count=0;
for (int i = 0; i < testCases; i++) {
for (int j=0;j<3;j++){
arr[i][j]=scanner.nextInt();
}
}
int result[] =new int[testCases];
for (int i = 0; i < testCases; i++) {
for (int j = 0; j < 3; j++) {
result[i] = arr[i][j]+arr[i][j+1]; //possible error
}
}
for (int i=0;i<testCases;i++){
for (int j=i+1;j<testCases;j++) { //possible error
if (result[i]!=result[j]){
count++;
}
}
}
System.out.println(count);
}
}
error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
at P1.TestClass.main(Solution.java:21)
how to correct the loops so as to not get the errors(note there maybe other errors than the one's i have highlighted) also some better ways of solving this problem are appreciated.
Your program has an ArrayIndexOutOfBoundException in the line result[i] = arr[i][j]+arr[i][j+1];. And I am not sure your second set of nested loops achieve what you want (Summing the triangles). Here is something that can work.
class TestClass {
public static void main(String args[]) throws Exception {
Scanner scanner = new Scanner(System.in);
int testCases = scanner.nextInt();
int arr[][]=new int[testCases][3];
int count=0;
for (int i = 0; i < testCases; i++) {
for (int j=0;j<3;j++){
arr[i][j]=scanner.nextInt();
}
}
//This section sums each set of three
int result[] =new int[testCases];
for (int i = 0; i < testCases; i++) {
for (int j = 0; j < 3; j++) {
result[i] += arr[i][j];
}
}
//This section counts values that are not duplicated
for (int i=0;i<testCases;i++){
boolean hasDuplicate = false;
for (int j=0;j<testCases;j++) {
if (i == j) continue; //skip comparison of value against itself
if (result[i]==result[j]){
hasDuplicate = true; //duplicate found
}
}
if (!hasDuplicate) count++;
}
System.out.println(count); //display number of unique entries
}
}
I don't want to be doing any homework for you, so I'll give you some pointers. Try not to have a look at a solution I have come up with below before trying it yourself again though.
I'd use an ArrayList to store the test data given to you. They're really useful and Java has great support for them.
result[i] = arr[i][j]+arr[i][j+1]; This breaks because j+1 will always be one over the final index of your array.
You can sort strings alphabetically using Arrays.sort which will make comparing triangles much easier, as possible combinations will all end up the same.
Collections.frequency will tell you how many times an element appears in your ArrayList.
My solution certainly isn't the best, and uses more advanced things as apposed to just arrays and booleans, but it works and produces the right answer at the end. It shows that you can solve problems in many different ways!
public static void main(String[] args) {
ArrayList<String> triangleArray = new ArrayList<String>();
Scanner scanner = new Scanner(System.in);
int uniqueTriangles = 0;
// Ask for input, and store in a string that remove all whitespace
System.out.print("Enter triangle sides in format abc separated by a comma:");
String input = scanner.nextLine().trim().replaceAll("\\s", "");
triangleArray.addAll(Arrays.asList(input.split(",")));
// For each item, check it is three characters, and if so, reorder them in
// ascending order i.e 726 => 267
for (int i = 0; i < triangleArray.size(); i++) {
if (triangleArray.get(i).length() != 3) {
triangleArray.remove(i);
}
// Split the triangle string into a character array and sort 'alphabetically'
char[] charArray = triangleArray.get(i).toCharArray();
Arrays.sort(charArray);
triangleArray.set(i, new String(charArray));
}
// Now go through them all again and see if any are unique
for (String s : triangleArray) {
if (Collections.frequency(triangleArray, s) < 2) {
uniqueTriangles++;
}
}
System.out.println(uniqueTriangles);
}

Reverse Array (HackerRank) [duplicate]

This question already has answers here:
How do I reverse an int array in Java?
(47 answers)
Closed 3 years ago.
Am I leaning in the right direction with my code? I'm currently working on hacker rank and am on the easy section of data structures yet I still am confused about how to reverse this array!
Out of all my attempts, I like these two that I did. Check it out.
one attempt:
two attempts:
You can reverse array in two ways
Either by fetching elements from last to start index and putting elements into new array
for example
int[] b = new int[n];
for(int i = n-1; i>=0 ; i--){
n[i] = arrayTobeReverse[i];
}
for more you can visit : https://www.geeksforgeeks.org/reverse-an-array-in-java/
By using Collection.reverse() method first you have to convert array into List using Arrays.asList(array) you can create List using array and then reverse the List.
for example :
import java.util.*;
public class ReverseDemo
{
public static void main(String[] args)
{
// Let us create a list of strings
List<String> mylist = new ArrayList<String>();
mylist.add("practice");
mylist.add("code");
mylist.add("quiz");
mylist.add("geeksforgeeks");
System.out.println("Original List : " + mylist);
// Here we are using reverse() method
// to reverse the element order of mylist
Collections.reverse(mylist);
System.out.println("Modified List: " + mylist);
}
}
You should be walking down the input array, then populating the target array in the opposite direction:
public static int[] reverseArray(int[] a) {
int[] b = new int[a.length];
for (int i=0; i < a.length; ++i) {
b[i] = a[a.length-i-1];
}
return b;
}
Just for fun, here is way to reverse the order of an original array, without using any extra storage:
// give input int[] a
for (int i=0; i < a.length / 2; ++i) {
a[i] = a[a.length-i-1];
}
Note that this approach just walks down half of the array, and swaps elements about the median.

Implentation of a Selection Shuffle in Java [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 4 years ago.
public static void selectionShuffle(int[] values) {
Random rand = new Random();
for(int i = values.length; i > 0; i--) {
int r = rand.nextInt(i);
swap(values, r, i);
}
//updated answer to include below method
public static void swap(int[]a, int i, int j){
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
I am writing a card game and need to randomly sort the cards in place, I got an ArrayOutOfBoundsException when I ran the above code, with the compiler complaining particularly about the reassignment from values[i] = values[r] . To be clear, this is , not intended to be a selection sort but instead a selection shuffle. Any help is appreciated!
Alternatively, you may try Collections.shuffle() but it would be more handy if you have to use the wrapper class Integer instead of the primitive type intat first.
Integer[] version:
public static void selectionShuffle(Integer[] values) {
Collections.shuffle(Arrays.asList(values));
}
int[] version:
public static void selectionShuffle(int[] values) {
Integer[] boxedArr = Arrays.stream(values).boxed().toArray( Integer[]::new );
Collections.shuffle(Arrays.asList(boxedArr));
for(int i=0 ; i<values.length ; i++){
values[i] = boxedArr[i];
}
}
Your start condition needs to be values.length-1, as Java arrays are 0 to length-1.
Also the test should be >=0, since as you wrote it'll only go down to index 1.
for(int i = values.length - 1; i >= 0; i--) {
Or as pointed out by Iłya Bursov, you could compare at index i-1 and leave your for loop conditions as you have them. Not sure what's the best form I always do it as in my example above.
Also, you aren't shuffling. You set the value at index i to the one at r, but you lost the value that was previously at i. You need a temp variable to swap the values.
tmp = values[i];
values[i] = values[r];
values[r] = tmp;

Array with 10 different random elements with no duplicate

im trying to make an array of 10 different elements with Random(), so basically i have this
public static int[] RandomArray (int xArra[]) throws java.io.IOException {
Random Rand = new Random();
int nal;
for (int i = 0; i < xArra.length; i++) {
nal = Rand.nextInt(11); /*I would like to make this thing work with any
numbers, for example, changing this to 50 or 100.
In an array of 10 elements it should be
impossible to have a duplicate because with
11 it just prints from 1 to 10.
Thats why i put 11 here. */
for ( int j = 0; j < xArra.length; j++) {
if (nal == xArra[j]) {
nal = Rand.nextInt(11);
j=0;
}
}
xArra[i] = nal;
}
return xArra;
}
Basically im storing a random number in nal and I run my array in a second For to check
this random number with the already given ones, and if its equal to any number given in the array it changes it with random again, and runs the For again checking that the new number isnt duplicated, if its not, I stored in xArra[i].
When i run it 3 times, the results look like this:
First run:
8
1
6
4
3
2
10
8
9
7
Second run:
9
3
8
10
7
1
4
5
9
6
Third run:
3
5
2
3
6
7
1
4
10
9
So, as you can see i almost though i had it but it duplicates just 1 number, no 2 or 3, so basically i just want to make this thing work. I just want to print 10 random numbers with no duplicate, no repeats.
Heres my full code:
import java.io.*;
import java.util.*;
public class ArraynoR {
public static void main (String[] args) throws java.io.IOException {
int Array[]= new int [10];
RandomArray(Array);
for(int i=0; i<Array.length; i++){
System.out.println("Array[" + (i + 1) + "]:" + Array[i]);
}
}
public static int[] RandomArray (int xArra[]) throws java.io.IOException... //up
}
Please forgive my bad english, I hope I explained myself.
Thanks!
Instead of storing and searching for duplicates, create an ArrayList containing the numbers in the range of interest. Use Collections.shuffle() to randomize the values, then select however many you want from the shuffled set. Guaranteed to give no duplicates, and much more efficient than a search/reject approach.
ADDENDUM
Perhaps not the prettiest code, but it works and gives the idea...
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
public class ShuffleDemo {
public static int[] RandomArray(int len) {
ArrayList<Integer> al = new ArrayList<Integer>(len);
for(int i = 1; i <= len; ++i) { // initialize the ArrayList with values 1 to len
al.add(i);
}
Collections.shuffle(al); // shuffle to random order
int[] results = new int[len];
// switching return type to ArrayList could eliminate the following loop
for(int i = 0; i < len; ++i) { // copy to array of ints
results[i] = al.get(i); // note: create a subset by reducing
} // the upper bound for this loop
return results;
}
public static void main(String[] args) {
System.out.println(Arrays.toString(RandomArray(10)));
}
}
Set j=-1 when you are resetting for the inner for loop and try it. Then it should work
for ( int j = 0; j < xArra.length; j++) {
if (nal == xArra[j]) {
nal = Rand.nextInt(11);
j=-1;
}
}
At the end of the for loop the loop increments the variable so when you set it to 0, before the next check it becomes 1 due to the internal code of the for loop
you can use the method nextPermutation of the class org.apache.commons.math3.random.RandomDataGenerator (see help here docs) in Apache Math. This method generate random numbers without repetition.

Categories