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);
}
}
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
My code will not compile and I can not figure out how to fix the error. It is a compile time run error I think. My error is in my method to print out array. Then, it says that there is something wrong with my closing bracket for the class. I am using a scanner class and I did import it, it is just not shown. Any help?
My code:
public static void main (String[] args){
int[] getArray; //reference to an int array of type and takes no parameters
System.out.println("How many numbers would you like to enter?" );
int size = scan.nextInt();
int[] nums; //reference to nums array of type int
nums = new int[size]; /* new array of type int. assigned to nums.
size, to specify number of elements array will have */
for(int i=0; i<nums.length; i++){
System.out.println("Enter a number." +(i+1)+ "left");
nums[i] = scan.nextInt(); //storing user input into array
return nums;
}//closing for loop
int[] minimumValue;
min = scan.nextInt();
min = nums[0]; //assigning min value to first element in array
return min;
for(int i=0; i<min.length; i++){
if(i<min){
min = nums[0];
}
}
return min;
public static void printArray (int[] getArray){ //method to print out array
for(int i = 0; i < nums.length; i++){
System.out.print(nums.length); //print out array
}
}
public static void printArrayInReverse(int[] getArray){ //method for arrayInReverse
for(int i = nums.length - 1; i >= 0; i--){
System.out.print(nums[i]);
}
}
int[] numbers = getArray();// calling getArray method
public static void main (String[] args){
System.out.print("************");
printArray(numbers); //calling printArray method and passing numbers through it
printArrayInReverse(numbers);// calling printArrayInReverse method and passing numbers through it
System.out.print(minimumValue(numbers)); /* calling minVal through print statement and passing
numbers through it*/
}
}
}
It is very hard to tell what you are trying to accomplish here from your code. There is no class here which means your program will not even compile, please remember to post all applicable code to your question as it makes it easier for people to help you.
Firstly, you can only have one entry point (ie. main(String[] args) for each class. This is better explained here Can there exist two main methods in a Java program?.
Within this main method, you cannot have any other methods, you can only call other methods and perform operations ad such.
The variable "scan" cannot ever do anything if it is not instantiated prior to use. The variable getArray is being used as a method, which it is not.
Please take a look at Simple Java array program where it shows more in-depth how to use arrays.
Take a look at this as see if it even accomplishes what you want to do, which is still somewhat unclear. I shortened everything so that it is simpler, with a program this small multiple methods are not needed unless there is some logic to denote when to print the array or when to print the array reversed.
import java.util.Scanner;
public class CLASSNAME {
static Scanner scan = new Scanner(System.in);
static int[] nums;
public static void main(String[] args){
// Get Size Of Array
System.out.println("How many numbers would you like to enter?" );
int size = scan.nextInt();
nums = new int[size];
// Fill Array
for(int i = 0; i < nums.length; i++){
System.out.println("Enter a number." +(i+1)+ "left");
nums[i] = scan.nextInt();
}
// Set 0th Number To
System.out.println("Enter 0th Number");
int min = scan.nextInt();
nums[0] = min;
// Print Array
System.out.println("\n" + "Printing Array Index 0 -> ArraySize");
for(int i = 0; i < nums.length; i++){
System.out.print(nums.length);
}
// Print Array Reversed
System.out.println("\n" + "Printing Array Index ArraySize -> 0");
for(int i = nums.length - 1; i >= 0; i--){
System.out.print(nums[i]);
}
}
}
you need to create a Scanner object to use it
you can't create more than one main method
you must create methods outside the main method
Example:
import java.util.Scanner;
public class a {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//code here
}
public static void method_name() {
//code here
}
//If you want to return integer value for example
public static int method_name() {
//code here
}
}
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);
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'm new to Java and am working through some problems. I'm stuck on a question that asks me to "Write a program to input ten words and then display the words that are first and last in alphabetical order". The question is ambiguous. It could mean put all the input words into alphabetical order and display the first and last of these (harder) or display the first and last inputted word in alphabetical order (easier). I wrote the following code:
import java.util.Scanner;
public class Alphabetical {
public static void main(String[] args) {
String[] s = new String[10];
for (int i = 0; i < 10; i++) {
System.out.println("Enter word");
Scanner ins = new Scanner(System.in);
s[i] = ins.nextLine().toLowerCase();
}
int result = s[0].compareTo(s[10]);
if (result < 0) {
System.out.println(s[0]);
System.out.println(s[10]);
}
else if(result>0){
System.out.println(s[10]);
System.out.println(s[0]);
}
else{
System.out.println("Words are identical so cannot be placed in alphabetical order");
}
}
}
But I'm getting an out of bounds exception where the compareTo method is placed and I'm not sure why. If anybody could help that would be great. If anyone could help with the harder version of the question too, that would be even better.
new String[10] creates an array of 10 elements.
s[10] is the 11th element of the array since elements begin with 0. So you have to treat s[9] as your last element. compareTo is not your problem
Because your "s" array have 10 elements. You cahange your code
import java.util.Scanner;
public class Alphabetical {
public static void main(String[] args) {
String[] s = new String[10];
for (int i = 0; i < 10; i++) {
System.out.println("Enter word");
Scanner ins = new Scanner(System.in);
s[i] = ins.nextLine().toLowerCase();
}
int result = s[0].compareTo(s[9]);
if (result < 0) {
System.out.println(s[0]);
System.out.println(s[9]);
}
else if(result>0){
System.out.println(s[9]);
System.out.println(s[0]);
}
else{
System.out.println("Words are identical so cannot be placed in alphabetical order");
}
}
}
The reason you're getting the error about the array is because arrays start with index 0 and go up to one less than the size of the array. So on an array with a size of 10, the highest index is 9. Did you try searching the exception online before posting this question?
What the question means, you'll have to clarify with the person who gave you the assignment/problem.