How to get ArrayList<Integer> and Scanner to play nice? - java

import java.util.*;
public class CyclicShiftApp{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList<Integer>();
while(scan.hasNextInt()){
list.add(scan.nextInt());
}
Integer[] nums = new Integer[list.size()];
nums = list.toArray(nums);
for(int i = 0;i < nums.length; i++){
System.out.println(nums[i]);
}
}
Thanks to poor-mans-debugging I've found that the while(scan.hasNextInt()) isnt actually adding anything. What might be going wrong? Is my google-fu weak or lack of know-how letting me down? I am rather new to programming, and so unfamiliar with Lists so thought this would be a nice first step but something isnt adding up. It also compiles fine so Its not syntax(anymore). Perhaps a casting issue?

Does this work, master Samwise?
import java.util.*;
public class CyclicShiftApp{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList<Integer>();
System.out.print("Enter integers please ");
System.out.println("(EOF or non-integer to terminate): ");
while(scan.hasNextInt()){
list.add(scan.nextInt());
}
Integer [] nums = list.toArray(new Integer[0]);
for(int i = 0; i < nums.length; i++){
System.out.println(nums[i]);
}
}
}
I'm assuming there's a reason why you need the list as an array, otherwise the conversion to an array is unnecessary. As Jon Skeet mentions in the comments, the loop will terminate only when the stream doesn't have a next int, ie. a non-integer value or a file's EOF if you're using 'java CyclicShiftApp < input_file.txt'.

Your problem is here :
while(scan.hasNextInt()){ <-- This will loop untill you enter any non integer value
list.add(scan.nextInt());
}
You just have to enter a character say e.g q once you finished entering all the integer values and then your program will print expected results.
Sample Input :14 17 18 33 54 1 4 6 q

import java.util.*;
class SimpleArrayList{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
ArrayList <Integer> al2 = new ArrayList<Integer>();
System.out.println("enter the item in list");
while(sc.hasNextInt())
{
al2.add(sc.nextInt());
}
Iterator it1 = al2.iterator();
/*loop will be terminated when it will not get integer value */
while(it1.hasNext())
{
System.out.println(it1.next());
}
}
}

This is one of the simple and easiest way to use Scanner and ArrayList together.
import java.util.*;
public class Main
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int num=sc.nextInt();
ArrayList<Integer> list=new ArrayList<Integer>(num);
for(int i=0;i<num;i++)
{
list.add(sc.nextInt());
}
Iterator itr=list.iterator();
{
while(itr.hasNext())
{
System.out.print(itr.next()+" ");
}
}
}
}

Related

How can I take the input and insert it into LINKED LIST in java?

I am trying to make a three different linked list. I will determine the first ones inputs but for the other two I want to ask the user for the inputs and then insert them into a linked list. Can anyone help me with how to do that? So far I could only write this code
package homework001;
import java.util.Scanner;
import java.util.List;
import java.util.LinkedList;
import java.util.ListIterator;
public class morph {
public static LinkedList<String> list;
public static void main(String[] args){
LinkedList<String> list = new LinkedList<>();
list.add("10");
list.add("34");
list.add("1");
list.add("97");
list.add("5");
list.add("62");
}
}
I think we can simply take user input in LinkedList by using
this method -> listname.add(sc.nextInt());
code for the implementation is below! thank you :)
public class LL_userInput {
public static void main(String[] args) {
LinkedList<Integer> ll = new LinkedList<>(); //creating list
Scanner sc = new Scanner(System.in); //creating scanner for total elements to be inserted in list
System.out.println("enter total count of elements -> ");
int num = sc.nextInt(); // user will enter total elements
while(num>0) {
ll.add(sc.nextInt());
num--; // decrement till the index became 0
}
sc.close();
System.out.println(ll);
}
}
Using scanner, you can get input from any source. To read from console use
Scanner sc = new Scanner(System.in);
while(!sc.hasNextInt()) sc.next();
int number = sc.nextInt();
for(i=0; i< number; i++)
myList.add(sc.next());
I think you don't understand from the comments here is a simple example ;
public static void main(String[] args) {
LinkedList<String> list = new LinkedList<>();//declare your list
Scanner scan = new Scanner(System.in);//create a scanner
System.out.print("Enter the Nbr of element : ");
int nbr = scan.nextInt();//read the number of element
scan.nextLine();
do {
list.add(scan.nextLine());//read and insert into your list in one shot
nbr--;//decrement the index
} while (nbr > 0);//repeat until the index will be 0
scan.close();//close your scanner
System.out.println(list);//print your list
}
import java.util.*;
class LinkedList{
public static void main(String[] args) {
Scanner sc= new Scanner (System.in );
LinkedList<Integer>list=new
LinkedList<>();
System.out.println("Enter how many
elements you want");
int num=sc.nextInt();
for(int i=0;i<num;i++){
System.out.println("Enter element
at index "+i);
list.add(sc.nextInt());
}
System.out.print(list+" ");
}
}

Dynamically defined list

Hi I'm trying to make a simple program that prints out the elements
of a list.The catch is that the list should be dynamically initialized from
the console(the user must be able to input as much as elements he wants),and
then the program has to print on the console.
I wrote this code,but it's giving me some errors at line 13:
Error:
Multiple markers at this line
Syntax error on token "(", ; expected
void is an invalid type for the variable-"keyPressed"
Syntax error on token ")", ; expected
Code:
import java.util.ArrayList;
import java.util.Scanner;
import java.awt.*;
import java.awt.event.*;
public class test2 {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList();
void keyPressed(KeyEvent e) {
for(Integer i = 0;i < list.size();i++){
i = (Integer) in.nextInt();
list.add(i);
if(e.getKeyCode() == KeyEvent.VK_ENTER){
System.out.println();
}
}
}
}
}
keyPressed method has to be defined outside the main method. Also, the body of your for loop won't be executed as the list is empty. You need to loop - "while" - until the user inputs the "KeyEvent.VK_ENTER" and then exit the loop and print the list.
Probably easier to do something like this instead of trying to capture each key press:
import java.util.ArrayList;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList();
while(in.hasNextInt())
{
list.add(in.nextInt());
}
System.out.println("Invalid integer entered.");
System.out.println("List contents:");
for(int i : list)
{
System.out.print(i + " ");
}
}
}
Scanner in = new Scanner(System.in);
int nextInt = in.nextInt();
List<Integer> list = new ArrayList<>(nextInt);
for (int i = 0; i < nextInt; i++) {
list.add(in.nextInt());
}
for (Integer integer : list) {
System.out.println(integer);
}
code to store and print value of dynamic length of list with dynamic value input

while there is input from user

I'm new to java. In my program, I have the user enter the integers that are being added to an array list. I need to set up a while loop that will be something like this:
arrayList = new ArrayList<int>;
int i = scanner.nextInt();
while(there is input from user)
{
arrayList.add(i);
}
I expect the user to enter 5 values. What do I put as the condition statement of the while loop. In other words, how do I say "while there is input?" Thanks
Try something along the lines of
while(scanner.hasNextInt())
{
arrayList.add(i);
}
import java.util.Scanner;
import java.util.ArrayList;
public class A {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList arrayList = new ArrayList<Integer>();
int input;
for (int i = 0; i < 5; i++)
{
input = scan.nextInt();
arrayList.add(input);
}
}
}
I tried below code and tested its working fine. let me know if u want another requirements.
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
public class test {
public static void main(String args[]){
Scanner scan = new Scanner(System.in);
ArrayList<Integer> arr = new ArrayList<Integer>();
System.out.print("enter 5 numbers");
int counter=1;
while(scan.hasNextInt()){
int i=scan.nextInt();
arr.add(i);
counter++;
if(counter==5){
scan.close();
break;
}
}
}
}
I believe, you're currently accepted answer has a very fatal (it never updates i). What you need is something more like this -
// arrayList = new ArrayList<int>; // And arrayList isn't a great name. But I have
// no idea what they actually are. So
// just use a short name.
List<Integer> al = new ArrayList<Inteeger>(); // <-- Use the interface type?
// And, you have to use the wrapper type.
// int i = scanner.nextInt();
while (scanner.hasNextInt())
{
al.add(scanner.nextInt()); // You don't need `i`.
}

Can't get my Scanner to work with ArrayList

Hi sorry in advance about my bad code haha. I'm trying to get my code to read out what I type in the keyboard (only one phrase) forwards and then backwards however I keep getting errors with every different method I try.
import java.util.ArrayList;
import java.util.Scanner;
class hw
{
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
ArrayList<String> sal = new ArrayList<String>();
sal.add(kb.next());
sal.add(kb.next());
sal.add(kb.next());
display(sal);
displayb(sal);
}
public static void display(ArrayList<String> sal)
{
for (int i=0; i<sal.size(); i++)
System.out.print(sal.get(i)+ " ");
System.out.println();
}
public static void displayb(ArrayList<String> sal)
{
for (int z = sal.size(); z >= 1; z--)
System.out.print(sal.get(z-1) + " ");
System.out.println();
}
}
I know this has something to do with using a while loop and something like
String s;
s = kb.next();
but I keep getting infinite loops and other errors with everything I try. Any ideas?
I am quite sure code is ok, you need to make following change though.
Scanner kb = new Scanner(System.in);
ArrayList<String> sal = new ArrayList<String>();
sal.add(kb.next());
sal.add(kb.next());
**Sal.add(kb.next());**
here replace "Sal" with "sal"
For simple constant adding using a while loop, you need some type of termination condition:
int i = 0;
while (i < 5) {
sal.add(kb.next());
i++;
}
/* or */
String last = "";
while (!last.equals("end")) {
last = kb.next();
sal.add(last);
}

Polymorphic sorting conversion in Java

I need help with the below problem. First I have listed the Numbers.java, and below that is my attempt at Strings.java. Please help!
Write a program Strings.java, similar to Numbers.java, that reads in an array of String objects and sorts them. You may just copy and edit Numbers.java.
package hw05;
/*
Demonstrates selectionSort on an array of integers.
*/
import java.util.Scanner;
public class Numbers {
// --------------------------------------------
// Reads in an array of integers, sorts them,
// then prints them in sorted order.
// --------------------------------------------
public static void main(String[] args) {
Integer[] intList;
int size;
Scanner scan = new Scanner(System.in);
System.out.print("\nHow many integers do you want to sort? ");
size = scan.nextInt();
intList = new Integer[size];
System.out.println("\nEnter the numbers...");
for (int i = 0; i < size; i++)
intList[i] = scan.nextInt();
Sorting.selectionSort(intList);
System.out.println("\nYour numbers in sorted order...");
for (int i = 0; i < size; i++)
System.out.print(intList[i] + " ");
System.out.println();
}
}
My Strings class
package hw05;
/*
Demonstrates selectionSort on an array of strings.
*/
import java.util.Scanner;
public class Strings {
// --------------------------------------------
// Reads in an array of strings, sorts them,
// then prints them in sorted order.
// --------------------------------------------
public static void main(String[] args) {
String[] stringList;
String size;
Scanner scan = new Scanner(System.in);
System.out.print("\nHow many strings do you want to sort? ");
size = scan.nextLine();
stringList = new String[size];
System.out.println("\nEnter the strings...");
for (String i = 0; i < size; i++)
stringList[i] = scan.nextLine();
Sorting.selectionSort(stringList);
System.out.println("\nYour strings in sorted order...");
for (String i = 0; i < size; i++)
System.out.print(stringList[i] + " ");
System.out.println();
}
}
You're going to get an error because of this declaration here:
String size;
As you are using it later as an integer:
stringList = new String[size];
You should use Integer.parse like this:
stringList = new String[Integer.parseInt(size)];
But you are using size later again for your loops, so I would suggesting reverting it back to an int like you have in your Numbers.java. Be sure to change your scanner back to:
scan.nextInt();
Other than this, I can't see any other problems. Maybe if you posted the output and pointed out what wasn't working?

Categories