Java run-time error - java

I am running this code:
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
class Ideone
{
public static int solution(int X, int[] A) {
int[] myNumbers = new int[X];
for (int i = 0; i < A.length; i++){
myNumbers[A[i]] = A[i];
}
return -1;
}
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
int[] A = {1,3,1,4,2,3,5,4};
System.out.println(solution(5,A));
}
}
However, I get a run-time error. I don't know why. I need to store the value of the array in A in another array with that value as an index. I.e myNumbers[4] = 4.

myNumber indexes goes from 0 to 4, at some point you are trying to access the index 5 which does not exist
So either pass 6 to solution or use myNumber[A[i]-1] (so myNumber[0] = 1)

Related

Java for loop where values jump

If I have three variables and I want a value in a for loop to jump from one to the next, how would I do that? You can assume the first variable is the smallest and the third is the biggest, and that the variables are not equal to one another(although if there is a way to do it where they are equal that would be good).
I have an example for if it was only two values.
int val1 = 5;
int val2 = 9;
for(int i = val1; i <= val2; i=i+(val2-val1) {
}
In this case i would first be 5, and then 9. Also, is there any way to do it with a different amount of variables?
I'm not 100% certain I understand your question, but you could do
for(int i = val1; i <= val2; i = (i == val1) ? val2 : val2+1) {
// ...
}
If you need more values, I would put them in an array and use a for-each loop over that
int[] vals = {5,9,17};
for (int i : vals) {
// ...
}
you can place those in an array and access to it by index
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
int[] myArray = {4, 6 , 9};
for(int x : myArray)
{
System.out.println(x);
}
//or....
for(int x =0; x<3; x++)
{
System.out.println(myArray[x]);
}
}
}
As #Gonen I said, you can handle this using stream. If you want '...the first variable is the smallest and the third is the biggest...' you should use stream.sorted() to get sorted values.
x corresponds to each one element of the vals list while traversing. So you can do whatever you want in the forEach block with using x
List<Integer> vals = Arrays.asList(5,9,17);
vals.stream().sorted().forEach(x -> {
System.out.println(x);
});
If we are already being a bit silly, this will do the trick for as many values as you want, and inside a for loop. But I would never actually write code like this because its completely unreadable:
package package1;
public class SillySkip {
public static void main(String[] args) {
for( int data[] = {5,10,-4}, i, j=0; j < data.length && (i = data[j]) % 1 == 0 ; ++j )
{
System.out.println(i);
}
}
}
From Java 8 and up you can use Stream.of to iterate arbitrary values like this:
package package1;
import java.util.stream.Stream;
public class IterateSomeValues {
public static void main(String[] args) {
Stream.of(5,10,-4).forEach(e->System.out.println(e));
}
}

Java ArrayIndexOutOfBounds Error For Array That Shouldn't Be Going Off Bounds

Here is my code:
public class Test {
static private int arraySize;
public Test(int arrayS){
arraySize = arrayS;
}
int []ma = new int[arraySize];
public static void main(String[] args){
}
public void increment(){
int count = arraySize - 1;
ma[count - 1] += 1;
while(count!= 0){
if(ma[count] > 9){
ma[count] =0;
ma[count - 1] +=1;
}
count -=1;
}
if(ma[0] > 9){
ma[0] = 0;
}
}
}
class Trial
{
public static void main(String[] args)
{
Test z = new Test(2);
System.out.println(z);
z.increment();
System.out.println(z);
}
}
There is a class called test and another called trial. Whenever the main method inside of Trial attempts to build test which has an array there is an index out of bounds exception that comes up. What could be the reason behind this?
First of all there is no any parameterised constructor in your Test class. How you create object using new Test(2);
Secondly you initialize globally int []ma = new int[arraySize];
This time arraySize having value zero.
Put ma=new int[arraySize]; in your constructor after you set value of arraySize by arrayS value
Since arraySize is a static instance variable, it will be initialized to 0 when your program is started and hence the ma has a size of 0
That is why when you access ma[0] you get an error
To resolve it, you need to initialize ma in your constructor
static private int arraySize;
public Test(int arrayS){
arraySize = arrayS;
ma = new int[arrayS];
}
int []ma;
You initialize arraySize and ma inline. So arraySize is initialized with 0 (not NULL) and then your array gets initialized with a capacity of 0. You should initialize your array within the constructor.

Chose amount of parameters to call in a method?

While I was attempting to make a method that runs calculations and returns the binary value for a small project I'm working on; I was trying to have the method parameters include all of the values to add together, but when doing so I realized I don't know how to do so without using an array of some sort.
Is it possible to have the parameters in the following method addBinary change based on the amount I wish to add?
public int addBinary() // I want these parameters to have all integers I wish to add
{
// Calculations go here //
}
Essentially, if I wish to run the program and add 5 values the first time and 25 the next; how would I get all of the values into the method without creating an array?
You can use variable number of arguments in the method definiton(using ellipses i.e ... ) like this:
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static int add(int ...arr)
{
int sum=0;
for(int i=0;i<arr.length;i++)
sum+=arr[i];
return sum;
}
public static void main (String[] args) throws java.lang.Exception
{
System.out.println(add(1, 2, 3, 4));
System.out.println(add(1, 2, 3));
}
}
Output:
10
6
https://ideone.com/PHL8Lb
I don't know why you are not thinking of using arrays here. Just pass an array as a parameter and do the calculations you want to do.
public int addBinary(int a[])
{
for(int i=0;i<a.length;i++)
sum+=a[i];
return sum;
}
Or by using an arraylist
public int addBinary(ArrayList m)
{
int sum = 0;
for(i = 1; i < m.size(); i++)
sum += m.get(i);
return sum;
}
Link for the code Ideone
You can use varargs for this
void testapp(String ...studentsName){
for (int i = 0; i < studentsName.length; i++) {
System.out.println(studentsName[i]);
}
}

How do I fix this array output?

I'm making a histogram program in which I have one array that generates a random number, another that makes them into an array, and a last one that attempts to use that array and tell how many characters are in each [] of the array. My problem is that I cannot find a way to count how many characters are in each array element and outprint it. I'm trying to use the .length function but it doesn't seem to be working. Is there another way that I could do this?
Here is my code. My problem is with my last method, before my main method.
package arrayhistogram;
/**
*
* #author Dominique
*/
public class ArrayHistogram {
public static int randomInt(int low, int high){
double x =Math.random ()* (high - low)+low;
int x1=(int)x;
return x1;
}
public static int[] randomIntArray(int n){
int[] a = new int[n];
for (int i=0; i<n; i++) {
a[i] = randomInt(-5, 15);
}
return a;
}
public static int[] arrayHist () {
int[] x=randomIntArray(30);
for (int i = 0; i < x.length; i++) {
System.out.println(x[i].length);
}
return x;
}
public static void main(String[] args) {
arrayHist();
}
}
Replace
System.out.println(x[i].length);
with
System.out.println(Integer.toString(x[i]).length());
There is no length property on an int. You can use this to get the number of digits in the int.
String.valueOf(x[i]).length()
This first transforms the int into a String and then returns the length of that String. E.g 123 => "123", whose length is 3.

I don't understand the program

I wanted a program which could list all the contents available in a directory. I found a nice code in java2's.com,
http://www.java2s.com/Code/Java/File-Input-Output/ListingtheDirectoryContents.htm
And here is the code,
import java.io.File;
import java.util.Arrays;
public class Dir {
static int indentLevel = -1;
static void listPath(File path) {
File files[];
indentLevel++;
files = path.listFiles();
Arrays.sort(files);
for (int i = 0, n = files.length; i < n; i++) {
for (int indent = 0; indent < indentLevel; indent++) {
System.out.print(" ");
}
System.out.println(files[i].toString());
if (files[i].isDirectory()) {
listPath(files[i]);
}
}
indentLevel--;
}
public static void main(String args[]) {
listPath(new File(".\\code"));
}
}
What I don't understand is the variable n in the first for loop. If it is not defined anywhere, then why is the program not showing any error?
int i, n;
would declare two ints.
In the code
int i = 0, n = files.length;
declares and initialises them.
It's declared right there, as an int. The comma separates the multiple variable declarations.
n is defined in the for loop in the same way as i.
int x,y;
Would define two variables x and y both as ints. the comma in the for with assignments just looks more complex.

Categories

Resources