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.
Related
This question already has answers here:
Unreachable code in Java
(2 answers)
Closed 3 years ago.
My goal is to make an String array which I'm going to send to a different method, it has to be a string array. Since I don't know how many strings are going to be entered I can't predict how many string are going to be used, I am using a arrayList. But when I try to convert the arrayList to a simple array, I got an unreachable statement error in my compiler.
I got the error here:
String[] gradic = new String[lista.size()];
This is the rest of my code:
public static main(){
Scanner in = new Scanner(System.in);
System.out.println("Enter strings (empty line to end):");
List<String> list = new ArrayList<String>();
while (true){
String x = in.nextLine();
if (x.equals(" ")) continue;
lista.add(x);
}
String[] x0 = new String[list.size()];
lista.toArray(x0);
}
I want the arrayList to turn into a String[] array.
This loop does not have any break, so the program cannot go out of it:
while (true){
String x = in.nextLine();
if (x.equals(" ")) continue;
lista.add(x);
}
Probably you meant to write:
while (true){
String x = in.nextLine();
if (x.equals(" ")) break;
lista.add(x);
}
If you're just starting with Java programming, do not use while(true), not even with an appropriate break. If you want to stop reading input when the user types something specific, test for that :
Scanner in = new Scanner(System.in);
System.out.println("Enter strings (empty line to end):");
List<String> list = new ArrayList<String>();
String input = "";
while (!input.equals(" ")) { // If this is your break condition: test for it.
input = in.nextLine();
if (!input.equals(" ")) {
list.add(input);
}
}
Does that check input twice? Yes. Is it "inefficient"? Not something you should care about, or can even meaningfully comment about in this kind of code. Is it explicit on what this code should do, to human readers? Very much so, and that's what matters for code you will be writing for a while.
You cannot have while(true) with code after the loop without a break; In general, given while([condition]) if condition evaluates to true during compile time (such as with constants) then the while loop must have a break statement of some sort if there is code after the while. If there is no code after the while, it will be fine.
I want to make a program which keeps prompting the user to input integers(from CUI) until it receives a 'X' or 'x' from the user.
The program then prints out the maximum number, minimum number and average value of the input numbers.
I did manage to get the user to input numbers until someone types 'X', but I can't seem to get it to stop if someone types 'x' and the second bit.
This is the code that I have managed to work out:
Scanner in = new Scanner(System.in);
System.out.println("Enter a number")
while(!in.hasNext("X") && !in.hasNext("x"))
s = in.next().charAt(0);
System.out.println("This is the end of the numbers");
Any hints on how I proceed further?
You will need to do something like this:
Scanner in = new Scanner(System.in);
System.out.println("Enter a number")
while(!(in.hasNext("X") || in.hasNext("x")))
s = in.next().charAt(0);
System.out.println("This is the end of the numbers");
Whenever you use while loop you have to use the {} in case the arguments in the while block are more than 1 line, but if they are just of a line then you can just go on without using the {}.
But the problem, you had I suppose is the use of && instead of ||. What the && (AND) operator does is execute if both the statements are true but a || (OR) Operator works if any of the conditions are true.
If you say while(!in.hasNext("X") && !in.hasNext("x")) it makes no sense as the user input is not both at the same time, but instead if you usewhile(!in.hasNext("X") || !in.hasNext("x"))` it makes sense. Understood?
And about sorry, im really new at this. but ive added the code No problem, you need not say sorry but there are a few things to keep in mind before asking a question. You must read this https://stackoverflow.com/help/how-to-ask and yeah one more thing, you should use proper English Grammar while framing your question.
Last of all, about how to calculate the average..., for that what you need to do is store all the input variables into an array and then take out the mean of that or alternatively you could think about it and code something up yourself. Like to take out mean, you could make a variable sum and then keep adding the integers the user enters and also keep a variable count which will keep the count of the number of integers entered and then at last you could divide both of them to have your answer
Update: For checking the minimum and the maximum, what you can do is make 2 new variables like int min=0, max=0; and when the user enters a new variable you can check
//Note you have to change the "userinput" to the actual user input
if(min>userinput){
min=userinput;
}
and
if(max<userinput){
max=userinput;
}
Note: At stackoverflow we are there to help you out with the problems you are facing BUT you cannot exploit this. You cannot just post your homework here. But if you are trying to code something up and are stuck at it and cannot find a answer at google/stackoverflow then you can ask a new question and in that you need to tell what all you have already tried. Welcome to SO! :D Hope you have a nice time here
This would fit your needs:
public void readNumbers() {
// The list of numbers that we read
List<Integer> numbers = new ArrayList<>();
// The scanner for the systems standard input stream
Scanner scanner = new Scanner(System.in);
// As long as there a tokens...
while (scanner.hasNext()) {
if (scanner.hasNextInt()) { // ...check if the next token is an integer
// Get the token converted to an integer and store it in the list
numbers.add(scanner.nextInt());
} else if (scanner.hasNext("X") || scanner.hasNext("x")) { // ...check if 'X' or 'x' has been entered
break; // Leave the loop
}
}
// Close the scanner to avoid resource leaks
scanner.close();
// If the list has no elements we can return
if (numbers.isEmpty()) {
System.out.println("No numbers were entered.");
return;
}
// The following is only executed if the list is not empty/
// Sort the list ascending
Collections.sort(numbers);
// Calculate the average
double average = 0;
for (int num : numbers) {
average += num;
}
average /= numbers.size();
// Print the first number
System.out.println("Minimum number: " + numbers.get(0));
// Print the last number
System.out.println("Maximum number: " + numbers.get(numbers.size() - 1));
// Print the average
System.out.println("Average: " + average);
}
This program I am writing is giving me fits. What I am trying to do is prevent a user from entering the same integer twice. The program takes 4 int inputs and compares them to an array of 4 random int's, searching for a match. Here is what I have thus far in my attempts to prevent multiple inputs.
for (int z = 0; z<4; z++){
System.out.println("Enter a number between 0-9. No duplicates please!");
temp[z] = inputDevice.nextInt();
for(int why = 0; why<temp.length; why++){
if(Arrays.asList(temp).contains(temp[z])){
System.out.println("Duplicate found! Please enter a non-repeating digit");
temp[z]=0;
z--;
}
}
}
The inputs are coming into the temp array just fine. And are being passed on to the other methods in the program, and that is working. I am guessing the issue is with my conditional statement - if(Arrays.asList(temp).contains(temp[z]))
Is there a better way to test to see if an array already contains a value?
Thanks in advance.
1) Since you are converting the array to a list, might as well use an ArrayList
2) Store your input in a variable and test if it is contained within the list already
List<Integer> my_list = new ArrayList<Integer>();
for (int z = 0; z<4; z++){
System.out.println("Enter a number between 0-9. No duplicates please!");
int input = inputDevice.nextInt();
if(my_list.contains(input)){
System.out.println("Duplicate found! Please enter a non-repeating digit");
z--;
}
else{
my_list.add(input);
}
}
When you check if temp contains z, it already contains z. Put the input in a temporary variable before you check it and only add it afterwards.
You're not using the why from your loop.
However if possible I would change temp to an ArrayList implementation. The problem with toList method. It's using the int[] array as a single object rather than treating it as an array of int objects. To do the latter you must use Integers.
This question already has answers here:
try/catch with InputMismatchException creates infinite loop [duplicate]
(7 answers)
Closed 7 years ago.
I am making a method in order to get how many numbers the user wants to sum together. aka if they want to sum the numbers 1 2 and 3. they would want to sum 3 numbers together. So when i ask them how many they want to sum together, I use a try - catch in order to catch if they enter a decimal place. Because you cant add together 3.5 numbers you can add 3 numbers or 4. problem is if the user enters a decimal, the program will infinite loop run everything but what is in the try statement. How can i fix this?
Here is the code for the method:
private static int requestMaxInputForFloat(Scanner scanner){
boolean appropriateAnswer = true; // assume appropriate catch not appropriate to loop again
int howManyInputs = 1000000; // hold value to return how many inputs. if this value we will not run.
//request an appropriate number of inputs until appropriate answer = true;
do
{
appropriateAnswer = true; //if looped again reset value to true
try{
System.out.print("How many decimal place numbers would you like to sum? ");
howManyInputs = scanner.nextInt();
}catch(Exception e){
System.out.println("Sorry but you can only request to average a whole number set of data.\nTry Again.");
appropriateAnswer = false;
}//end of try-catch
if (howManyInputs <= 0) //invalid answer
{
System.out.println("Sorry but " + howManyInputs + " is equal to or below 0. Please try again.");
}else{
appropriateAnswer = false;
}
}while(!appropriateAnswer);//end of while loop
return howManyInputs; //return the value
}// end of getMaxInput
Add scanner.nextLine(); in the catch block. I think the problem is that if nextInt() gets an error, the scanner's "pointer" is still pointing at a bad character, and if you just try nextInt() again, it will try to scan the same bad character over again. You have to do something to make the scanner skip over it. Here, you want to just throw away whatever the user typed in, so nextLine(), which skips over the entire remainder of the input line, is the most appropriate.
One other thing: I'd change
if (howManyInputs <= 0) //invalid answer
to
if (appropriateAnswer && howManyInputs <= 0) //invalid answer
Otherwise, if the user types in -1, then the loop will go back and howManyInputs will still be -1; then if the user types 3.5, you'll get the exception but you'll get a second error message because howManyInputs is still -1 left over from the previous loop. You don't need to test howManyInputs if you already know there was an input error.
I am making an inefficient calculator type of program that takes values from user defined arrays and plugs them into an equation that the user also defines. To do this I needed to make my program change my string to a char array, the problem? I have it so that users must use A1-10 to reference the definded index and I cannot find a way to make the program search the next array for the number to specify what array the program is accessing.
out.println("Please input a string of commands in a format similar to this: ");
out.println("([A1]-[A2]=) or ([A8]+[A6]=) or ([A1]-[A4]+[A7]*[A10]/[A3]=)");
out.println("Use only the numbers 1-10 when referencing an array. \n You may always type in 'Help' if you need help. ");
String eString = scn.nextLine();
if ("help".equals(eString)) {
out.println("Figure it our yourself...");
} else {
for (char c: eString.toCharArray()) {
if (c == 'A') {
}
}
the code got a little jumbled up while changing code and I haven't taken the time to make it look nice and pearly again.
If you need the index you should just use a normal for loop instead of an enhanced for loop.
char[] input = eString.toCharArray();
for(int i = 0; i < input.length; i++) {
if(input[i] == 'A'){
// You know the index of A here.
}
}
You should also use "help".equalsIgnoreCase(eString) when comparing with help so that they can enter either "Help" or "help" (link to doc)