NoSuchElementException with Java.Util.Scanner with array - java

I m very new to java and don't know why I'm getting this error when I run below program
program : this program basically read no of input N in first line and then scan each number and store it in array arr and display it.
range of N is : 0<N<10^6
input numbers can be long so that I used long array in the program.
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner sc = new Scanner(System.in);
long no = sc.nextLong();
if(no > 1000000 || no < 1)
System.exit(0);
long arr[] = new long [(int)no];
for(int i=0;i<(int)no;i++) {
arr[i] = sc.nextLong();
System.out.println(arr[(int)i]);
}
}
}
input values : here you find input values
output :
Runtime Errors
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:907)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextLong(Scanner.java:2265)
at java.util.Scanner.nextLong(Scanner.java:2225)
at Solution.main(Solution.java:23)
rest of output is here

You are repeatedly calling nextLong(), but not testing to see if there is a next long:
for(int i=0;i<(int)no;i++) {
arr[i] = sc.nextLong();
System.out.println(arr[(int)i]);
}
You need do something like this:
for(int i=0;i<(int)no && sc.hasNextLong();i++) {
arr[i] = sc.nextLong();
System.out.println(arr[(int)i]);
}

It's supposed to be something like this:
import java.util.Scanner;
import java.io.InputStream;
class Solution {
public static void main(String... args) {
InputStream in;
// initialize in
Scanner scanner = new Scanner(in);
int[] numbers;
// You don't need to store long values because int values fall within 0 and 10^6
try {
numbers = new int[(scanner.hasNextInt()? scanner.nextInt(): 0)];
} catch(NegativeArraySizeException nase) {
numbers = new int[0];
}
// we store the limits in variables so that your system doesn't create them repeatedly in each iteration
for(int i = 0, number, LOW = 0, HIGH = 1000000; scanner.hasNextInt() && i < numbers.length;) {
number = scanner.nextInt();
if(number > LOW && number < HIGH) {
numbers[i] = number;
// go to next index only if we have a number
i++;
}
}
}
}

Related

ArrayList queries in java

I am solving this problem on ArrayList in HackerRank. I completed the code but there's no stdout showing on the console.
Question:
You are given lines. In each line, there are zero or more integers. You need to answer a few queries where you need to tell the number located in the Yth position of Xth line.
The first line has an integer (n). In each of the next (n) lines there will be an integer denoting the number (d) of integers on that line and then there will be (d) space-separated integers. In the next line, there will be an integer denoting q number of queries. Each query will consist of two integers (x)and (y).
I am getting a number format exception at (int)number.
Problem statement - if the number is present at x row and y position, print it otherwise print ERROR!
Input:
5
5 41 77 74 22 44
1 12
4 37 34 36 52
0
3 20 22 33
5
1 3
3 4
3 1
4 3
5 5
Output:
74
52
37
ERROR!
ERROR!
My code:
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
int n = 0;
String []problem;
int queries = 0;
int number = 0;
ArrayList<List<String>> allProblems = new ArrayList<>();
List<String> problems = new ArrayList<>();
ArrayList<List<String>> allPos = new ArrayList<>();
List<String> pos = new ArrayList<>();
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
sc.nextLine();
for(int i=0;i<n;i++)
{
problem = sc.nextLine().split(" ");
problems = Arrays.asList(problem);
allProblems.add(problems);
}
queries = sc.nextInt();
sc.nextLine();
for(int i=0;i<queries;i++)
{
pos = Arrays.asList(sc.nextLine().split(" "));
allPos.add(pos);
}
for(int i=0;i<queries;i++)
{
int x = Integer.parseInt((allPos.get(i)).get(0));
int y = Integer.parseInt((allPos.get(i)).get(1));
if(y >= allProblems.get(i).size()-1)
{
System.out.println("ERROR!");
}
else
{
number = Integer.parseInt((allProblems.get(x)).get(y+1));
System.out.println(number);
}
}
sc.close();
}
}
Please, try to use the code below. I added the comments in places where I changed something
package tests;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class Solution
{
public static void main(String[] args)
{
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
int n = 0;
String[] problem;
int queries = 0;
int number = 0;
ArrayList<List<String>> allProblems = new ArrayList<>();
List<String> problems; // removed an implementation from here, it wasn't used
ArrayList<List<String>> allPos = new ArrayList<>();
List<String> pos; // removed an implementation from here, it wasn't used
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
sc.nextLine();
for (int i = 0; i < n; i++)
{
problem = sc.nextLine().split(" ");
problems = Arrays.asList(problem);
allProblems.add(problems);
}
queries = sc.nextInt();
sc.nextLine();
for (int i = 0; i < queries; i++)
{
pos = Arrays.asList(sc.nextLine().split(" "));
allPos.add(pos);
}
sc.close(); // I closed the scanner as soon as I ended read data
// defining the return values
for (int i = 0; i < queries; i++)
{
int x = Integer.parseInt((allPos.get(i)).get(0));
int y = Integer.parseInt((allPos.get(i)).get(1));
if (y > allProblems.get(x-1).size() - 1) // the equal mark was not needed
{
System.out.println("ERROR!");
} else
{
number = Integer.parseInt((allProblems.get(x-1)).get(y)); // (x-1) instead of X and Y instead of (y+1)
System.out.println(number);
}
}
}
}

java for loop factors program

Hi I have to make a program(java) on which you input a number and it outputs the number of factors it has(EX: 4 ---> 3)
Code:
package Class;
import java.util.Scanner;
public class Profgrams {
public static void main(String[] args) {
System.out.println("Enter the number;");
Scanner scan = new Scanner(System.in);
long n = scan.nextLong();
for(int i=1, f=0; i <= n; i++){
if(n % i == 0){
f++;
}
System.out.println(f);
}
}
}
Thanks for help.
Declare and initialize f before the loop, and then print the result after the loop terminates. That way printing will not occur at each iteration of the loop.
int f = 0;
// ...
System.out.println(f);

TLE in Fast Multiplication in spoj

How can I make this code faster?
Spoj said time limit exceeded when I paste this solution.
import java.math.BigInteger;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("the number of multiplications <= 1000: ");
int n = scanner.nextInt();
if (n <= 1000) {
for (int i = 1; i <= n; i++) {
System.out.print("First number to multiply");
BigInteger l1 = new BigInteger(scanner.next());
System.out.print("Second number to multiply");
BigInteger l2 = new BigInteger(scanner.next());
if (l1.toString().length() == 10000 || l2.toString().length() == 10000) {
System.err.println("numbers to multiply should be at most 10000 decimal digits each.");
} else {
System.out.println("Product: "+l1.multiply(l2));
}
}
} else {
System.err.println("number of multiplications should be less than or equal to 1000");
}
}
}
update: I have now used a buffered reader but now I'm getting wrong answer even though my outputs are right. Here's my updated code
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
public class Main {
public static void main(String[] args) throws IOException{
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("the number of multiplications <= 1000: ");
int n = Integer.parseInt(reader.readLine());
if (n <= 1000) {
for (int i = 1; i <= n; i++) {
System.out.print("First number to multiply: ");
BigInteger l1 = new BigInteger(reader.readLine());
System.out.print("Second number to multiply: ");
BigInteger l2 = new BigInteger(reader.readLine());
if (l1.toString().length() == 10000 || l2.toString().length() == 10000) {
System.err.println("numbers to multiply should be at most 10000 decimal digits each.");
} else {
System.out.println("Product: "+l1.multiply(l2));
}
}
} else {
System.err.println("number of multiplications should be less than or equal to 1000");
}
} catch (NumberFormatException e) {
System.err.println("invalid");
}
}
}
Thanks in advance.
Reading input in java is very slow if you use Scanner. You can pass only problems with really small input using it. You should use BufferedReader and BufferedWriter if you think the input can be larger. The rest of your algorithm is correct(although this problem is meant for testing own implementation of big integer numbers instead of built-in types).
EDIT: you are getting WA because of all the helper output you print to system.out. In programming competitions you should write nothing but the answer on the standard output. Thus you need to print only the result of the multiplication. Use the example. Your output should be precisely the same for your solution to pass.

getting input from stdin

I want to get input from stdin in the for of
3
10 20 30
the first number is the amount of numbers in the second line. Here's what I got, but it is stuck in the while loop... so I believe. I ran in debug mode and the array is not getting assign any values...
import java.util.*;
public class Tester {
public static void main (String[] args)
{
int testNum;
int[] testCases;
Scanner in = new Scanner(System.in);
System.out.println("Enter test number");
testNum = in.nextInt();
testCases = new int[testNum];
int i = 0;
while(in.hasNextInt()) {
testCases[i] = in.nextInt();
i++;
}
for(Integer t : testCases) {
if(t != null)
System.out.println(t.toString());
}
}
}
It has to do with the condition.
in.hasNextInt()
It lets you keep looping and then after three iterations 'i' value equals to 4 and testCases[4] throws ArrayIndexOutOfBoundException.
The Solution to do this could be
for (int i = 0; i < testNum; i++) {
*//do something*
}
Update your while to read only desired numbers as below:
while(i < testNum && in.hasNextInt()) {
The additional condition && i < testNum added in while will stop reading the numbers once your have read the numbers equivalent to your array size, otherwise it will go indefininte and you will get ArrayIndexOutOfBoundException when number array testCases is full i.e. you are done reading with testNum numbers.

Find max value in java from file input

I'm new to Java and I am trying to write a program that asks the user to input the name of a txt file containing only numbers, and the program will output the sum, average, max, and min of the numbers in the file. I have written most of the program, however I am stuck trying to find the max and min of the values. Any information you can give would be helpful, and if I was not clear enough I can try to elaborate. My code so far is:
public class NumberFile{
public static void main(String[] args){
boolean goodName = false;
int currentNumber, sum = 0, numberCount=0;
Scanner numberFile = null;
FileReader infile;
Scanner input = new Scanner(System.in);
System.out.println("Please enter the name of the file you wish to import: ");
String fileName = input.nextLine();
while (!goodName){
try{
infile = new FileReader(fileName);
numberFile = new Scanner(infile);
goodName = true;
}
catch (IOException e){
System.out.println("invalid file name, please enter another name");
fileName = input.nextLine();
}
}
while (numberFile.hasNextInt()){
currentNumber = numberFile.nextInt();
sum+=currentNumber;
numberCount++;
}
System.out.println("The sum of the numbers is " +sum);
System.out.println("The average of the numbers is " + ((double) sum)/numberCount);
} // end main
} // end class
Have two variables min and max (of course min and max should initially be int.max)
Hint:
if(currentNumber < min)
{
min= currentNumber;
}
if(currentNumber > max)
{
max = currentNumber
}
The above would be in your file read loop.
Declare two int variables - one "min" and one "max".
Initialize min with Integer.MAX_VALUE and max with Integer.MIN_VALUE.
Then within your while loop check every number against those variables - ie. if number is smaller than "min" then assign it as a new "min" value.
If its larger than "max" then assign it as new "max" value.
Hope this clarifies, its very simple so I didnt put any code so you can implement it yourself.
int min=Integer.MAX_VALUE;
int max=Integer.MIN_VALUE;
while (numberFile.hasNextInt()){
currentNumber = numberFile.nextInt();
sum+=currentNumber;
numberCount++;
if(min>currentNumber){
min=currentNumber;
}
if(max<currentNumber){
max=currentNumber;
}
}
Declare the minimum value to the maximum int value and reassign the minimum value every time you read new value that is smaller than current minimum value.
Same thing goes for maximum value.
I had an instance where I needed to find the largest Id from an .sql file containing large set of insert statements. These statements also inserted the Id along with all other fields. I thought this will make a good example as the file not only has integers but large chunk of mixed data types. Below is my program,
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Scanner;
/**
* #author Hamzeen. H.
* #date 15/10/2015
*/
public class Driver {
public Driver() {
}
private void readData() {
try {
Scanner inputFile = new Scanner(new DataInputStream(
new FileInputStream("all_inserts.sql")));
long highest = 0L;
while (inputFile.hasNext()) {
String strNum = buildNumber(inputFile.next());
if (!strNum.equals("")) {
Long temp = Long.parseLong(strNum);
if (temp > highest) {
highest = temp;
}
}
}
System.out.println("Highest:: " + highest);
inputFile.close();
} catch (IOException e) {
System.out.println("Problem finding file");
}
}
private String buildNumber(String str) {
StringBuilder strBuilder = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (Character.isDigit(ch)) {
strBuilder.append(ch);
} else if ('.' == ch || !Character.isDigit(ch) || ',' == ch) {
return strBuilder.toString().trim();
}
}
return strBuilder.toString().trim();
}
public static void main(String args[]) {
new Driver().readData();
}
}

Categories