java.lang.ArrayIndexOutOfBoundsException inside for loop - java

Whenever I run my code, it says Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0. I make sure that my I value isn't exceeded but it still says it. Can you guys help me?
I made sure that nothing in my for loop exceeded my I value but it seems to be something else that is triggering the problem.
And by the way, sorry if my formatting is incorrect. This is my first time using stack overflow.
One more thing, my compiler says that the error is in line 17(inside my for loop).
Here's my code:
import java.io.*;
public class Main {
public static int length1;
public static String numbers;
public static String str;
public static void main(String[] args)throws IOException{
System.out.println("");
System.out.println("Hello world!");
char[] nums = new char[length1];
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Type in numbers with spaces in them.");
numbers = br.readLine();
System.out.println("");
for(int i = 0; i < numbers.length(); i++){
nums[i] = numbers.charAt(i);
System.out.println(numbers.charAt(i));
}
length1 = numbers.length();
}
}

so your problem is at this line...
char[] nums = new char[length1];
length1 is does not have a value.
Try This...
import java.io.*;
public class Main {
public static int length1;
public static String numbers;
public static String str;
public static void main(String[] args) throws IOException {
System.out.println("");
System.out.println("Hello world!");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Type in numbers with spaces in them.");
numbers = br.readLine();
char[] nums = new char[numbers.length()];
System.out.println("");
for (int i = 0; i < numbers.length(); i++) {
nums[i] = numbers.charAt(i);
System.out.println(numbers.charAt(i));
}
}
}

Related

HackerRank says ~ no response on stdout ~

So I was solving this Question on HackerRank (Project Euler Q1) link here, and have used the following code to solve it
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
int T = 0;
ArrayList<Integer> N = new ArrayList<Integer>();
String[] Input = args;
if (args.length>1){
T = Integer.parseInt(args[0]);
if(T<1||T>Math.pow(10,6))
System.exit(0);
}
if (args.length-1 == T){
for (int i=1;i<args.length;i++){
N.add(Integer.parseInt(args[i]));
int sum3=0,sum5=0,sum15=0;
int count=0;
while (count<N.get(i-1)){
sum3+=count;
count+=3;
}
count =0;
while (count<N.get(i-1)){
sum5+=count;
count+=5;
}
count =0;
while (count<N.get(i-1)){
sum15+=count;
count+=15;
}
N.set(i-1,(sum3+sum5-sum15));
}
}
for(int j=0;j<N.size();j++)
System.out.println(N.get(j));
}
}
This gives me the following output on an IDE :
23
2318
While Inputting :
2
10
100
And this matches the expected output on HackerRank, but however When I use this code on the website, It says :
Input (stdin)
2
10
100
Your Output (stdout)
~ no response on stdout ~
Expected Output
23
2318
Compiler Message
Wrong Answer
One thing I could observe was I couldn't print anything from inside a loop on HackerRank. What would the solution to this be?
You're not reading from STDIN the way HackerRank wants you to. Instead of getting your input from args, you should be doing this kind of thing:
Scanner sc = new Scanner(System.in);
int numberOfTestCases = sc.nextInt();
and so on.
I just ran this code, compiled fine and submitted it.
import java.io.*;
public class Solution{
public static void main(String[] args) throws IOException
{
//Input
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine());
int[] N = new int[T];
for(int t = 0; t < T; N[t++] = Integer.parseInt(br.readLine())){
}
br.close();
br = null;
//Solve
long[] V = new long[T];
for(int t = 0; t < T; ++t){
int n = N[t] - 1;
V[t] = 3*nSum(n/3) + 5*nSum(n/5) - 15*nSum(n/15);
}
//Print
StringBuilder sb = new StringBuilder();
for(int t = 0; t < T; sb.append(V[t++]).append("\n")){
}
System.out.print(sb);
}
public static long nSum(int n){
long v = n;
return (v*v + v) >> 1;
}
}
I had the same problem with a php code and I used return instead of echoing for your case replace sout with return

Getting NZEC error in SPOJ with Java for this Code

This is my answer for half of half question in SPOJ( Question ID :12156) . I'm a beginner in JAVA. Please Help why am i getting an error. I'm able to get an expected answer while compiling in Ideone. Thanks
import java.util.*;
import java.lang.*;
import java.io.*;
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner scan =new Scanner(System.in);
String[] name= new String[10];
int size,count;
String temp,news;
char[] chars= new char[20];
temp=scan.nextLine();
count=Integer.parseInt(temp);
for(int i=0;i<count;i++)
{
name[i]=scan.nextLine();
}
for(int j=0;j<count;j++)
{
news=name[j];
size=news.length();
chars=news.toCharArray();
for(int k=0;k<size/2;k=k+2)
{
System.out.print(chars[k]);
}
System.out.println();
}
}
}
Pay attention to the following points in the problem description:
In the first line of input your are given the positive integer t
(1 <= t <= 100) - the number of test cases.
In your code, you can handle 10 (and not 100) strings at maximum.
String[] name = new String[10];
In the each of the next t lines, you are given a sequence of 2*k
(1 <= k <= 100) characters.
In your code, you can handle 20 (and not 200) characters at maximum.
char[] chars = new char[20];
I did attempt same question half of half at SPOJ, my code is accepted.
I think array initialisation should be based on input.
import java.util.Scanner;
class Main {
public static void main(String[] args) throws java.lang.Exception {
Scanner scan = new Scanner(System.in);
int testCase = scan.nextInt();
scan.nextLine();
String[] inputStringArray = new String[testCase];
for (int x = 0; x < testCase; x++) {
String input = scan.nextLine();
input = input.replaceAll("\\s+", "");
inputStringArray[x]=input;
System.out.println("#-"+x);
}
for(int y=0;y<testCase;y++){
String text = inputStringArray[y];
char[] inputArray = text.toCharArray();
int len = inputArray.length/2;
for(int z=0;z<len;z=z+2){
System.out.print(inputArray[z]);
}
System.out.println("");
}
}
}

NumberFormatException when reading from System.in

I am getting these exception while running the code
Exception in thread "main" java.lang.NumberFormatException: null
at java.lang.Integer.parseInt(Integer.java:542)
at java.lang.Integer.parseInt(Integer.java:615)
at Ideone.main(Main.java:22)
I am new at java and unable to resolve this error. Please help !
Here is my code ->
import java.util.*;
import java.lang.*;
import java.io.*;
class etest {
public static void main (String[] args) throws java.lang.Exception{
int n,k;
Scanner in = new Scanner(System.in);
n = in.nextInt();
k = in.nextInt();
BufferedReader input = new BufferedReader( new InputStreamReader(System.in));
//StringTokenizer token = new StringTokenizer(input.readLine());
int total=0;
int values[] = new int[n];
for(int i =0; i<n; i++) {
values[i] = Integer.parseInt(input.readLine());
if ((values[i]%k)==0) {
total++ ;
}
input.close();
}
System.out.println(total);
}
}
I am using the following input sample to run the program.
Thank you so much for any help!
7 3
1
51
966369
7
9
999996
11
your program has too many errors :
You can change your code as below
public static void main(String[] args) throws java.lang.Exception {
int n, k;
Scanner in = new Scanner(System.in);
n = in.nextInt();
k = in.nextInt();
int total = 0;
int values[] = new int[n];
for (int i = 0; i < n; i++) {
values[i] = in.nextInt();
if ((values[i] % k) == 0) {
total++;
}
}
System.out.println(total);
}
1) you should not close BufferedReader it will automatically close input stream also.
2) you don't need Scanner and BufferedReader at the same time. your solution can use any one of them.
3) better to use try-catch while using Integer.parseInt(String str);
if you want to go with BufferedReader then you need to change your code as
public static void main(String[] args) throws java.lang.Exception {
int n, k;
BufferedReader input = new BufferedReader( new InputStreamReader(System.in));
String str[]= input.readLine().split(" ");
n = Integer.parseInt(str[0]);
k = Integer.parseInt(str[1]);
int total = 0;
int values[] = new int[n];
for (int i = 0; i < n; i++) {
values[i]=Integer.parseInt(input.readLine());
if ((values[i] % k) == 0) {
total++;
}
}
System.out.println(total);
}

Java, basic array error

I am trying to do a Java program that will let me input 10 words, and then the words should be repeated in reverse order (the last first etc).
This is my current code:
import java.util.Scanner;
import java.lang.String;
public class Words {
public static void main(String[] args){
String word[] = {};
for(int x = 0; x < 10; x+=1) {
System.out.println("Input any word");
Scanner input = new Scanner(System.in);
word = new String[] { input.next() };
}
for(int y = 9; y >= 0; y-=1) {
System.out.println(word[y]);
}
}}
It gives me the following error when trying to compile:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9 at Words.main(Words.java:21)
I am new to Java and would appreciate help, thanks in advice.
That's not how arrays work.
Change String word[] = {}; to String word[] = new String[10];
Also, change word = new String[] { input.next() }; to word[x] = input.next().
It is also a good idea to move Scanner input = new Scanner(System.in); outside of the for loop. You should read up on how arrays work to make sure this doesn't happen again.
You could try use an ArrayList to do this like so:
import java.util.*;
public class HelloWorld
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
ArrayList al = new ArrayList();
do{
System.out.println("Enter word");
String word = sc.nextLine();
al.add(word);
if(al.size()==10){
System.out.println("Words in reverse order");
for(int i = al.size()-1; i>= 0; i--){
System.out.println(al.get(i));
}
}
}while(al.size()<10);
}
}
I think this answers your question properly.
All the best
Sean

Permutations of a string

public class Permute {
public static void main(String[] args) throws IOException {
System.out.println("Enter a string");
BufferedReader bufReader = new BufferedReader(new InputStreamReader(System.in));
String text = bufReader.readLine();
shuffle("",text);
}
public static void shuffle(String dummy, String input){
if(input.length() <= 1)
System.out.println(dummy+input);
else{
for(int i=0; i <input.length();i++){
input = input.substring(i,1) + input.substring(0,i) + input.substring(i+1);
shuffle(dummy+input.substring(0,1),input.substring(1));
}
}
}
}
Am trying to print all the permutations of a string entered. And I really cannot guess where am going wrong because on paper I find that this executing. Where exactly am going wrong.
Try change your shuffle:
public static void shuffle(String dummy, String input){
if(input.length() <= 1)
System.out.println(dummy+input);
else{
for(int i=0; i <input.length();i++){
shuffle(dummy+input.charAt(i), input.substring(0, i) + input.substring(i+1, input.length()));
}
}
}
public class Permute {
public static void main(String[] args) throws IOException {
System.out.println("Enter a string");
BufferedReader bufReader = new BufferedReader(new InputStreamReader(System.in));
String text = bufReader.readLine();
shuffle("",text);
}
public static void shuffle(String dummy, String input){
if(input.length() <= 1)
System.out.println(dummy+input);
else{
for(int i=0; i <input.length();i++){
input = input.substring(i,i+1) + input.substring(0,i) + input.substring(i+1);
shuffle(dummy+input.substring(0,1),input.substring(1));
}
}
}
}
It should be input.substring(i,i+1) instead of input.substring(i,1). Because each time I need only 1 character to be constant, which is at the beginning of the string and others have to be jumbled.
The bug was I presumed the functionality of substring to be substring(beginIndex, length). But it is substring(beginIndex,endIndex).
#Oli: Thank you for the help.
Since this seems like a homework assignment I once did I will help you out here. You will need two loops, one inside the other.
for(int i;i<something;i++)
for(int j;j<somethingElse;j++)
This will enable you to generate the permutations that are required.
Replace two lines in the for loop with following:
String partString = input.substring(0, i) + input.substring(i + 1);
shuffle(dummy + input.charAt(i), partString);
Since this looks like your homework I will let you figure out. If not, will post explanation after a bit ( got to get back to my day job ;) )

Categories

Resources