My program compiles, but when I run it, it gives me an IndexOutOfBoundsException. I am wondering what is wrong with it as I am unable to see it. My program is supposed to take input by the user and add it to the ArrayList. I am sorry if my mistake is obvious to you, but I am relatively new at using ArrayLists. Thanks!
ArrayList<ArrayList<Integer>> arr = new ArrayList<ArrayList<Integer>>();
int counter = 0;
int i = 0;
Scanner in = new Scanner(System.in);
int input = in.nextInt();
while(i < 5)
{
input = in.nextInt();
if(input != 0){
arr.get(i).set(counter++, input);
}
else{
arr.get(i).set(counter++, input);
i++;
counter = 0;
}
}
System.out.println(arr);
When you create your ArrayList of ArrayLists, initially, there are no ArrayLists contained in arr. So any call to get will fail with a IndexOutOfBoundsException.
First, add the initial inner ArrayList to arr.
Then, in the while loop, get the current inner ArrayList as you're doing, but just call add to append a number to the end of the list. Otherwise, you'll get a IndexOutOfBoundsException on your inner ArrayList. Again, the ArrayList you've created is initially empty.
When the user enters 0, then add another ArrayList when you're incrementing i (unless i is already at the last desired value), to prepare for the user adding numbers to the next list.
You are creating a list of list and both are empty. Also you are using "set" method which is actually used to replace the object in a list on specific location.
So it looks like you wanted to take input from user and if the value is 0 you just wanted to ignore it. Below is the update example for you.
ArrayList<ArrayList<Integer>> arr = new ArrayList<ArrayList<Integer>>();
int i = 0;
Scanner in = new Scanner(System.in);
int input = 0;
while(i < 5){
input = in.nextInt();
if(input != 0){
arr.add(new ArrayList<Integer>());
arr.get(i).add(input);
i++;
}
}
System.out.println(arr);
If you just want to create a list of integers then you don't have need to create a list of list. You can achieve by creating a list of integer only.
ArrayList<Integer> arr = new ArrayList< Integer >();
int i = 0;
Scanner in = new Scanner(System.in);
int input = 0;
while(i < 5){
input = in.nextInt();
if(input != 0){
arr.add(input);
i++;
}
}
System.out.println(arr);
Related
My question is what they do " smallest" variable and the if statement. I know what the program do but it cost me to understand well the flow execution of this part .
import java.util.Scanner;
import java.util.ArrayList;
public class IndexOfSmallest {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList<>();
while(true){
int numbers = Integer.valueOf(reader.nextLine());
if(numbers == 9999){
break;
}
list.add(numbers);
}
int index;
int smallest = list.get(0);
for (int i = 0; i < list.size();i++){
int number = list.get(i);
if ( smallest > number){
smallest = number;
}
}
System.out.println(smallest);
}
}
This is a rather simple console application. You should try to read your code line by line when you are starting to learn a new language.
This way you can show some effort and ask more clear and concise questions. Here is an example to go about reading your code line by line. If you don't know what some function is doing, look up that function.
Just take your time, you'll get used to the syntax and it will get easier every time.
Scanner reader = new Scanner(System.in); // Create scanner taking console inputs
ArrayList<Integer> list = new ArrayList<>(); // Create list
while(true){ // Endlessly loop
// Keep reading input from console until user inputs 9999, then break
int number = Integer.valueOf(reader.nextLine());
if(number == 9999){
break;
}
list.add(number); // Add number to list
}
/* int index; // This is worthless, not used again */
int smallest = list.get(0); // Variable to store smallest number
for (int i = 0; i < list.size();i++){ // Increase i until list size is reached
int number = list.get(i); // Get number for position i in list
if ( smallest > number){ // Compare
smallest = number; // Set new smallest number
}
}
System.out.println(smallest); // Print
I really need help with my program. I'm trying to make a cumulative grade calculator in java, using arrays and dialog boxes. For some reason, my arrays won't print out the input made by the user which is throwing off my calculations. How can I give it the correct value?
{
// First array - Length
int[] arNumber = null;
int number;
String str;
// Second array - Elements
int numbers;
int[] arNumbers = null;
int total = 0;
int gradeSum = 0;
String str2;
String message = "How many grades will you input in this class?";
str = JOptionPane.showInputDialog(message);
number = Integer.parseInt(str);
arNumber = new int[number];
for(int index = 0; index < arNumber.length; index++)
{
String message2 = "Insert your grade";
str2 = JOptionPane.showInputDialog(message2);
numbers = Integer.parseInt(str2);
arNumbers = new int[numbers];
}
for (int element : arNumbers)
{
// Print array onto console
System.out.println(element);
// Add all elements
gradeSum += element;
// Print grade onto console
System.out.println(gradeSum);
}
total = gradeSum / arNumber.length;
return total;
}```
It looks like you don't need to use two arrays. The line with arNumbers = new int[numbers]; means that arNumbers is getting reinitialized as a new array for every iteration of that loop. Try using arNumber[index] = numbers; to assign the user-entered value into the arNumber array and do away with arNumbers. Then loop over arNumber in the second loop.
Also note that total is declared as an int which will truncate your floating point value, which I'm guessing you don't want. Good luck!
I am trying to add the Integer inputted by the user to the ArrayList. It's originally a String, so I converted it to an Integer. I added the Integer to the Arraylist, but now I'm not sure how to display it. I want to be able to keep adding marks, and have all the marks displayed on the screen. I tried a for loop, but I'm not sure what the second parameter would be.
Edit: for (i=0; ... ; i++) -- What would go in the second place?
private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {
String strInputMark;
int intInputMark;
strInputMark = txtInputMark.getText();
intInputMark = Integer.parseInt(strInputMark);
ArrayList<Integer> Marks = new ArrayList<>();
int intMarks;
Marks.add(intInputMark);
}
Try this for loop:
String output = "";
for(int i = 0; i < Marks.size(); i++){
output += "\n"+Marks.get(i);
}
JOptionPane.showMessageDialog(null, output);
The short answer is i < Marks.size()
for (int i = 0; i < Marks.size(); i++) {
System.out.println(Marks.get(i));
}
You can try this
String strInputMark;
Integer intInputMark;
strInputMark = txtInputMark.getText();
intInputMark = Integer.valueOf(strInputMark);
ArrayList<Integer> Marks = new ArrayList <>();
int intMarks;
Marks.add(intInputMark);
I think the answer is two-fold. First, you need to move 'Marks' outside of the method scope so it can be accessible and continually appended two as input continues. Second, as #Umesh said, Marks.size() will give you the total number of elements in your arraylist.
I build removing duplicates, however I'm thinking how to use a method that removes the duplicate elements from an array list of integers using the following header:
public static void removeDuplicate(ArrayList<Integer> list)
write a test program that prompts the user to enter 10 integers to a list and
displays the distinct integers separated by exactly one space.
import java.util.ArrayList;
import java.util.Scanner;
public class RemoveDuplicates {
public static void main(String[] args){
ArrayList<Integer>list = new ArrayList<Integer>();
Scanner input = new Scanner (System.in);
System.out.print("Enter integers (input ends with 0): ");
int value;
do{
value = input.nextInt();
if(!list.contains(value)&& value !=0)
list.add(value);
}while (value !=0);
input.close();
for (int i = 0; i < list. size(); i++)
System.out.print(list.get(i) + " ");
}
}
It's my code,please modifying please, how to use method and test .
If I understand correctly, you should implement a method with this header
public static void removeDuplicate(ArrayList<Integer> list)
judging by its name, I'd say that method should remove the duplicates from the list and not (as you are doing it right now) the do-while-loop during input.
So first remove the check in your loop (if(!list.contains(value)&& value !=0)) and just add every number the user types to the list.
Then you can make a call to the method removeDuplicate(list);. If you want you can add this call in your loop and it will be executed after every input or you execute it just once when the input is closed.
Now implementing the method:
public static void removeDuplicate(ArrayList<Integer> list) { // this is the header you need to use
The problem here is, the method knows the list but not the element that is a possible duplicate. So you have to look for it
for (int i = 0; i < list.size(); i++) { // iterate through every element in the list
Integer current = list.get(i); // for convenience, save the current list item in a variable
So, you check every integer in the list – one by one.. but if you want to know if the integer exists a second time, you have to search the tail of the list. Meaning you have to check the sublist after i.
List sublist = list.subList(i + 1, list.size()); // the sublist with all elements of the list from i+1 to the end
your list.contains(value) line is correct, you can use it here as well. Only now you call it on the sublist
if(sublist.contains(current)){ // checks if the number is in the sublist
sublist.remove(current); // removes the number from the sublist
}
This however would only remove the first duplicate. Alternatively, you can remove every item in the list that equals the current integer:
while (sublist.contains(current)) {
sublist.remove(current);
}
And that's it. Your method is finished.
}
}
It is finished because you are actually working on the one and only list in your program. Even when you remove an integer from your sublist, it is actually removed from the sublist and the real list (the sublist is just a reference, and not an actual list on its own)
EDIT
for your convenience here the complete code with both methods. If you compare the code to yours, you'll see that there is not much different:
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
Scanner input = new Scanner(System.in);
System.out.print("Enter integers (input ends with 0): ");
int value;
do {
value = input.nextInt();
if (value != 0) { // this changed: add every number except 0
list.add(value);
}
} while (value != 0);
input.close();
removeDuplicate(list); // here you make the call for the new method
for (int i = 0; i < list.size(); i++) {
System.out.print(list.get(i) + " ");
}
}
// and this is the new method
public static void removeDuplicate(ArrayList<Integer> list) {
for (int i = 0; i < list.size(); i++) {
Integer current = list.get(i);
List sublist = list.subList(i + 1, list.size());
while (sublist.contains(current)) {
sublist.remove(current);
}
}
}
If you don't want duplicate, use a collection that implements the Set interface (http://docs.oracle.com/javase/7/docs/api/java/util/Set.html) instead of an array list.
I am having trouble starting out this program. I am supposed to write a program that will populate an ArrayList by asking the user for 10 numbers.
After the list is made I'm to navigate it and if a number is even number, remove it from the ArrayList and put the number to a Stack of integers. So far I have this but I am confused on how to get the stack started so that I can put the even numbers into it:
import java.io.* ;
import java.util.*;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
ArrayList<Integer> test = new ArrayList<Integer>();
Stack<Integer> myStack = new Stack<Integer>();
System.out.print ("Enter Number: \n");
for (int i = 0; i < 10; i++) { //Put Into ArrayList
test.add(input.nextInt());
}
System.out.print("Contents of Array: " + test );
System.out.print("\n");
for (int i= 0; i < 10 ; i++) {
int item = myIterator.getNext();
if (item % 2 == 0) {
myListIterator.remove(); //removes it from the ArrayList
myStack.push(item); //puts it into the stack
}
}
System.out.print("Contents of Array afer numbers removed: " + test );
System.out.print("\n");
}
}
It seems that you just need to initialize the stack. Do the initialization of the stack where you initialize the test array.
Put this:
Stack<Integer> item = new Stack <Integer> ();
After:
ArrayList<Integer> test = new ArrayList<Integer>();
EDIT -- I was feeling generous, so I finished it for ya ;) You were actually almost all the way there, so I don't feel I really deprived you of a learning opportunity. The only other real thing you were missing was initializing the iterator and using it correctly.
Note the following:
-- you will see that if you use the iterator, you can just get rid of the for loop.
-- I changed the names of the variables so they are a bit easier to follow-naming is important.
-- Finally, since an ArrayList ISA List, you will notice I changed the declaration for the input values to use the interface for the declaration.
import java.util.*;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
List<Integer> inputValues = new ArrayList<Integer>();
Stack<Integer> evens = new Stack <Integer> ();
System.out.print("Enter Number: \n");
for (int i = 0; i < 10; i++) { //Put Into ArrayList
inputValues.add(input.nextInt());
}
System.out.println("Contents of Array: " + inputValues);
Iterator<Integer> iter = inputValues.iterator();
while(iter.hasNext()) {
Integer currentVal = iter.next();
if (currentVal % 2 == 0) {
iter.remove(); //removes it from the ArrayList
evens.push(currentVal); //puts it into the stack
} else {
System.out.println("No");
}
}
System.out.println("List values " + inputValues);
System.out.println("Stack values " + evens);
}
}
Hint: The commented out code has a declaration and initialization of a stack that is suitable for your purposes. It needs to be before the code that pushes stuff onto the stack.
I really doubt your code compiles without modification. For example myListIterator and myStack aren't even declared and I don't remember java Iterators to have a getNext() method.
Before using a variable, you must first declare it and the initialize it, these operations can be both done in one line, for example : Stack<Integer> myStack = new Stack<Integer>();
Looking at the tags of your question, this seems to be some kind of homework, I'm sure the documentation explains all of theses steps.
And since your using a ListIterator to remove the Integer from the ArrayList, there's no need to use a for loop, you can do something like
while(myListIterator.hasNext()) {
Integer item = myListIterator.next();
if(item % 2 == 0) {
item.remove();
myStack.add(item);
}
}