Scanner : Exception in thread "main" java.util.NoSuchElementException - java

I'm trying to create an Utility Class to take inputs from the Standard Console using java.util.Scanner
package dbasics;
import java.util.*;
public class Utils {
public static int getNumericInput() {
System.out.println("Enter a integer ");
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
scanner.close();
return n;
}
public static int[] getNumericArrayInput(int n) {
//System.out.println("Enter "+n+" integers seperated by a whitespace ");
int[] numbers = new int[n];
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < n; i++) {
numbers[i] =scanner.nextInt();
}
scanner.close();
return numbers;
}
}
While calling the static methods in another class the method getNumericInput() works fine however the following method getNumericArrayInput(int n) results in an exception.
package dbasics;
public class Demo {
public static void main(String[] args) {
int n = Utils.getNumericInput();
System.out.println("Number "+n);
int arr[] = Utils.getNumericArrayInput(n);
for(int i : arr) {
System.out.println(i);
}
}
}
Running this results in following exception
Enter a integer
5
Number 5
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at dbasics.Utils.getNumericArrayInput(Utils.java:21)
at dbasics.Demo.main(Demo.java:9)
The intresting thing I have noticed is if I comment out the first input procedure the array input works fine

You are closing Scanner in your function that is causing in Exception:
Try this:
import java.util.*;
class Utils {
public static int getNumericInput() {
System.out.println("Enter a integer ");
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
return n;
}
public static int[] getNumericArrayInput(int n) {
int[] numbers = new int[n];
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < n; i++) {
numbers[i] =scanner.nextInt();
}
scanner.close();
return numbers;
}
}
public class cn {
public static void main(String[] args) {
int n = Utils.getNumericInput();
System.out.println("Number "+n);
try{
int arr[] = Utils.getNumericArrayInput(n);
for(int i : arr) {
System.out.println(i);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
For more information please read this link

In the first method, don't close the scanner

Related

I am trying to use user input in an arraylist

I was going all over the internet looking for something to help me with this problem. I learned how to make an arrayList, but i want to know how to make it acceptable user input. What i mean by that is that i want the user to input his number.
Here is what i have:
public class MyClass {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
ArrayList<Integer> myList=new ArrayList<Integer>(10);
System.out.println("Enter your number:");
myList.add(416355);
myList.add(21212);
for(int x : myList)
System.out.println(x);
System.out.println("Size="+myList.size());
}
}
What i have now is the numbers i have put in there. Any help is greatly appreciated.
Thanks in advance.
These two lines of code are necessary to get the user input into the ArrayList:
int n = input.nextInt();
myList.add(n);
So the full code would read:
public class MyClass {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
ArrayList<Integer> myList=new ArrayList<Integer>(10);
System.out.println("Enter your number:");
int n = input.nextInt();
myList.add(n);
myList.add(416355);
myList.add(21212);
for(int x : myList)
System.out.println(x);
System.out.println("Size="+myList.size());
}
}
You might find this helpful: How can I get the user input in Java?
public class MyClass {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
ArrayList<Integer> myList=new ArrayList<Integer>(10);
System.out.println("Enter your number:");
int totalNumbers = 2;
for (int i = 0; i < totalNumber; i++) {
myList.add(input.nextInt());
}
for(int x : myList)
System.out.println(x);
System.out.println("Size="+myList.size());
}
}
import java.util.ArrayList;
import java.util.Scanner;
public class MyClass {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<Integer> myList = new ArrayList<Integer>(10);
int totalNumbers = 10;
for (int i = 0; i < totalNumbers; i++) {
System.out.println("ENTER Element to add into list");
Scanner element = new Scanner(System.in);
int ele = (element .nextInt());
myList.add(ele);
}
for (int x : myList)
System.out.println(x);
System.out.println("Size=" + myList.size());
}
}
So the full code would read:
As I understood you want to capture user data and save it into an array;for each input element you need to create a variable:
import java.util.ArrayList;
import java.util.Scanner;
public class MyClass {
public static void main(String[] args) {
ArrayList<Integer> myList=new ArrayList<Integer>(10); enter code here
System.out.println("Enter your number:");
Scanner input=new Scanner(System.in);
int a = input.nextInt();
int b = input.nextInt();
myList.add(a);
myList.add(b);
for(int x : myList)
System.out.println(x);
System.out.println("Size="+myList.size());
}
}
import java.util.ArrayList;
import java.util.Scanner;
public class Average
{
public static void main(String[] args)
{
ArrayList<Double> numbers = new ArrayList<Double>();
Scanner in = new Scanner(System.in);
System.out.println("Please enter a list of numbers: ");
while (in.hasNextDouble())
{
double input = in.nextDouble();
numbers.add(input);
}
if (numbers.size() == 0)
{
System.out.println("No average.");
}
else
{
double total = 0;
for (double element : numbers)
{
total = total + element;
}
double average = total / numbers.size();
System.out.println("The average is: " + average);
}
}

Resource leak: 'sc' is never closed

Program to count how many times a particular character, letter or number occur in a sentence.
However I keep getting message:
Resource leak: 'sc' is never closed
I am using Java and Eclipse. What should I do?
import java.util.Scanner;
class Number-count {
public static void number - count(String args[]) {
String s;
char ch;
int count = 0;
Scanner SC = new Scanner(System. in );
System.out.println("Enter a sentence");
String str = sc.nextLine();
System.out.println("Enter a character to be searched for occurence");
s = sc.nextLine();
char c = s.charAt(0);
for (int i = 0; i < str.length(); i++) {
ch = str.charAt(i);
if (ch == c) {
count++;
}
}
System.out.println("Character " + c + " occur " + count + " times");
}
}
Scanner objects need to be closed after one is done using them. So, after you're done with it you should call the following before the end of your main method
SC.close();
after your scanner work completed put: sc.close();
It is working 100%
Try this code
public static void number - count(String args[]) throws IOException {
Scanner sc = new Scanner(System.in);
try{
//your code
}
finally {
sc.close();
}
}
If you want to use the scanner globally in a class(which is the case sometimes)
try this:
static Scanner sc = new Scanner(System.in);
/* Making it easy for beginners, when we use Scanner sc it is required to be close once we have taken all inputs from user, to close use sc.close(); */
package basicjava;
import java.util.*;
public class sumbyuser {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter your numbers for summation : ");
int a = sc.nextInt();
int b = sc.nextInt();
sc.close();
int sum = a+b;
System.out.println("Summation is : "+sum);
}
}
Try sc.close();
After the using the scanner inputs :
import java.util.*;
public class Func1 {
public static void CalculateSum() {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
sc.close();
int sum = a + b;
System.out.println("The sum is " + sum);
}
public static void main(String[] args) {
CalculateSum();
}
}

read multiple inputs from same line in java

Here is my code snippet
public void m1(int a) // a value passed from main
{
for(int i=0;i<a;i++)
{
// Read "a" inputs from the user one by one
}
}
public static void main(String[] args)
{
int a;
// read value of a from user
m1(a)
}
Can U please tell me how to give this input in one line.
Like in the same line we need to provide the value of a and also should take a values from user.
eg:enter code here
a=6. 6 values from user
6 22 33 44 55 66
6 and the 6 inputs from the user should be in the same line (given by the user at the same time).
You could go this way:
public class Number {
static Scanner sc = new Scanner(System.in);
static int arr[];
public static void read(int a)
{
arr = new int[a];
for (int i = 0; i < a; i++) {
arr[i] = sc.nextInt();
}
}
public static void main(String args[]) {
System.out.print("Enter numbers here : ");
int a = sc.nextInt();
read(a);
// printing the array
for (int i = 0; i < a; i++) {
System.out.print(arr[i]+" ");
}
System.out.println("");
}
}
But better and cleaner way will be returning the array from read method:
public class Number {
static Scanner sc = new Scanner(System.in);
public static int[] read(int a)
{
int arr[] = new int[a];
for (int i = 0; i < a; i++) {
arr[i] = sc.nextInt();
}
return arr;
}
public static void main(String args[]) {
System.out.print("Enter numbers here : ");
int a = sc.nextInt();
int numbers[] = read(a);
// printing the numbers array
for (int i = 0; i < a; i++) {
System.out.print(numbers[i]+" ");
}
System.out.println("");
}
}
Input:
Enter numbers here : 4 1 2 3 4
Output:
1 2 3 4
Solve that your problem? I haven't understand exactly what you want, but with this you can do anything, or not?
public static void m1(String[] a) // a value passed from main
{
for (int i = 1; i < a.length; i++) {
// Read "a" inputs from the user one by one
System.out.println(a[i]);
}
}
public static void main(String[] args) {
m1(args);
}
public static void m1(int a) // a value passed from main
{
Scanner scan = new Scanner(System.in);
int arr[] = new int[a];
for(int i=0;i<a;i++)
{
arr[i]=scan.nextInt();
}
}
public static void main(String[] args)
{
int a=(int) 6.6;
// read value of a from user
m1(a);
}
Input:
1 -2 "nonumber" 34
Output:
1
-2
34
Code:
String line = scanner.nextLine();
Pattern p = Pattern.compile("-?\\d+");
Matcher m = p.matcher(line);
while (m.find()) {
System.out.println(m.group());
}
First, a couple of quick pointers:
- Name your methods something more practical than m1()
- Make sure you end your statements with a semi-colon ( e.g m1() )
- You need to define m1() as static, or otherwise instantiate the class which contains m1()
- Learn about Scanners and Arrays; you must import a library to use a Scanner object. ( import java.util.Scanner; )
public static void storeIntegers(int a){
//This is how you declare an array.
int[] someIntArray = new int[a];
//You must create a Scanner object to take in user input.
Scanner userInput = new Scanner(System.in);
for(int i = 0; i < a; i++){
someIntArray[i] = userInput.nextInt();
}
// Just to make sure it worked.
for(int e = 0; e < someIntArray.length; e++){
System.out.println(someIntArray[e]);
}
}// End storeIntegers()
public static void main(String[] args){
Scanner userInput = new Scanner(System.in);
System.out.println("How many numbers?");
int a = userInput.nextInt();
storeIntegers(a);
}// End main()

Small addition to current code

import java.util.Scanner;
public class linecounter {
public static void main(String[] args) {
System.out.print("Enter a line of integers ");
Scanner chopper = new Scanner(System.in);
int x = chopper.nextInt();
while (chopper.hasNextInt()) {
System.out.println(chopper.nextInt());
}
}
}
I am in a CS1 class learning the basics of Java and have a quick question, on this code could anyone tell me how i could get it to keep count of how many integers were typed in?
Thank you
above your while loop, declare:
int count = 0;
then in your while loop use
count++;
This will start you at 0 and every time it increments the count
You could add a counter to the while loop.
int counter = 0;
while (chopper.hasNextInt()) {
counter++;
System.out.println(chopper.nextInt());
}
System.out.println(counter);
In the cases that you have integer numbers, double numbers and you only need count the integer numbers, you can use:
public class linecounter {
public static void main(String[] args) {
System.out.print("Enter a line of integers ");
Scanner chopper = new Scanner(System.in);
int x = chopper.nextInt();
int counter = 0;
while (chopper.hasNextInt()) {
System.out.println(chopper.nextInt());
String myCurrentArg = chopper.nextInt();
if(isInteger(myCurrentArg) ){
counter++;
}
}
System.out.println("The number of integer arguments are: " + counter);
}
public static boolean isInteger(String s) {
return isInteger(s,10);
}
}

How to put a Scanner input into an array... for example a couple of numbers

Scanner scan = new Scanner(System.in);
double numbers = scan.nextDouble();
double[] avg =..????
You could try something like this:
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
double[] numbers = new double[5];
for (int i = 0; i < numbers.length; i++)
{
System.out.println("Please enter number");
numbers[i] = input.nextDouble();
}
}
It seems pretty basic stuff unless I am misunderstanding you
You can get all the doubles with this code:
List<Double> numbers = new ArrayList<Double>();
while (scan.hasNextDouble()) {
numbers.add(scan.nextDouble());
}
import java.util.Scanner;
public class Main {
/**
* #param args
*/
public static void main(String[] args) {
Scanner in=new Scanner (System.in);
int num[]=new int[10];
int average=0;
int i=0;
int sum=0;
for (i=0;i<num.length;i++) {
System.out.println("enter a number");
num[i]=in.nextInt();
sum=sum+num[i];
}
average=sum/10;
System.out.println("Average="+average);
}
}
**Simple solution**
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int size;
System.out.println("Enter the number of size of array");
size = sc.nextInt();
int[] a = new int[size];
System.out.println("Enter the array element");
//For reading the element
for(int i=0;i<size;i++) {
a[i] = sc.nextInt();
}
//For print the array element
for(int i : a) {
System.out.print(i+" ,");
}
}
For the values of the array given by separated with space " " you can try this cool one liner Java 8 & onwards suppported streams based solution:
Scanner scan = new Scanner(System.in);
double[] arr = Arrays.stream(scan.nextLine()
.trim()
.split(" "))
.filter(x -> !x.equals(""))
.mapToDouble(Double::parseDouble)
.toArray();
For int array you can try:
Scanner scan = new Scanner(System.in);
int[] arr = Arrays.stream(scan.nextLine()
.trim()
.split(" "))
.filter(x -> !x.equals(""))
.mapToInt(Integer::parseInt)
.toArray();
With filter() method you can also avoid more than one spaces in between the inputs.
Complete code reference:
import java.util.Scanner;
import java.util.Arrays;
public class Main{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
double[] arr = Arrays.stream(scan.nextLine()
.trim()
.split(" "))
.filter(x -> !x.equals(""))
.mapToDouble(Double::parseDouble)
.toArray();
for(double each: arr){
System.out.print(each + " ");
}
}
}
Input: 1 2 3 4 5 6 7 8 9
Output: 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0
If you observe carefully, there are extra spaces in between the input randomly, that has also been handled with line .filter(x -> !x.equals("")) so as to avoid blank inputs ("")
import java.util.Scanner;
class Array {
public static void main(String a[]){
Scanner input = new Scanner(System.in);
System.out.println("Enter the size of an Array");
int num = input.nextInt();
System.out.println("Enter the Element "+num+" of an Array");
double[] numbers = new double[num];
for (int i = 0; i < numbers.length; i++)
{
System.out.println("Please enter number");
numbers[i] = input.nextDouble();
}
for (int i = 0; i < numbers.length; i++)
{
if ( (i%3) !=0){
System.out.print("");
System.out.print(numbers[i]+"\t");
} else {
System.out.println("");
System.out.print(numbers[i]+"\t");
}
}
}
double [] avg = new double[5];
for(int i=0; i<5; i++)
avg[i] = scan.nextDouble();
This is a program to show how to give input from system and also calculate sum at each level and average.
package NumericTest;
import java.util.Scanner;
public class SumAvg {
public static void main(String[] args) {
int i,n;
System.out.println("Enter the number of inputs");
Scanner sc = new Scanner(System.in);
n=sc.nextInt();
int a[] = new int [n];
System.out.println("Enter the inputs");
for(i=0;i<n;i++){
a[i] = sc.nextInt();
System.out.println("Inputs are " +a[i]);
}
int sum = 0;
for(i=0;i<n;i++){
sum = sum +a[i];
System.out.println("Sums : " +sum);
}
int avg ;
avg = sum/n;
System.out.println("avg : " +avg);
}
}
List<Double> numbers = new ArrayList<Double>();
double sum = 0;
Scanner scan = new Scanner(System.in);
while(scan.hasNext()){
double value = scan.nextDouble();
numbers.add(value);
sum += value;
}
double average = sum / numbers.size();
public static void main (String[] args)
{
Scanner s = new Scanner(System.in);
System.out.println("Please enter size of an array");
int n=s.nextInt();
double arr[] = new double[n];
System.out.println("Please enter elements of array:");
for (int i=0; i<n; i++)
{
arr[i] = s.nextDouble();
}
}
If you don't know the size of the array, you need to define, when to stop reading the sequence (In the below example, program stops when the user introduces 0 and obviously, last zero shouldn't be taken into account).
import java.util.Scanner;
import java.util.ArrayList;
public class Main
{
public static void main (String[]args)
{
System.out.println("Introduce the sequence of numbers to store in array. Each of the introduced number should be separated by ENTER key. Once you're done, type in 0.");
Scanner scanner = new Scanner(System.in);
ArrayList<Integer> numbers = new ArrayList<Integer>();
boolean go = true;
while (go) {
int value = scanner.nextInt();
numbers.add(value);
if (value == 0) {
go = false;
numbers.remove(numbers.size() - 1);
}
}
System.out.println(numbers);
}
}
Scanner scan = new Scanner (System.in);
for (int i=0; i<=4, i++){
System.out.printf("Enter value at index"+i+" :");
anArray[i]=scan.nextInt();
}
import java.util.Scanner;
public class sort {
public static void main(String args[])
{
int i,n,t;
Scanner sc=new Scanner(System.in);
System.out.print("Enter the size of array");
n=sc.nextInt();
int a[] = new int[n];
System.out.println("Enter elements in array");
for(i=0;i<n;i++)
{
a[i]=sc.nextInt();
}
t=a[1];
for(i=0;i<n;i++)
{
if(a[i]>t)
t=a[i];
}
System.out.println("Greates integer is" +t);
}
}

Categories

Resources