ArrayList Scanner input help Java - java

I am trying to write a code where you sort a given list of numbers, and I'm trying to do so using ArrayList. I am using a while loop to allow for repeated inputs. This is my code:
import java.util.Scanner;
import java.util.ArrayList;
public class sortinggg {
public static Scanner keyboard = new Scanner(System.in);
public static ArrayList<Integer> number = new ArrayList<Integer>();
public static void main (String [] args) {
int count= 0;
System.out.println("Enter your numbers.");
while (keyboard.hasNextInt()); {
number.add(keyboard.nextInt());
}
The integer count is irrelevant right now, as I only use it when I am sorting the list.
The problem is that after I input my numbers, even if I type in a string (for example), the program doesn't move on to the next line of code. Am i missing anything here?
P.S. I tired looking up questions that have been asked previously on this topic, but none of the solutions suggested worked for me.Thank you for your help in advance!

Try this:
import java.util.ArrayList;
import java.util.Scanner;
public class Main
{
public static void main(String args[])
{
Scanner keyboard = new Scanner(System.in);
ArrayList<Integer> number = new ArrayList<Integer>();
System.out.println("Enter your numbers:");
while (keyboard.hasNextInt()) {
number.add(keyboard.nextInt());
}
}
}
Modifications:
In while (keyboard.hasNextInt()); remove semicolon(;) at the end.
Here while loop will keep adding values to the arraylist until you provide int values.

In the first place the ; just after the while is wrong. It does not let you to execute the body. Then how are you going to skip the loop. You may ask the end user to enter some special value and use it to break the loop. The corrected version is given below.
public static void main(String[] args) {
int count = 0;
System.out.println("Enter your numbers or -1 to skip.");
while (keyboard.hasNextInt()) {
int num = keyboard.nextInt();
if (num == -1) {
break;
}
number.add(num);
}
System.out.println(number);
}

Related

how to use the same input for two different scanners in two methods with formatted input

I realized the issue was due to me creating a new scanner/reader object(the new scanner has a blank input), the issue still persists - how do I use the same input stream for both methods (or) how do I use the same scanner reader for both methods
Original question: how to pass on the main method input stream to called method
So I'm taking in formatted input which is like this from geek for geeks (this is important to my error)
1
4
1 2 3 4
And I am using scanner class to read the numbers into variables. This is my code
// code to print reverse of input string after reading the length of the string and no. of testcases
class Main {
public static void main (String[] args) {
int i,t,n;
String x,y;
Scanner scan = new Scanner(System.in);
try {
t=scan.nextInt();
scan.nextLine();
REV rv=new REV();
for (i=0;i<t;i++){
rv.reverse();
}
}catch (Exception e){
return;
}
}
}
class REV{
public void reverse(){
int i,a[],n;
Scanner scan = new Scanner(System.in);
try {
n=scan.nextInt();
scan.nextLine()
a= new int[n];
for (i=n-1;i>=0;i--){
a[i]=scan.nextInt();
}
System.out.println(a[i]);
}catch(Exception E){
return;
}
}
}
I get no output for this (java.util.NoSuchElementException if I don't use try and catch)
I am able to read the variables in the main method but my input stream becomes empty for the new method
I verified this by using nextLine() both in the main() method and reverse() method as shown
public static void main (String[] args) {
int t,n;
String x,y,z;
t=scan.nextInt();
x=scan.nextLine();
n=scan.nextInt(); //to eat up the n input
y=scan.nextLine();
z=scan.nextLine();
System.out.println(x+y);
....
}
output-
141 2 3 4
and
public void reverse(int n){
....
String k,j;
k = scan.nextLine(); //replacing n- to check what n=scanInt() reads
j= scan.nextLine();
System.out.println(x +y);
....
}
Output is blank again (java.util.NoSuchElementException)
I think this means the input stream is empty for the reverse() method.
So how do I pass on the main() input to reverse()
Note: 1. if I don't use try{} and catch{} it gives me java.util.NoSuchElementException
I'm aware I have made the code needlessly a little complicated, this is due to me trying to solve this problem
I got the try{} and catch{} solution from here, but it doesn't solve my empty input problem
4.This made me understand the empty input exception
Create a method instead of making an Object of a class and then calling the method. (Unless you want it that way).
Create a single static Scanner and use it everywhere.
private static Scanner scanner = new Scanner(System.in)
To print an array use System.out.println(Arrays.toString(a));.
Reductant use of scanner.nextLine() after Scanner.nextInt.
import java.util.Arrays;
import java.util.Scanner;
class Main {
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
int i, t, n;
String x, y;
t = scanner.nextInt();
for (i = 0; i < t; i++) {
reverse();
}
}
private static void reverse() {
int i;
int[] a;
int n;
n = scanner.nextInt();
a = new int[n];
for (i = n - 1; i >= 0; i--) {
a[i] = scanner.nextInt();
}
System.out.println(Arrays.toString(a));
}
}
Is this your desired output?

Input and store an arbitrarily long sequence of numbers

So, this is basically what I have to do:
Ask the user to enter as many ints as they want, and tell them to type “done” when they are done entering the numbers.
Store these numbers in a data structure. (Think carefully about which one to use.)
Write a method that computes the sum of all the elements in the data structure.
Write a method that finds the smallest positive number in the data structure (return 9999 if there aren’t any positive numbers).
Call these methods on the data structure with the user’s numbers.
I have already written some of the code, but it's taking me no where.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
if (in.hasNextInt())
System.out.println(in.nextInt());
else
in.next();
}
}
}
By using the Java8 stream we could write this more efficiently and in a fewer lines of code than using the equivalent for loop.
import java.util.*;
class Main {
// Returns an array containing all inputted integers.
public static int[] getInts() {
List<Integer> list = new ArrayList<Integer>();
System.out.println("Enter integers or done to exit and press enter: ");
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
if (in.hasNextInt())
list.add(in.nextInt());
else if (in.next().equals("done"))
break;
}
return list.stream().mapToInt(i->i).toArray();
}
// Returns the sum of the integers, if the array is empty it returns 0.
public static int sum(int[] arr) {
return Arrays.stream(arr).sum();
}
// Returns 9999 if the array is empty or only has negative integers.
public static int min(int[] arr) {
return Arrays.stream(arr).filter(i -> i > 0).min().orElse(9999);
}
public static void main(String[] args) {
int[] arr = getInts();
System.out.println(Arrays.toString(arr));
System.out.println(sum(arr));
System.out.println(min(arr));
}
}
Output:
Enter integers or done to exit and press enter:
5 3 1 done // Our Input.
[5, 3, 1]
9
1
Here is a change that will lead you into the right direction:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
if (in.hasNextInt()) {
addNumber(in.nextInt());
} else {
final String string = in.next();
if ("done".equals(string.toLowerCase())) {
compute();
} else {
System.err.println("Invalid input " + string + ". Aborting...");
}
return;
}
}
}
private static void compute() {
// Do your magic here
}
private static void addNumber(int number) {
// Change this to code that stores the number
System.out.println(number);
}
EDIT: Some insight in what has changed. The very basic structure you had was alright. I mean, you got the right idea. I added the addNumber() method that will be called every time you get a number in the input. Now, inside that method you can write code for storing the value in a set or list maybe.
Then, if the input doesn't get a integer we just get whatever it is as a string a compare to "done". If it's equal we call compute() method. Inside that method you should write code that computed whatever calculation you are requested to do. Using the values in the set/list.
If the string isn't "done" we consider that an error.

How do I loop nextInt to define variables in an array?

the question I've asked isn't too clear but essentially I have been tasked to:
Write a program to read in 5 integer numbers from the user. You
should store the numbers in an array.
Use loops for efficiency.
I would know how to do this if it weren't for loops, however I am unsure how to use loops for this certain task.
What I have is this (I know this is completely wrong I was just trying to base it on the example from the book).
import java.util.Arrays;
import java.util.Scanner;
public class fivenumbersloops {
public static void main(String[] args)throws Exception {
Scanner aids = new Scanner(System.in);
int[] numbers = new int[5];
do
{
System.out.println("Enter a whole number: ");
numbers[0] = aids.nextInt();
numbers[0]++;
}while (numbers[0]==numbers[5]);
}
}
I know it's the bottom bit which is completely wrong, but if someone could help point me in the right direction I would appreciate it.
What you want is a for loop. This for loop initializes the variable i to 0, continues while i is less than 5 and increments i for each iteration. The variable i is used to specify the position to place the input number into the array.
public static void main(String[] args) throws Exception {
Scanner aids = new Scanner(System.in);
int[] numbers = new int[5];
for (int i = 0; i < 5; i++) {
System.out.println("Enter a whole number: ");
numbers[i] = aids.nextInt();
}
}

Why does my scanner ask for input every three lines?

Does anyone know why my scanner is asking for input every three lines, rather than every one line? If you run it, you will see that it asks the question first, but then doesn't for two more lines, then it asks the question again. How do I get it to ask a question every line, let alone store it in a linked list.
import java.util.Scanner;
public class StackCalc {
public static StackLL stackll = new StackLL();
public static void create() {
String hold = new String();
Scanner scanner = new Scanner(System.in);
boolean running = true;
while (true) {
System.out.print("Enter number, math operation(+,-,*, or /), or Q to quit: ");
hold = scanner.next();
if (scanner.next().equals("Q") || scanner.next().equals("q")) {
System.out.println(hold);
break;
}
}
}
public static boolean checkInt(String s, int it){
Scanner scan = new Scanner(s.trim());
if(!scan.hasNextInt(it))
return false;
scan.nextInt(it);
return !scan.hasNext();
}
public static void main(String args[]) {
create();
}
}
Any input would be awesome.
It is because you are using the method Scanner.next() three times:
hold = scanner.next()
scanner.next().equals("Q")
and scanner.next().equals("q")
Instead, only call it once by changing:
scanner.next().equals("Q") to hold.equals("Q")
and
scanner.next().equals(q") to hold.equals("Q")

SPOJ PALIN NZEC Error

I have used the following code for the question but it keeps giving me NZEC error when I submit it on SPOJ. My code runs perfectly on Eclipse or through cmd.
import java.util.Scanner;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
int line,num,numb,rev = 0,r,i,flag;
ArrayList <Integer> nums=new ArrayList <Integer>();
Scanner b=new Scanner(System.in);
Scanner a=new Scanner(System.in);
line=b.nextInt();
for(i=0;i<line;i++)
{flag=0;
num=a.nextInt();
num=num+1;
numb=num;
do {
while(numb>0)
{r=numb%10;
rev=(rev*10)+r;
numb=numb/10;
}
if (rev==num)
{nums.add(num);
rev=0;
flag=1;
break;
}
else
{num=num+1;
numb=num;
rev=0;}
}while(flag==0);
}
for (int newnum : nums)
{System.out.println(newnum);}
}
}
the mistake that you are doing is that you are storing num in an integer datatype..the constraint says that
K of not more than 1000000 digits(it is digits and not up to that number)
It is impossible for an integer to store such a huge number..so you have to use string to solve this particular problem..try this input in your eclipse
454646546546546546546546464646464646
you will realize where you are wrong

Categories