Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am getting the error Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at sorting.main(sorting.java:53). I am just trying to pass string integer values to an integer array but it is not working as intended. I have variables above such as count which is determined by how many integers the user wants to enter. In and another variable int[] list = new int[count]; which is the integer array I am trying to pass them to. If I enter the value of 5 for count I am trying to only accept 5 values of integers. Passing them to the int[] list array is where I am messing up.
// Prompts user to enter the integer values here
while(true){
System.out.print("\nEnter integer values here seperated by a space: ");
intValues = input.readLine();
String[] intCheck = intValues.split("\\s+");
try {
for(int j = 0; j < intCheck.length; j++){
list[j] = Integer.parseInt(intCheck[j]); // LINE 53 IS HERE
}
}
catch (NumberFormatException ex) {
System.err.println("You need to enter valid integer numbers. Try again.");
}
}
you probably have an extra space at the end so your split is returning an overlarge array. Use j < count.
I have gotten my error. I declared int count = 0 early on. Then just below that I declared int[] list = new int[count] which was taking 0 values. I should have declared the range after I prompted the user to enter the information.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I need to print an array's element with it's index next to it. If the array element is even, it must display the element and its correlating index number, if the element is odd, it must display the element and "1".
For example:
Input: int[] array = new int [25]
Output: 0:0, 1:1, 2:2, 3:1, 4:4, 5:1, 6:6, 7:1 and so on
How would I do this?
You could do something like, You can check if a number is even then print the number and index separated by a colon else print number and 1 separated by a colon, This can be achieved by using for loop construct.Would recommend you to follow proper guide/tutorial as you look like a beginner in java.
public static void main(String[] args) {
int[] array = {1,2,3,4,5};
int counter = 0;
for(int i : array) {
if(i % 2 == 0)
System.out.print(i+":"+counter);
else
System.out.print(i+":1");
if(counter<array.length-1)
System.out.print(", ");
counter++;
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am trying to make a java program that will add inputs until the total equals 100+ OR the user inputs 5 numbers. I'm also attempting to add a highest run to it that keeps track of the highest input. Currently it continues to run after 5 inputs when it's less than 100 total and my highest run doesn't work. How would I fix this?(I'm new to Java if you can tell)
import java.io.*;
public class HighScoreTest {
public static void main(String[] args) {
// input streams.
InputStreamReader input = new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(input);
// constant declarations
final Integer MAX = 100;
final Integer MAX_NUMBER = 4;
// variable declarations
String sName;
Integer currentTotal;
Integer currentNumber;
Integer numbersInputed = 0;
Integer count;
Integer maxRunToDate = 0;
// we catch exceptions if some are thrown.
// an exception would be entering a string when a number is expected
try {
System.out.println("What is your name?");
// reading string from the stream
sName = reader.readLine();
currentTotal = 0;
for(count = 0; count < MAX_NUMBER; count++) {
numbersInputed += count;
}
do {
System.out.println("Please enter a number");
currentNumber = Integer.parseInt(reader.readLine());
currentTotal = currentTotal + currentNumber;
}while(currentTotal < MAX || numbersInputed == MAX_NUMBER);
if (maxRunToDate < currentTotal) {
maxRunToDate = currentTotal;
}
System.out.println(sName +", the total for this run is "+ currentTotal);
System.out.println("The highest run is "+ maxRunToDate);
} catch (IOException e){
System.out.println("Error reading from user");
}
}
}
Some help to get you going:
currentRun = currentRun + currentNumber;
Simply doesn't make sense!
I assume that currentRun should count the number of runs so far. So that you can stop after the 5th round.
Thus: you should just increment that counter by for each round.
In other words: try to separate things. Step back and consider what kind of information you want to "track" and how many variables you really need to do that.
And please understand: we will not solve your assignment for you. If at all, there will be some guidance on how to make progress. But don't expect us to figure all the bugs in your code and resolve them for you.
There is several things that you need to know:
First, avoid wrap classes like Integer unless you intend to use it together with the Colection FrameWork or even Streams. If your problem is the fact that the output of the parsing is the Integer class, don't worry, for it will auto unbox. Something like this:
int currentNumber = Integer.parseInt(reader.readLine()); //Auto Unboxing
Second, why do you even have the for loop in the beginning? Remove it. If you want to initialize the numbersInputed variable just do it.
And third, if you whant to increment or decrement, you can just use ++ or `--
And check the Oracle Tutorials: https://docs.oracle.com/javase/tutorial/
I hope I have helped.
Have a nice day. :)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I'm trying to read some data from a user and do some very simple calculations with them, but for some reason I can't explain, the program stops after first 2-3 inputs (given they are doubles). Can someone explain this behaviour?
My code:
Scanner in = new Scanner(System.in);
System.out.println("Enter your values, 'q' to quit: ");
double average, input, smallest, largest, range;
average = smallest = largest = range = Double.parseDouble(in.nextLine());
int counter = 1;
while (in.hasNextDouble()) {
input = Double.parseDouble(in.nextLine());
smallest = input < smallest ? input: 0;
largest = input > largest ? input: 0;
average += input;
counter++;
}
Consider this input:
1.23
4.56 7.89
To Scanner this looks like a valid sequence of three doubles on two separate lines. When you call nextLine to obtain the first double, it works fine, because the number occupies the entire string.
When you do the same for the next double, the string that you try to parse looks like this:
"4.56 7.89"
This string is not a valid double, so you cannot parse it.
One approach to deal with this problem is to call nextDouble, and avoid parsing altogether. Pairing up hasNextDouble() with nextDouble() has an advantage of not requiring users to put their data on different lines.
Note: The first call to Double.parseDouble(in.nextLine()) happens without checking that Scanner has next double, so your program could crash on initial bad input.
This question already has answers here:
How can I avoid ArrayIndexOutOfBoundsException or IndexOutOfBoundsException? [duplicate]
(2 answers)
Closed 7 years ago.
Here is my code:
for (int i = 0; i < 99; i++)
{
String inputString = keyboard.next();
String[] inputArray = inputString.split(":");
if (inputString.equals("quit"))
System.out.println("You have quit");
FirstArray[i] = inputArray[0];
SecondArray[i] = Integer.parseInt(inputArray[1]); // these throw errors
ThirdArray[i] = Integer.parseInt(inputArray[2]);
System.out.println(FirstArray[i]);
System.out.println(SecondArray[i]);
System.out.println(ThirdArray[i]);
So here is my code, I'm trying to test out arrays and I need to get input from the user split using the delimiter ":"
I had to parseInt the last two arrays (as they are taking in integer values) to get the split input from the second and third index of the inputArray.
I have the last part of the code to test if it works, and it does but when I type in "quit" to end the loop it throws:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
I have searched and understood the issue but don't know how to avoid it. Sorry if I'm not explaining my issue, would appreciate another working solution. Thanks in advance for help
The string "quit" does not contain any ":" characters, so the result of inputString.split(":") is an array with a single element. So as soon as you try to access inputArray[1], you will have the exception, because index 1 refers to the 2nd element in the array, although this array has only one element
if (inputString.equals("quit")) {
System.out.println("You have quit");
return; // add this line
}
Add the return statement (shown above), and this will by pass the code problematic code. It seems like the right thing to do anyways, as the user is asking to quit the program.
Access inputArray only till its length i.e use inputArray.length() first to find array length then access array elements from 0 to length -1.
Most evident case from your code is when you enter quit but other inputs might cause it too since your are not checking length of array i.e. if length of splitted array is less that 3 for whatever input , you will receive this exception.
The issue you are running into is that the code accessing the inputArray variable is run regardless of whether or not the quit command is received. You have two options here.
1) Return on the quit command (recommended)
if (inputString.equals("quit")) {
System.out.println("You have quit");
return; // This will avoid running the code below
}
FirstArray[i] = inputArray[0];
SecondArray[i] = Integer.parseInt(inputArray[1]); // these throw errors
ThirdArray[i] = Integer.parseInt(inputArray[2]);
System.out.println(FirstArray[i]);
System.out.println(SecondArray[i]);
System.out.println(ThirdArray[i]);
2) Throw the remaining code in an else case
if (inputString.equals("quit")) {
System.out.println("You have quit");
} else {
FirstArray[i] = inputArray[0];
SecondArray[i] = Integer.parseInt(inputArray[1]); // these throw errors
ThirdArray[i] = Integer.parseInt(inputArray[2]);
System.out.println(FirstArray[i]);
System.out.println(SecondArray[i]);
System.out.println(ThirdArray[i]);
}
I would also recommend adding an error case if the inputArray doesn't end up being the expected length.
if (inputArray.length != 3) {
System.out.println("That's weird. I was expecting 3 parameters, but only found " + inputArray.length);
return;
}
you can use Scanner class to read the input.
Scanner scanner = new Scanner(System.in);
for(int i=0; i<Noofiterations; i++){ //iterations are the no.of times you need to read input.
String[] inputArray = scanner.nextLine().split(":");
//rest of the code is same as yours.
}
Input should be in the form "abc:123:334:wet"
Hope this helps. Let me know if i didn't get your question.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
How to fill an array of integers in Java by asking the user to enter the number once ?
for example :
Enter 3 integers >: 123
then I want to get the array filled like that :
arr[0]=1
arr[1]=2
arr[2]=3
I hope the question is clear :)
rgds
One way of going about this would be to take the integer in as a String. You can then use toCharArray() in order to grab an array of the characters - these characters can then be individually parsed into Integer by utilizing Character.getNumericValue().
See the String and Character APIs for more details on those methods.
Small example of what I mean:
String numbers = "123";
char[] numArray = numbers.toCharArray();
for (char c : numArray) {
int num = Character.getNumericValue(c);
// Do what you will with the number.
}
As noted, this particular implementation would only work in this format if you are assuming that each integer is single digit.
How about this:-
Scanner input = new Scanner(System.in);
System.out.println("How many numbers do you want to enter?");
int num = input.nextInt();
int array[] = new int[num];
System.out.println("Enter the " + num + " numbers now.");
for (int i = 0 ; i < array.length; i++ ) {
array[i] = input.nextInt();
}