while there is input from user - java

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`.
}

Related

Why doesn't my java code print out the array list?

package booking;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class CarProfile {
static int year;
static int cylinders;
static int plateNum;
public static void main(String[] args) {
int reg = 1;
ArrayList <CarProfile> list = new ArrayList <CarProfile>();
#SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
while(reg == 1) {
System.out.println("Enter manf. year");
year = sc.nextInt();
System.out.println("Enter num. of cyl");
cylinders = sc.nextInt();
System.out.println("Enter plateNum");
plateNum = sc.nextInt();
System.out.println("If you wish to register another car press 1, otherwise press anything");
reg = sc.nextInt();
}
Arrays.toString(list.toArray());
}
}
This is the code. I also tried to use a for loop with System but didn't get any luck there either. So what am I missing here?
I don't know what else to type, it is a really simple question.
You aren't calling System.out.println on the code, The code doesn't knows its suppose to print it out. so replace
Arrays.toString(list.toArray());
With
System.out.println(Arrays.toString(list.toArray()));

Create a simple java random number pick with in a certain range

I tried searching on here for something similar, but failed to find it, maybe using wrong keywords let me know, but here is the deal.
I am fairly new with java and wanted to make something useful myself.
My idea was to create a random number picker within a range with.
So let's say range is from 1-50, and I want 5 random number in this range, and they have to be all different. I have worked with Random before, but not sure what I am doing wrong, here is the code I have so far, please push me in the right direction if possible.
I want to create an array or list with the number, or is there a better way to do this?
import java.util.Scanner;
import java.util.Random;
public class Randomizer {
static Random rnd = new Random();
static int rnd(int a, int b){
return a+rnd.nextInt(b-a+1);
}
public static void nPicker(){
Scanner sc = new Scanner(System.in);
System.out.println("Enter start of range: ");
int start = sc.nextInt();
System.out.println("Enter end of range: ");
int end = sc.nextInt();
System.out.println("Enter amount of numbers to pick: ");
int c = sc.nextInt();
sc.close();
rnd(start,end);
int[] randomArrays = new int[c];
for(int i = 0; i>randomArrays.length; i++){
randomArrays.add();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
nPicker();
}
}
sorry if my code is messy.
At the moment I can't even get the random number to be added into the array
Try this, I did explain to you what is wrong with comments at the code, read them.
import java.util.Scanner;
import java.util.Random;
public class Randomizer {
static int[] randomArrays; // You need to declare the vector as an instance variable, otherwise it will disappear when the method it's done.
static Random rnd = new Random();
static int rnd(int a, int b){
return a+rnd.nextInt(b-a+1);
}
public static void nPicker(){
Scanner sc = new Scanner(System.in);
System.out.println("Enter start of range: ");
int start = sc.nextInt();
System.out.println("Enter end of range: ");
int end = sc.nextInt();
System.out.println("Enter amount of numbers to pick: ");
int c = sc.nextInt();
sc.close();
randomArrays = new int[c];
for(int i = 0; i<randomArrays.length; i++){ // The condition was wrong
int numberToAdd = rnd(start,end);
randomArrays[i] = numberToAdd; //You are not using an ArrayList, vector has not the method add(), you have to add new element to the vector throughout its index
}
}
public static void main(String[] args) {
Randomizer rdm = new Randomizer();
rdm.nPicker();
for(int number:rdm.randomArrays) {
System.out.println(number);
}
}
}
Thank you everyone for your advices and hints. In the end I think I managed to get the code how I wanted with the code below.
Tell me if you see an error in this method, or if it has a way that is not allowed in java.
import java.util.Scanner;
import java.util.Random;
import java.util.ArrayList;
import java.util.List;
public class Randomizer {
static Random rnd = new Random();
static int rnd(int a, int b){
return a+rnd.nextInt(b-a+1);
}
public static void nPicker(){
Scanner sc = new Scanner(System.in);
System.out.println("Enter start of range: ");
int start = sc.nextInt();
System.out.println("Enter end of range: ");
int end = sc.nextInt();
System.out.println("Enter amount of numbers to pick: ");
int c = sc.nextInt();
sc.close();
List randomnumbers = new ArrayList();
for(int i = 0; i<c; i++){
int numb = rnd(start,end);
if(randomnumbers.contains(numb)){
break;
}else{
randomnumbers.add(numb);
}
}
randomnumbers.forEach(System.out::println);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
nPicker();
}
}
ok in the end i changed the loops as following:
for(int i = 0; i<c;){
int numb = rnd(start,end);
while(!(randomnumbers.contains(numb))){
randomnumbers.add(numb);
i++;
}
}
randomnumbers.forEach(System.out::println);
}
seems to work fine this way

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

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