Scanner throwing java.util.NoSuchElementException when input is taken - java

This code below throws NoSuchElementException in the function aVeryBigSum.
PS: This is task from hackerrank so I can only modify the code in function: aVeryBigSum.
This function takes the following inputs: n which is the number of elements in an array to be added, and the elements of array.
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;
public class Solution {
// Complete the aVeryBigSum function below.
static long aVeryBigSum(long[] ar) {
int n, sum = 0;
Scanner read = new Scanner(System.in);
n = read.nextInt();
for(int i = 0; i < n; i++)
sum += read.nextLong();
return sum;
}
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws IOException {
BufferedWriter bufferedWriter
= new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
int arCount = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
long[] ar = new long[arCount];
String[] arItems = scanner.nextLine().split(" ");
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
for (int i = 0; i < arCount; i++) {
long arItem = Long.parseLong(arItems[i]);
ar[i] = arItem;
}
long result = aVeryBigSum(ar);
bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();
bufferedWriter.close();
scanner.close();
}
}
Output:

Why are you reading from Scanner in your aVeryBigSum method?
Just loop through ar argument and calculate sum.
static long aVeryBigSum(long[] ar) {
long _sum = 0;
for(int i=0; i < ar.length; i++)
sum += ar[i];
return _sum;
}

static long aVeryBigSum(long[] ar) {
int n;
Long sum = 0;
Scanner read = new Scanner(System.in);
n = read.nextInt();
for(int i = 0; i < n; i++)
sum += read.nextLong();
return sum;
}
its working fine for me if you change: int n;
long sum=0; in existing code and try.
output:2
1 2
5
1000000001
1000000002
1000000003
1000000004
1000000005
5000000015

Related

Counting words using parallel Java arrays

I am trying to write code to count the frequency of each word in an array. I am wondering if I need to use two nested loops to keep track of both the array with integers and the array with the words. I have been fiddling with the code for hours and cannot make any progress. If you have any pointers, they would be much appreciated. I am given the input as first the number of elements in the array, then the words that I am supposed to count the frequency of, such as 4 dog cat dog fish.
import java.util.Scanner;
public class LabProgram {
public static int getFrequencyOfWord(String[] wordsList, int listSize, String currWord) {
int i;
int count;
int[] countArr = new int[listSize];
// need to use two arrays; one for frequency, one for words.
for (i = 0; i < countArr.length; ++i) {
if (wordsList[i].compareTo(currWord) == 0) {
countArr[i] += 1;
}
}
//check previous LAB that had same concept; then make it use a method.
return countArr[i];
}
public static void main(String[] args) {
int size;
int i;
size = scnr.nextInt();
String[] array = scnr.nextLine().split(" ");
for (i = 0; i < array.length; ++i) {
System.out.println(array[i]);
}
for (i = 0; i < array.length; ++i) {
currWord = array[i];
System.out.println(currWord + getFrequencyOfWord(array, size, currWord));
}
}
}
Can you please try below solution?:
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
try (Scanner scnr = new Scanner(System.in)) {
int size = scnr.nextInt();
Map<String, Integer> wordCounts = new HashMap<>();
for (int i = 0; i < size; i++) {
String s = scnr.next();
if (wordCounts.containsKey(s)) {
int count = wordCounts.get(s);
wordCounts.put(s, ++count);
} else {
wordCounts.put(s, 1);
}
}
wordCounts.entrySet().stream().forEach(s -> System.out.println(
s.getKey() + ": " + s.getValue()));
}
}
}
Using Java 8 Streams:
import java.util.Map;
import java.util.Scanner;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class LabProgram {
public static void main(String[] args) {
try (Scanner scnr = new Scanner(System.in)) {
int size = scnr.nextInt();
String array[] = new String[size];
for (int i = 0; i < size; i++) {
array[i] = scnr.next();
}
Map<Object, Integer> data = Stream.of(array)
.collect(Collectors.groupingBy(
s -> s, Collectors.summingInt(s -> 1)));
data.entrySet().stream().forEach(s -> System.out.println(
s.getKey() + ": " + s.getValue()));
}
}
}
If your input is:
4 dog cat dog fish
Output:
cat: 1
fish: 1
dog: 2

Is there any way to fix my main class for my adjacency list graph?

So basically I'm suppose to take the numbers from a file Ex.
And turn it into this Ex.
We're suppose to make a graph class and store a adjacency list representation of a graph. We're also suppose to do it with an array of arraylists. So I got some help making the graph class and I'm making it so that the users file is processed through the graph class but for some reason there's an error and the output isn't right. Can someone help with this?
Graph Class
import java.util.ArrayList;
public class Graph {
ArrayList<Integer> [] nodes;
int n_nodes;
public Graph(int numberNodes){
this.nodes = new ArrayList[numberNodes+1];
this.n_nodes = numberNodes;
for(int i = 0; i < n_nodes + 1; i++){
nodes[i] = new ArrayList<>();
}
}
public void addNeighbor(int node, int neighbor){
nodes[node].add(neighbor);
}
public String toString(){
StringBuilder myGraph = new StringBuilder();
for(int i = 1; i < nodes.length; i++){
myGraph.append(i);
ArrayList<Integer> neighbors = nodes[i];
int totalNeighbors = neighbors.size();
for(int j = 0; j < totalNeighbors; j++){
int myneighbor = neighbors.get(j);
myGraph.append(" -> " + myneighbor);
}
myGraph.append('\n');
}
return myGraph.toString();
}}
Main Class
import java.io.File;
import java.io.IOException;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Program1 {
public static void main(String[] args) throws IOException {
File file = null;
JFileChooser chooser = new JFileChooser();
Scanner ans = new Scanner(System.in);
int result = chooser.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
file = chooser.getSelectedFile();
} else {
JOptionPane.showMessageDialog(null, "No File Selected");
System.exit(1);
}
Scanner input = new Scanner(file);
int y = input.nextInt();
int x = 0;
Graph graph = new Graph(y);
while (input.hasNextLine()) {
for (int i = 0; i < y; i++) {
x = input.nextInt();
graph.addNeighbor(i, x);
}
System.out.println(graph.toString());
}
}}
Also I'm new to the whole stackoverflow website so sorry if my wording isn't clear or my code isn't formatted good enough.
Edit
This is the error it's showing
As 3 as read by
int y = input.nextInt();
is on a different line then you need to read the CR-LF as well.
Personally I would use the following paradigm
str = input.nextLine ()
// convert to int
while (input.hasNextLine) {
str = input.nextLine ()
arr[] = str.split (" ");
// loop through length of arr - in your code `y` is not updated
add arr[x] to graph
so basically you want something like
Scanner input = new Scanner(file);
String line = input.nextLine();
int y = 0;
if (line != null) {
y = Integer.parseInt(line.trim());
}
Graph graph = new Graph(y);
while (input.hasNextLine() && y > 0) {
if (input.hasNextLine()) {
line = input.nextLine();
}
String nums[] = line.split(" ");
for (int i = 0; i < nums.length; i++) {
int x = Integer.parseInt(nums[i]);
graph.addNeighbor(i, x);
}
System.out.println(graph.toString());
}

Java using scanner input a txt to a 2 dimensional array

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class test{
public static final int SIZE = 30;
public static final int DUE_DATE = 15;
public static final int TASK_NUMBER = 30;
public static void main(String[] args)throws FileNotFoundException{
Scanner console = new Scanner(System.in);
System.out.println("Enter input file: ");
String inputCompletionName = console.next();
boolean[][] completion = new boolean[TASK_NUMBER][SIZE];
File inputCompletion = new File(inputCompletionName);
Scanner in = new Scanner(inputCompletion);
int i = 0, j = 0;
for(j = 0; j < SIZE; j++){
for(i = 0; i < TASK_NUMBER; i++){
while(in.hasNextBoolean()){
boolean input = in.nextBoolean();
completion[i][j] = input;
}
System.out.println(completion[i][j]);
}
}
}
I tried this code. My input is some boolean value but the output only have first element. Really don't know how to fix this.
My input file is just some random boolean values like this.
true
false
true
false
true
But the output only shows the first element.
The problem is this:
while(in.hasNextBoolean()) {
boolean input = in.nextBoolean();
completion[i][j] = input;
}
And that is inside your 2 for loops, so you read your booleans into the same grid cell.
This will work:
for(j = 0; j < SIZE && in.hasNextBoolean(); j++){
for(i = 0; i < TASK_NUMBER && in.hasNextBoolean(); i++){
boolean input = in.nextBoolean();
completion[i][j] = input;
System.out.println(completion[i][j]);
}
}

Hackerrank Dynamic Array Timeout

I was working on the Data Structures track on Hackerrank, when I came across this challenge.
I think my code works, but I am getting timeout issues. That is, it seems to be taking too long to run on inputs with a lot of queries. Here is my first shot at a solution (with the timeout issues):
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);
int n = sc.nextInt();
int q = sc.nextInt();
ArrayList<Integer>[] group = (ArrayList<Integer>[])new ArrayList[n];
int lastAns = 0;
ArrayList<Integer> curr = null;
//int currVal = 0;
for(int i = 0;i < q;i++){
int query = sc.nextInt();
int x = sc.nextInt();
int y = sc.nextInt();
int thing = (x^lastAns) % n;
if(query == 1){
if(group[thing] == null){
group[thing] = new ArrayList<Integer>(n);
}
curr = group[thing];
curr.add(y);
}else if(query == 2){
curr = group[thing];
lastAns = curr.get(y % curr.size());
System.out.println(lastAns);
}
}
sc.close();
}
}
Here is code that worked with no timeout issues:
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) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int q = sc.nextInt();
int lastAns = 0;
ArrayList<ArrayList> group = new ArrayList();
ArrayList<Integer> curr = null;
//int currVal = 0;
for (int i = 0; i < n; i++){
group.add(new ArrayList<Integer>());
}
for(int i = 0;i < q;i++){
int query = sc.nextInt();
int x = sc.nextInt();
int y = sc.nextInt();
int thing = (x^lastAns) % n;
if(query == 1){
curr = group.get(thing);
curr.add(y);
}else if(query == 2){
curr = group.get(thing);
lastAns = curr.get(y % curr.size());
System.out.println(lastAns);
}
}
sc.close();
}
}
My question is: What is the difference here that resolved the timeout issues? My first guess is that arrays take longer to access/change elements than ArrayLists. Is this the case?
The key difference I see is that in the poorly-performing code, you're giving each inner ArrayList<Integer> an initial size of n, whereas in the other code you're only giving that initial size to the outer list:
group[thing] = new ArrayList<Integer>(n);
vs
group.add(new ArrayList<Integer>());
I'm guessing this was a mistake, and by forcing each of the inner lists to have size n you're making the memory space required by this algorithm O(n²).

NumberFormatException when reading from System.in

I am getting these exception while running the code
Exception in thread "main" java.lang.NumberFormatException: null
at java.lang.Integer.parseInt(Integer.java:542)
at java.lang.Integer.parseInt(Integer.java:615)
at Ideone.main(Main.java:22)
I am new at java and unable to resolve this error. Please help !
Here is my code ->
import java.util.*;
import java.lang.*;
import java.io.*;
class etest {
public static void main (String[] args) throws java.lang.Exception{
int n,k;
Scanner in = new Scanner(System.in);
n = in.nextInt();
k = in.nextInt();
BufferedReader input = new BufferedReader( new InputStreamReader(System.in));
//StringTokenizer token = new StringTokenizer(input.readLine());
int total=0;
int values[] = new int[n];
for(int i =0; i<n; i++) {
values[i] = Integer.parseInt(input.readLine());
if ((values[i]%k)==0) {
total++ ;
}
input.close();
}
System.out.println(total);
}
}
I am using the following input sample to run the program.
Thank you so much for any help!
7 3
1
51
966369
7
9
999996
11
your program has too many errors :
You can change your code as below
public static void main(String[] args) throws java.lang.Exception {
int n, k;
Scanner in = new Scanner(System.in);
n = in.nextInt();
k = in.nextInt();
int total = 0;
int values[] = new int[n];
for (int i = 0; i < n; i++) {
values[i] = in.nextInt();
if ((values[i] % k) == 0) {
total++;
}
}
System.out.println(total);
}
1) you should not close BufferedReader it will automatically close input stream also.
2) you don't need Scanner and BufferedReader at the same time. your solution can use any one of them.
3) better to use try-catch while using Integer.parseInt(String str);
if you want to go with BufferedReader then you need to change your code as
public static void main(String[] args) throws java.lang.Exception {
int n, k;
BufferedReader input = new BufferedReader( new InputStreamReader(System.in));
String str[]= input.readLine().split(" ");
n = Integer.parseInt(str[0]);
k = Integer.parseInt(str[1]);
int total = 0;
int values[] = new int[n];
for (int i = 0; i < n; i++) {
values[i]=Integer.parseInt(input.readLine());
if ((values[i] % k) == 0) {
total++;
}
}
System.out.println(total);
}

Categories

Resources