Dynamically defined list - java

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

Related

Java program while run again pops up error message

When I input Y (trying to run this program again), it does not compile. The first time is good.
But the second try is not working.
I don't know what is going on, please help me through this.
The program is like reading a seat arrangement file and put them into a 2D array. I am trying to use the function to read the file and display the seat arrangement. But it can only run one time.
package Tickets;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
public class Main
{
public static void main(String[] args) throws Exception
{
Scanner sc = new Scanner(new BufferedReader(new FileReader("A1.txt")));
int rows = 0;
int cols = 0;
char again;
Scanner input = new Scanner(System.in);
do
{
displayMenu();
switch(input.nextInt())
{
case 1:
System.out.println("\tReserve seat\t\n");
readFile(sc,rows,cols);
// Get user input
int rowNumber = 0;
char startingSeatNumber = 'Y';
break;
case 2:
System.out.println("Exiting the program");
System.exit(0);
break;
default:
System.err.println("Unrecgnized option");
}
System.out.println("Again?(Y/N)");
again = input.next().charAt(0);
}while (again == 'Y' || again == 'y');
}
public static List<String> readFile(Scanner sc, int rows, int cols) throws Exception
{
List<String> stringList = new ArrayList<>();
while (sc.hasNext())
{
stringList.add(sc.nextLine());
}
rows = stringList.size();
cols = 0;
if (rows > 0 )
{
cols = stringList.get(0).length();
}
// Display current seating.
char[][] auditorium = new char[rows][cols];
char alphabet = 'A';
for (int i = 1; i <= stringList.get(0).length(); i++)
{
System.out.print(" " + alphabet);
alphabet++;
}
System.out.println();
for (int r = 0; r < rows; r++)
{
System.out.print((r+1 ) );
for (int c = 0; c < cols; c++)
{
auditorium[r][c] = stringList.get(r).charAt(c);
System.out.print(auditorium[r][c]+ " ");
}
System.out.println();
}
return stringList;
}
public static void displayMenu()
{
System.out.println("1. Reserve Seats\n2. Exit");
}
}
Error message:
ok here is what is going on,
you created Scanner sc in you static void main method which you then pass to readFile. you read the file and update the stringList list object.
1) iteration one proceeds as it should since it is the first pass on the file and Scanner object has not yet opened the buffer. It opens it, reads it and the stringList is populated.
2) in iteration two, the same scanner object is passed! but the object has already read the entire buffer! so the following never executes:
while (sc.hasNext())
{
stringList.add(sc.nextLine());
}
and then you run into a runtime exception (out of bounds ) when you try to access the stringList.get(0).length() since it is an empty list!
please try to create a local Scanner sc = new Scanner(new BufferedReader(new FileReader("A1.txt"))); inside the readFile method instead of passing the sc object.

Selection sort with arrays from keyboard in java

Good Morning,
I'm trying to write a code where the user writes some numbers in the keyboard (casually), and the program should write them in order, from the lower to greater.
I don't remember in particular how to insert the number from the keyboard to the array or to the arraylist class if i don't want any limit.
This is my code. i know it is not correct.
import java.util.*;
class Ordine {
public static void main (String [] args) {
Scanner s = new Scanner (System.in)
System.out.println; ("insert the number which you need to order");
int n = s.nextInt();
int [] x = new int [200];
for (int i=0; i<x.length; i++) {
x [i] = s.nextInt();
for (int j=i+1; j<x.length; j++) {
if (x[i] > x[j]) {
//cambia ELEMENTI
int temp = x[i];
x[i] = x[j];
x[j] = temp;
}
}
}
}
}
Thank you!
Since array have fixed size you will have to use arraylist. Below is the code
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class test{
public static void main(String[] args){
Scanner in=new Scanner(System.in);
ArrayList<Integer> a = new ArrayList<Integer>(Arrays.asList(1,2,3,4,8,9,10,13));
try{
while (true)
{
int l=0;int r=a.size()-1,m=0;
int p=in.nextInt();
while(l<=r){
m=(l+r)/2;
if(a.get(m)>p){
l=l;r=m-1;
}
if(a.get(m)<p){
l=m+1;r=r;
}
if(a.get(m)==p){
l=m;
break;
}
}
a.add(l,p);
System.out.println("Entered number is: "+p);
System.out.print("Sorted arraylist is: ");
for(int j=0;j<a.size();j++){
System.out.print(a.get(j)+" ");
}
System.out.println();
}
}
catch(Exception e){
}
}
}
I have intitialized the arraylist. And it will print the ordered arraylist everytime you enter a new number.
Below is a sample output

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);
}

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

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()+" ");
}
}
}
}

Categories