This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 5 years ago.
I'm creating a program of letting people enter 10 integers and display them from the smallest to the largest. Here is my program:
import java.util.Scanner;
public class EnterTenNumbers {
public static void main(String[] args){
System.out.println("Enter 10 numbers");
int small=0;
for(int i=0; i<10; i++){
Scanner in=new Scanner(System.in);
int[] i1=new int[10];
int num=in.nextInt();
i1[i]=num;
if(i1[i]<i1[i+1] || i1[i]==i1[i+1]){
System.out.println(i1);
}else if(i1[i]>i1[i+1]){
i1[i+1]=i1[i];
System.out.println(i1);
}
}
}
}
When I run my program, after the user input the numbers, such things like "[I#55f96302" appear.
And after the user entered 10 integers, Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
at EnterTenNumbers.main(EnterTenNumbers.java:13)
appears while it should display the numbers from smallest to largest.
What happened?
Every time you are asking the user to give a number as input, you are creating a new array of integers. Aren't you supposed to create only one array to hold those 10 integers ? So, declare the integer array outside the loop. in this way, it will be declared only once.
You have to take all the 10 integers from user at the very beginning, then you have to run the operations over these 10 integers in order to show them from smallest to the largest.
after taking all the 10 integers from user and saving them in An array, you have to again loop through among those numbers one by one and check which number is smallest and which number is largest. When the loop check the last index of the array, you can't check the next index of that array (because that index of the array doesn't exists). That's why you are having an exception every time.
if(i1[i]<i1[i+1] || i1[i]==i1[i+1]){
System.out.println(i1);
}else if(i1[i]>i1[i+1]){
i1[i+1]=i1[i];
System.out.println(i1);
}
When I run my program, after the user input the numbers, such things
like "[I#55f96302" appear.
This is because you are printing the string representation of your array, not the elements of the array.
Replace
System.out.println(i1);
with
System.out.println(i1[i]);
And after the user entered 10 integers, Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: 10
As the exception clearly indicates, you are trying to access 10th index (index starts from 0) or 11th element of the array. But your array has only 10 elements. So that's why you get AIOOBE. In your conditional statement, the predicate i1[i+1] becomes i1[10] when i=9. You need to fix this.
Lastly, you can achieve your objective the following way too:
System.out.println("Enter 10 numbers");
int small=0;
for(int i=0; i<10; i++){
Scanner in=new Scanner(System.in);
int[] i1=new int[10];
int num=in.nextInt();
i1[i]=num;
}
Arrays.stream(i1).sorted().forEach(System.out::println);
Related
I have a quick question about the Scanner class.
I had an idea to make a simple program that starts to count all the numbers I write in, but if it goes over a limit it should stop.
This is not the problem....
The problem is that the FIRST number you write in should be the number that tells the program how many numbers it will be counting.
For an example.
When the program starts, I will write in for example :
3
100
234
546
Sum: 880.
and the output should be the sum of 100+234+546.
The number 3 in the beginning just told the program that it is 3 numbers that it should read. I don't understand how to make the first number the number that tells the program how many numbers it should be in the input before it starts to count.
If you are using Java 8, you can do something like this:
Scanner scan = new Scanner(System.in);
int N = scan.nextInt(); //First number is the count of numbers
//line below loops for you and sums at the end
int sum = IntStream.range(0, N).map(i -> scan.nextInt()).sum();
use this code
void yourMethod()
{
int sum=0;
Scanner scan = new Scanner(System.in);
int conut=scan.next();
for(int i=0;i<count;i++)
{
sum=sum+scan.next();
}
}
Store the first number in a variable called counter or similar, and then execute a loop (for, while) for counter times, in each iteration you will read the next number and sum them. The algorithm seems very straightforward to create code from it.
How about:
Scanner scan = new Scanner(System.in);
int count = scan.nextInt();
while(count>0){
//your logic
count--;
}
I am trying to have a method that takes the a five-dice random roll (int [] dice) and allows the user to say which dice they want to throw again (1st, 2nd, 3rd, 4th , or 5th die) like in the game Yahtzee. I also have to validate that the user picked a number between 1 and 5, that they don't put a duplicate number, and that they don't enter more than 4 numbers to roll again. If the requirements aren't satisfied, I need to out print "Illegal die!" and ask the user to enter again. Whichever die/ dice they choose needs to be randomized again and be assigned to the dice[] array. This is what I have so far that basically takes the user string input and changes it to integers and I can't figure out how to do the other things I mentioned above. Any help would be greatly appreciated!
public static void throwAgain(int[] dice) {
Scanner keyboard = new Scanner(System.in);
System.out.print("List which die to throw again: ");
String line = keyboard.nextLine();
String [] strArray = line.split(" ");
int [] intArray = new int[strArray.length];
for (int i = 0; i < intArray.length; i++){
intArray[i] = Integer.parseInt(strArray[i]); // Changes user's string input to an array of integers
}
// Arrays.sort(intArray);
}
I also have to validate that the user picked a number between 1 and 5
Check each int as you are looping. > and < are useful.
that they don't put a duplicate number
Make a subloop that will check each previous value. = is useful.
and that they don't enter more than 4 numbers to roll again.
.length and > are useful.
If the requirements aren't satisfied, I need to out print "Illegal die!"
Have a boolean flag error that starts out as false and set it to true when a validation check fails. At the end, check the flag. System.out.println is useful.
and ask the user to enter again.
while is useful. Set error as true at the top, and false as the loop starts. Loop while there is an error.
Whichever die/ dice they choose needs to be randomized again and be assigned to the dice[] array
Loop over the intArray, and assign new random values to the dice elements whose indices are one less than each element of intArray. [], - and java.util.Random are useful.
I'm trying to make an Insertion Sort algorithm in Java, and I want it to read user input, and he/she can put however many numbers they wish (We'll say they're all integers for now, but long run it would be nice to be able to do both integers and doubles/floats), and I want the algorithm to sort them all out. My issue is that when I run this code to see if the integers are adding correctly, my loop never stops.
public class InsertionSort {
public static void main(String[] args){
System.out.println("Enter the numbers to be sorted now: ");
ArrayList<Integer> unsortNums = new ArrayList<Integer>();
Scanner usrIn = new Scanner(System.in);
while(usrIn.hasNextInt()) {
unsortNums.add(usrIn.nextInt());
System.out.println(unsortNums); //TODO: Doesn't stop here
}
sortNums(unsortNums);
}
}
Now, I suspect it has something to do with how the scanner is doing the .hasNextInt(), but I cannot for the life of me figure out why it isn't stopping. Could this be an IDE specific thing? I'm using Intellij Idea.
Let me know if I left anything out that I need to include.
Your code will stop as long as you stop adding numbers to your input stream. nextInt() is looking for another integer value, and if it can't find one, it'll stop looping.
Give it a try - enter in any sequence of characters that can't be interpreted as an int, and your loop will stop.
As a for-instance, this sequence will cease iteration: 1 2 3 4 5 6 7 8 9 7/. The reason is that 7/ can't be read as an int, so the condition for hasNextInt fails.
When using a scanner on System.in, it just blocks and waits for the user's next input. A common way of handling this is to tell the user that some magic number, e.g., -999, will stop the input loop:
System.out.println("Enter the numbers to be sorted now (-999 to stop): ");
List<Integer> unsortNums = new ArrayList<Integer>();
Scanner usrIn = new Scanner(System.in);
int i = usrIn.nextInt();
while(i != -999) {
unsortNums.add(i);
i = usrIn.nextInt();
}
I am making a program that prompts the user for 3 integers and prints out the biggest one chosen. I am stuck with 2 problems at the moment. I would like to know how I can make the program so that the user can only choose integers from the array. I would also like to know how to find and print out the biggest integer from the ones that the user chose. I'm quite new to programming so all feedback is appreciated.
Thanks!
import java.util.Scanner;
public class Lab14C // name of class file
{
public static void main(String [] args)
{
int[] array = {0,1,2,3,4,5,6,7,8,9};
for(int i=0; i<array.length; i++)
{
System.out.print(array[i] + " ");
}
System.out.println("\n");
Scanner array1 = new Scanner(System.in);
System.out.println("What is your first integer? ");
double array11 = array1.nextInt();
Scanner array2 = new Scanner(System.in);
System.out.println("What is your second integer? ");
double array22 = array2.nextInt();
Scanner array3 = new Scanner(System.in);
System.out.println("What is your third integer? ");
double array33 = array3.nextInt();
System.out.println("\n");
}
}
I don't think there is a way to force a user to input an element. Few things you could do is :
Tell the user he has to select a number in a particular range.
Keep the input statement in a loop. If the entered element exists in array , go ahead. Else tell the user to enter again.
Printing the biggest integer can be done using Math.max(double,double) function. For three elements you can try System.out.println("Max of three is "+Math.max(array11,Math.max(array22,array33)))
You can do it yourself if you want instead of built in function like:
if(array1>array2&&array1>array3)
//print max as array1
else if(array2>array1&&array2>array3)
//print max as array2
else //print array3 as max
Also change your element types to int as you are reading integer.
1) There is no need to create a new Scanner all the time.
Just create one Scanner (which I would just call input or scanner or something that makes sense).
2) If you're reading int's why are you storing them in doubles?
3) To check for a certain condition you use if(*condition*) { /*do something */ }. So if you want to check if x is smaller than y you do if(x < y) { /* do something */ }. (In your case you'll want to check if current input is greater than biggest input and if so set the biggest input to current input.)
4) For a sorted array you can use Arrays.binarySearch(array, elementToSearch) which will return the index of the element when found, or a negative number if not found (the negative number is (-(insertionPoint)-1)). (So you can check if the number entered by the user is in the array and keep asking for a new number if is not.)
1) How I can make the program so that the user can only choose integers from the array.?
You are declaring array variable as int[] so it stores only integer values. Whenever you retrives the value from this array, it returns int value only so you don't have to worry about it.
2)how to find and print out the biggest integer from the ones that the user chose.?
To find the maximum or minimum from a set of values, Java provide a function name Math#max(). You can use it like this :
int maxValue = Math.max(Math.max(array11,array22),array33);
Here is the doc for Math library.
I"m trying to make a program that retrieves an endless amount of numbers that user inputs until the user quits and display the numbers .Here is the code I have so far.After entering the first and second number it shows an exception at the line array1[i]=s1
import java.util.Scanner;
public class Program_2 {
public static void main(String[] args) {
int a=1,i;
Scanner sn = new Scanner(System.in);
String[] array1= new String[a];
for(i=0;i<a;i++)
{
System.out.println("Enter Value Number "+ (i+1));
System.out.println("Press Q or q to Exit");
String s1=sn.next();
if(s1.equalsIgnoreCase("q"))
{
for(i=0;i<a;i++)
{
System.out.println("Value of Number "+(i+1)+" is "+ array1[i]);
}
a=0;
}
else
{
array1[i]=s1;
a=(i+2);
}
}
}
}
Your array is of size 1 (a is 1 at the beginning of your code).
The first input works because i is 0 and array1[0] exists. The second input crashes because array1[1] does not exist.
You need to increase your array. That can be done by copying the array into a larger one and using the result of the copy, but that is clumsy.
Better way to do it is to use an ArrayList instead of a simple array and you do not have to worry about the size as it is managed automatically.
For one, a is only incremented when they press q, when you go to the else statement. So the the for loop is going to end after a couple of iterations.
You also set a to 0 in the inside for loop, making sure it won't run more.
Also, your quit code doesn't quit.