Java-ArrayIndexOutOfBoundsException Error - java

When i run the following program I get an error at line 20, and this is my code:
package J1;
import java.util.Scanner;
public class SpeedLimit {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int input = keyboard.nextInt();
String[] tab = new String[2];
String output="";
int speed = 0;
while(input!=-1){
int last =0;
for (int i=0; i<input ; i++){
String pair = keyboard.next();
tab = pair.split(" ");
speed = speed + Integer.parseInt(tab[0])*(Integer.parseInt(tab[1])-last);
last = Integer.parseInt(tab[1]);
}
output = output +speed + "miles" + "\n";
speed =0;
input = Integer.parseInt(keyboard.nextLine());
}
System.out.println(output);
}
}
when i run the code, I enter the following input from the keyboard:
3
20 2
30 6
10 7
2
60 1
30 5
4
15 1
25 2
30 3
10 5
-1
to get this result as an output:
170 miles
180 miles
90 miles
but i get the following Error when i run the code
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at J1.SpeedLimit.main(SpeedLimit.java:20)

String pair = keyboard.next(); This reads only one token which are separated by " " so when you split pair by " ". It will only have one element, The String itself. So you need to read the whole line and then split it by delimited " ".
Another mistake is that when you change that line with String pair = keyboard.nextLine(); , You will still get error because System considers Enter key as input of .nextLine() method. So you need to discard that extra unnecessary input.
while(input!=-1){
int last =0;
for (int i=0; i<input ; i++){
int ip1=keyboard.nextInt();
int ip2=keyboard.nextInt();
speed = speed + ip1*(ip2-last);
last = ip2;
}
output = output +speed + "miles" + "\n";
speed =0;
input = keyboard.nextInt();
}

You are reading the variable pair the wrong way and then you split it and assign it to tab which fails to automatically to fetch index cause pair variable got a problem.
*nextLine(): reads the remainder of the current line even if it is empty.
keyboard.nextLine(); //To avoid the exception you commented
String pair = keyboard.nextLine(); //here is solved
tab = pair.split(" ");

Keyboard.next() will only read the input till the space, so pair and the array will have only one number, so tab[1] results in arrayOutOfBound exception. Use the method nextLine() to read the inputs with space.

You Can try below changes in your code :
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int input = Integer.parseInt(keyboard.nextLine());
String[] tab = new String[2];
String output="";
int speed = 0;
while(input!=-1){
int last =0;
for (int i=0; i<input ; i++){
String pair = keyboard.nextLine();
tab = pair.split(" ");
speed = speed + Integer.parseInt(tab[0].trim())*(Integer.parseInt(tab[1].trim())-last);
last = Integer.parseInt(tab[1]);
}
output = output +speed + " miles " + "\n";
speed =0;
input = Integer.parseInt(keyboard.nextLine());
}
System.out.println(output);
}

i did'n really understand how you are providing the inputs. but, if "3" happens to be your first line then split(" ") would return an array of length 1. thus, tab[0] would return 3 and tab[1] will give you a nullPointerException.
try adding an check for the length of tab before executing your line 20.
this should do the trick:
if(tab.length() > 1){
speed = speed + Integer.parseInt(tab[0])*(Integer.parseInt(tab[1])-last);
}

Related

java.lang.NumberFormatException error after inputting a number [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 2 years ago.
I am feeling quite stupid at this point for not being able to figure out something that is most likely a simple fix. I keep getting the error "Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
at java.base/java.lang.Integer.parseInt(Integer.java:662)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at searchSorting.main(searchSorting.java:15)" after inputting how many numbers I want to input. Others solutions to this problem just don't seem to apply to me somehow. Thanks for the help
import java.util.Scanner;
import java.util.Arrays;
public class searchSorting
{
public static void main (String[]args)
{
String line;
int number, search, item, array[], first, last, middle;
Scanner in = new Scanner(System.in);
System.out.print("How many numbers you want to input?: ");
number = in.nextInt();
array = new int [number];
item = Integer.parseInt(in.nextLine());
double[] values = new double[item];
for (int i = 0; i < values.length; i++) {
System.out.print("Input number " + i + ": ");
values[i] = Double.parseDouble(in.nextLine());
}
for (int index = 0; index < 5; index++)
System.out.print(values[index] + " ");
in.nextLine();
Arrays.sort(values);
System.out.println("Sorted number is: " + Arrays.toString(values));
System.out.println("Enter the number you are looking for?");
search = in.nextInt();
first = 0;
last = (item - 1);
middle = (first + last)/2;
while( first <= last )
{
if ( array[middle] < item )
first = middle + 1;
else if ( array[middle] == item )
{
System.out.println(item + " found at location " + (middle + 1) + ".");
break;
}
else
{
last = middle - 1;
}
middle = (first + last)/2;
}
if ( first > last )
System.out.println(item + " is not found.\n");
}}
For more info check out Scanner and Integer documentation, it's an excellent resource.
Edit: Try removing line 15 and replacing item with number in the next line
You call this:
number = in.nextInt();
Assuming the user types 123 and ENTER, this call consumes the 123 and leaves the input stream positioned before the end-of-line character.
The next relevant code is
item = Integer.parseInt(in.nextLine());
The nextLine call advances the input stream past the end-of-line, returning all characters it passed on the way. Since the ENTER key was pressed immediately after 123, the returned value is the emoty string. Which is not an integer.
You need to review your strategy of sometimes scanning numbers (nextInt) and sometimes scanning rest-of-linr (nextLine). Mixing the two needs to be done quite carefully. You might be better advised to stick to the numerical methods (nextInt/nextDouble).
For example, replacing this
item = Integer.parseInt(in.nextLine());
by this
item = in.nextInt();
automatically handles the line-ending.
From discussion in comments:
I am still confused as to why it's having me input
the value a second time on the next line
Making assumptions about how you modified the code since your initial question: it's because you've written code that reads the number twice:
System.out.print("How many numbers you want to input?: ");
number = in.nextInt(); // **** first input ****
array = new int [number];
item = in.nextDouble(); // **** second input ****
double[] values = new double[item];
Each time you call for in.nextSomething() the Scanner is going to read more input. It should likely just be this:
System.out.print("How many numbers you want to input?: ");
number = in.nextInt();
array = new int [number];
double[] values = new double[number];

Rearranging numbers using variable.charAt(). Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range:

I have looked on other such answers with this error and I can't seem to figure out my code specifically. I am using Java, and I am trying to make a program where I enter a number as an input, and as an output I should get:
example input: 1234
The original number is 1234
The number in reverse is 4 3 2 1
I have this code written:
import java.util.Scanner; //Needed for Scanner class
public class CoeQuiz3
{
public static void main(String[] args)
{
//establish variables
String ogNumber;
int ogNumberInt;
Scanner keyboard = new Scanner(System.in); //establish scanner
System.out.println("Enter a positive integer greater than 0.");
ogNumber = keyboard.nextLine();
ogNumber = checknumber(ogNumber);
ogNumberInt = Integer.parseInt(ogNumber);
//print the original number
System.out.println("The original number is " + ogNumber);
//print the reverse number
int ogNumberLength = ogNumber.length();
int digitposition, ogDigit;
String reverseStatement = "The number reversed is ";
for (digitposition = ogNumberLength; digitposition >= 0;
digitposition--)
{
ogDigit = ogNumber.charAt(digitposition);
reverseStatement += ogDigit + " ";
}
System.out.println(reverseStatement);
it compiles and runs, but every time it gives me the error:
The original number is 1234
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of
range: 4
at java.lang.String.charAt(String.java:658)
at CoeQuiz3.main(CoeQuiz3.java:30)
It should work logically - what is the problem? This problem still occurs if I replace >= with >.
You are trying to access one past the highest available character index in your string. Try this loop instead:
for (int i=ogNumber.length()-1; i >=0; i--) {
char chr = ogNumber.charAt(i);
reverseStatement += chr;
}
System.out.println(reverseStatement);
But a nicer way to do this is to use the StringBuffer.reverse() method:
String ogNumberReversed = new StringBuffer(ogNumber).reverse();
for (int i=0; i < ogNumberReversed.length(); ++i) {
char chr = ogNumberReversed.charAt(i);
reverseStatement += chr;
}
System.out.println(reverseStatement);
Alternative solution:
int number = 1234;
String strReversed = new StringBuilder(String.valueOf(number)).reverse().toString().replace("", " ").trim();
System.out.println(strReversed); // 4 3 2 1
Ideone example
See this piece of code
for (digitposition = ogNumberLength; digitposition >= 0;
digitposition--)
{
ogDigit = ogNumber.charAt(digitposition);
reverseStatement += ogDigit + " ";
}
The first parameter of the loop digitposition = ogNumberLength
specifies that the loop should access the char at the position equal to length of the string, and in case of string, the length is equal to the number of characters (for e.g. length of string "HAPPY" would be 5 not 4). But the index of the last element of the String array is one less than the length of the string (as arrays are zero indexed).
So in practice if you have entered the number "1234":
length of string is = 4
position of last element array = 3
So your code is trying to access the element number 4 in an array of last index 3, hence the exception.
You should instead write the following (notice the -1 in the 1st parameter)
for (digitposition = ogNumberLength - 1; digitposition >= 0;
digitposition--)
{
ogDigit = ogNumber.charAt(digitposition);
reverseStatement += ogDigit + " ";
}
This would solve your problem, however if reversing only numbers is your sole objective then I would suggest use the following method as using strings is much more resource intensive
import java.util.Scanner;
class ReverseNumber
{
public static void main(String args[])
{
int n, reverse = 0;
System.out.println("Enter the number to reverse");
Scanner in = new Scanner(System.in);
n = in.nextInt();
while( n != 0 )
{
reverse = reverse * 10;
reverse = reverse + n%10;
n = n/10;
}
System.out.println("Reverse of entered number is "+reverse);
}
}
Cheers!!!
Please change your for-loop as follows:
for (digitposition = ogNumberLength-1; digitposition >= 0; digitposition--){
ogDigit = Character.getNumericValue(ogNumber.charAt(digitposition));
reverseStatement += ogDigit + " ";
}
and see the results.
There are two things which have been added:
The for loop counter should start from ogNumberLength-1 not
ogNumberLength. This was the reason for
java.lang.StringIndexOutOfBoundsException
There is a need to convert the ASCII value of char to number. That is why
Character.getNumericValue() has been used.
Hope, it helps!

I have a file with 3 columns and 7 rows, I need to make 3 arrays out of each column in the file

I have been trying to figure this out for days and I feel that I am just stuck on something that is so easy from over thinking it. I need to read the file, (contents of what text file looks like are right below)... create 3 arrays out of each column.
My issue is when splitting the String under " " conditions into a String [] Array, takes the last row of my txt and puts that into the new String [] Array, not the entire contents of string that i made from file...
my txt file looks like this...
200 1000 800
450 845 1200
800 250 400
0 1500 1800
600 500 1000
700 1400 1700
675 400 900
my code so far after days of manipulation, deletion, starting over from scratch...all to come to this small piece.
PLEASE HELP ME!!!
import java.io.File;
import java.io.FileNotFoundException;
import java.util.InputMismatchException;
import java.util.Scanner;
public class WeeklyCalorieCount {
public static void main(String[] args) {
try {
File input = new File("Lab1File.txt"); //reads file and names it input to refer back later
Scanner klg = new Scanner(input); //creates scanner that reads the file named input
String [] b = new String [7]; //creating breakfast, lunch and dinner Strings (To Split later)
String [] l = new String [7];
String [] d = new String [7];
String fileLine = null;
System.out.println("TEST 1: Contents of file are as follows: ");
while (klg.hasNextInt()) { //Puts file contents into string
fileLine = klg.nextLine();
System.out.println(fileLine);
}
System.out.println("");
System.out.println("TEST 2 BELOW");
String strArr[] = fileLine.split(" "); //temporary array to hold all numbers and split
for(int i = 0; i < strArr.length; i++){ //Trying to split String into individual elements and put into string array.
System.out.print(strArr[i] + " ");
}
System.out.println("");
System.out.println("--------");
for(int k = 0; k < strArr.length;k++) {
b[k] = strArr[k]; //Assigns contents into 3 arrays
l[k] = strArr[k];
d[k] = strArr[k];
System.out.println(b[k]);
System.out.println(l[k]);
System.out.println(d[k]);
}
OUTPUT:
TEST 1: Contents of file are as follows:
200 1000 800
450 845 1200
800 250 400
0 1500 1800
600 500 1000
700 1400 1700
675 400 900
TEST 2 BELOW
675 400 900
--------
675
675
400
400
900
900
Use a 3x7 matrix and two for loops, saving each int value separately:
File input = new File("Lab1File.txt");
Scanner scanner = new Scanner(input);
int[][] matrix = new int[7][3];
for(int i = 0; i < 7; i++)
{
for(int j = 0; j < 3; j++)
{
matrix[i][j] = scanner.nextInt();
}
}
scanner.close();
After the while loop finishes which has fileLine = klg.nextLine();, fileLine will have only the last line. You are not concatenating the strings.
You are replacing fileLine with the line that you read every time. So you only have the last line after the loop.
You probably need to do:
fileLine = fileLine + " " + klg.nextLine();
instead of:
fileLine = klg.nextLine();
Edit:
You need to initialize String fileLine = ""; with this approach.
Your problems are in :
fileLine = klg.nextLine(); fileLine will have only one line
for(int k = 0; k < strArr.length;k++)
Better you move the code in for loop to the while (klg.hasNextInt()):
int k = 0;
while (klg.hasNextInt()) {
fileLine = klg.nextLine();
System.out.println(fileLine);
String strArr[] = fileLine.split(" ");
b[k] = strArr[0];
l[k] = strArr[1];
d[k] = strArr[2];
k++;
}
Or you can do it the way you initially planned as shown in the runnable below:
package weeklycaloriecount;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
public class WeeklyCalorieCount {
public static void main(String[] args) {
// Declare and initialize string variables to hold
// the values from each column of each file line as
// they are read in.
String colA = "";
String colB = "";
String colC = "";
try {
File input = new File("Lab1File.txt");
Scanner klg = new Scanner(input);
// Read each line of file until the end.
while (klg.hasNextInt()) {
// Place the line read into a String Array
String[] fileLine = klg.nextLine().split(" ");
// Take each element of the array and place them into
// their respective column variable and delimit them
// with a whitespace...
colA+= fileLine[0] + " ";
colB+= fileLine[1] + " ";
colC+= fileLine[2] + " ";
}
klg.close(); // Close the scanner.
}
catch(FileNotFoundException ex) {
// Trap the File Not Found Exception
System.out.println("Whoops! File Not Found!");
}
// Display each String variable...
System.out.println("The colA Variable: " + colA);
System.out.println("The colB Variable: " + colB);
System.out.println("The colC Variable: " + colC);
// You can at this point use each variable (colA, colB, and colC)
// as your separated columns or you can place the contents of each
// variable and place them into individual arrays as done below...
String[] b = colA.trim().split(" ");
String[] l = colB.trim().split(" ");
String[] d = colC.trim().split(" ");
// Display our Arrays (b[], l[], and d[])
// Breakfast...
System.out.println("");
System.out.println("The b[] Array: " + Arrays.toString(b));
// Lunch...
System.out.println("The l[] Array: " + Arrays.toString(l));
// Dinner...
System.out.println("The d[] Array: " + Arrays.toString(d));
}
}

Average Word Length

I am attempting to calculate the average word length of user input in Java in a very simplistic way. The actual "math" of the code I've already completed, and it seems to be working quite well, but there are some odd house keeping things I need to address in order to complete the code.
So far, I have the following:
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Please type some words, then press enter: ");
int count = 0;
double sum = 0;
while (sc.hasNext()) {
String userInput = sc.next();
double charNum = userInput.length();
sum = charNum + sum;
count++;
double average = 0;
if (count > 0) {
average = sum / count;
}
System.out.println("Average word length = " + average);
}
}
}
The end result output should look like this:
run:
Please type some words, then press enter:
this is a test
Average word length = 2.75
BUILD SUCCESSFUL (total time: 10 seconds)
However, the output is looking like this:
run:
Please type some words, then press enter:
this is a test
Average word length = 4.0
Average word length = 3.0
Average word length = 2.3333333333333335
Average word length = 2.75
Based on the code that I've written, how can I change it so that:
The "average word length" is only printed one final time.
The program ends after the user presses enter
Thank you for any suggestions.
You're calculating the average every single time you enter a word, which is not what you want. Also, the while loop will continue even if enter is pressed. Try this:
Scanner sc = new Scanner(System.in);
System.out.println("Please type some words, then press enter: ");
int count = 0;
double sum = 0;
String input = sc.nextLine();
String[] words = input.split("\\s+"); // split by whitespace
// iterate over each word and update the stats
for (String word : words) {
double wordLength = word.length();
sum += wordLength;
count++;
}
// calculate the average at the end
double average = 0;
if (count > 0) {
average = sum / count;
}
System.out.println("Average word length = " + average);
Output:
Please type some words, then press enter:
this is a test
Average word length = 2.75
You just need to move your System.out.println after the loop and declare average out of the loop to prevent scope issues. However, it is more elegant to do it this way :
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Please type some words, then press enter: ");
double average = 0;
for (String word : sc.nextLine().split("\\s+"))
average += word.length();
average /= words.length;
System.out.println("Average word length = " + average);
sc.close();
}
}
sc.nextLine() returns the entire line typed by the user (without the last "\n" character) and split("\\s+") splits this line using the regex \s+, returning an array containing the words. This regex means to split around any non-empty sequence of blank characters.
Just get System.out.println(...) out of the while loop. And declare average variable before the loop body.
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Please type some words, then press enter: ");
String words = sc.nextLine();
int count = 0;
double sum = 0;
double average = 0;
sc = new Scanner(words);
while (sc.hasNext()) {
String userInput = sc.next();
double charNum = userInput.length();
sum = charNum + sum;
count++;
if (count > 0) {
average = sum / count;
}
}
System.out.println("Average word length = " + average);
}
A) Print your output outside of the loop when all of the averaging has already been done
B) Use Date.getTime() to get the time at the start of the program after the user has inputted their sentence, and store it in a variable, then at the end of the program, get the time again, subtract it from the old time, and divide by 1000 to convert it from milliseconds to seconds. After that you can just print it out however you want it formatted
C) call sc.readLine() after you have outputted everything so that when they press enter that line will stop blocking and let the program end.

Why is my for loop executing more than once for each time a value is inputted?

I have a programming assignment that's asking me to have the user input 10 (or less) integers and put them in an array, then take the average of them and output it. If they input a period, the program should stop asking for integers and do the averaging.
My problem is that whenever the user inputs an integer, the for loop executes more than once.
My code is below. Any ideas on how to fix this?
int[] intArr = new int[10];
int entered;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
for(entered = 0; entered < 10; entered++){
System.out.println("Please enter an integer: ");
int input = br.read();
if(input == '.') break;
else{
intArr[entered] = input;
}
}
int total = 0;
for(int i : intArr){
total += i;
}
System.out.println("Average: " + total/entered);
System.out.println("Entered: " + entered);
Use String input = br.readLine() to read an entire line.
To check for ".", use if (input.equals(".")) { ... }.
(check out this if you want to know why you have to use .equals() instead of == for Strings)
Finally, to convert the input to an integer, see here.
for (entered = 0; entered < 10; entered++) {
System.out.println("Please enter an integer: ");
String str = br.readLine();
if (".".equals(str)) {
break;
}
int input = Integer.valueOf(str);
intArr[entered] = input;
}
Ok Its Really Simple
First let Me Explain You Why Its Happening
Ok the read() function reads first char of the input value and rest of line is stored in buffer
so when you enter any integer
for example: 1
1 is stored in variable and '\n'which java by defaults adds to a input value gets stored in buffer
so in next iteration of loop
it reads the char '\n' from buffer as input value and moves to next iteration
EXAMPLE 2:
If In Your Program We Enter Input As 12
It Skips Two Iterations
Coz Firstly It Stores 1 At The Time Of Input
In Next Iteration It Takes value 2 of previous input as input for this time
In Further Next Iteration It Takes '\n'
and then moves to next iteration at which their is no character left in memory so it asks you to input
Note:::
read() functions return character so even if user enters 5 while calculation ASCII Code Of 10 will be used that is 53 not one creating problems
FIX:::
int[] intArr = new int[10];
int entered;
BufferedReader br = new BufferedReader(new InputStreamReader(System. in ));
for (entered = 0; entered < 10; entered++) {
System.out.println("Please enter an integer: ");
String input = br.readLine();
if (input.equals(".")) {
break;
} else {
intArr[entered] = Integer.parseInt(input);
}
}
int total = 0;
for (int i: intArr) {
total += i;
}
System.out.println("Average: " + total / entered);
System.out.println("Entered: " + entered);

Categories