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);
}
Related
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
Even though I have parsed it to an integer value I'm still getting an error. I need to get the integer value from a String input where I remove the comma and space, and store it in an array, then I convert that array to an integer array
import java.util.ArrayList;
import java.util.Scanner;
public class SeriesSolution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int count = sc.nextInt();
ArrayList<Integer> modes = new ArrayList<>();
for (int x = 0; x < count; x++) {
String lines = sc.nextLine();
String[] strs = lines.split(", ");
int[] array = new int[strs.length];
for (int i = 0; i < strs.length; i++) {
if (Integer.parseInt(strs[i]) > 0 && Integer.parseInt(strs[i]) < 100) {
array[i] = Integer.parseInt(strs[i]);
}
}
modes.add(mode(array));
}
for (int y:modes){
System.out.println(y);
}
}
private static int mode(int a[]) {
int maxValue=0, maxCount=0;
for (int anA : a) {
int count = 0;
for (int anA1 : a) {
if (anA1 == anA) ++count;
}
if (count > maxCount) {
maxCount = count;
maxValue = anA;
}
}
return maxValue;
}
}
The issue is mainly because Scanner accepts Enter keystroke as input. And because of which
String lines = sc.nextLine();
this peice of code stores an empty string into lines variable. This empty string throws NumberFormatException when passed to parseInt()
I would recommend you to use BufferedReader with InputStreamReader
BufferedReader br = new BuffereedReader(new InputStreamReader(System.in));
This is good for larger inputs and is error free. Though empty checks are must as prevention is better.
If you want to use Scanner, I would recommend you to update the code and use the below snippet of code.
String lines = "";
while (lines.equals("")) {
lines = sc.nextLine();
}
Do a check before the parseInt
if (strs[i] != null && !"".equals(strs[i]) && Integer.parseInt(strs[i]) ...
Or surround it with a try catch to catch the NumberformatException that will happen if a string is inserted instead of a number
I'm currently doing a simple university project about the arrays.
In my project I initialize and fill an array by using a method called "setArray", but when the program returns on the main method in which I try to print the array's content, it returns a NullPointerException.
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int num[] = null;
String command;
setArray(in, num);
for(int i = 0; i < num.length ; i++)
{
System.out.println(num[i]);
}
}
private static void setArray(Scanner in, int[] num)
{
System.out.println("Type the array size: ");
int dim = in.nextInt();
num = new int[dim];
System.out.println("Size: " + num.length);
System.out.println("Type the numbers' variability: ");
int var = in.nextInt();
int ran;
for(int i = 0; i < num.length ; i++)
{
ran = (int) (Math.random() * var);
num[i] = ran;
System.out.println(num[i]);
}
}
Have a look at this question about whether Java is Pass By Reference
Your code would be better off like this:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int num[] = null;
String command;
num = setArray(in);
for(int i = 0; i < num.length ; i++)
{
System.out.println(num[i]);
}
}
private static int[] setArray(Scanner in)
{
System.out.println("Type the array size: ");
int dim = in.nextInt();
int[] numToReturn = new int[dim];
System.out.println("Size: " + numToReturn.length);
System.out.println("Type the numbers' variability: ");
int var = in.nextInt();
int ran;
for(int i = 0; i < numToReturn.length ; i++)
{
ran = (int) (Math.random() * var);
numToReturn[i] = ran;
System.out.println(numToReturn[i]);
}
return numToReturn;
}
if you see your code you are declaring a local variable num in your setArray(scanner in,int[] num) method which is not visible in main function nor it is same as that you declared in main function .
The variable array num in the main function is different from that in setArray() function.
This question already has an answer here:
Closed 10 years ago.
I run through the entire code. I am able to enter a simple .txt file to search for a word. After it asks for a word, it returns
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -48
at SearchEngine.main(SearchEngine.java:150)
Line 150 is for (int j = 0; j
Any help debugging?
This is basic search engine program that should be able to search a .txt file for any word.
Assignment link: http://cis-linux1.temple.edu/~yates/cis1068/sp12/homeworks/concordance/concordance.html
import java.util.*;
import java.io.*;
public class SearchEngine {
public static int getNumberOfWords (File f) throws FileNotFoundException {
int numWords = 0;
Scanner scan = new Scanner(f);
while (scan.hasNext()) {
numWords++;
scan.next();
}
scan.close();
return numWords;
}
public static void readInWords (File input, String [] x) throws FileNotFoundException {
Scanner scan = new Scanner(input);
int i = 0;
while (scan.hasNext() && i<x.length) {
x[i] = scan.next();
i++;
}
scan.close();
}
public static int getNumOfDistinctWords (File input, String [] x) throws FileNotFoundException {
Scanner scan = new Scanner(input);
int count = 0;
int i = 1;
while (scan.hasNext() && i<x.length) {
if (!x[i].equals(x[i-1])) {
count++;
}
i++;
}
scan.close();
return count;
}
public static void readInDistinctWords (String [] x, String [] y) {
int i = 1;
int k = 0;
while (i<x.length) {
if (!x[i].equals(x[i-1])) {
y[k] = x[i];
k++;
}
i++;
}
}
public static int getNumberOfLines (File input) throws FileNotFoundException {
int numLines = 0;
Scanner scan = new Scanner(input);
while (scan.hasNextLine()) {
numLines++;
scan.nextLine();
}
scan.close();
return numLines;
}
public static void readInLines (File input, String [] x) throws FileNotFoundException {
Scanner scan = new Scanner(input);
int i = 0;
while (scan.hasNextLine() && i<x.length) {
x[i] = scan.nextLine();
i++;
}
scan.close();
}
public static void main(String [] args) {
try {
//gets file name
System.out.println("Enter the name of the text file you wish to search");
Scanner kb = new Scanner(System.in);
String fileName = kb.nextLine();
String TXT = ".txt";
if (!fileName.endsWith(TXT)) {
fileName = fileName.concat(TXT);
}
File input = new File(fileName);
//First part of creating index
System.out.println("Creating vocabArray");
int NUM_WORDS = getNumberOfWords(input);
//System.out.println(NUM_WORDS);
String [] wordArray = new String[NUM_WORDS];
readInWords(input, wordArray);
Arrays.sort(wordArray);
int NUM_DISTINCT_WORDS = getNumOfDistinctWords(input, wordArray);
String [] vocabArray = new String[NUM_DISTINCT_WORDS];
readInDistinctWords(wordArray, vocabArray);
System.out.println("Finished creating vocabArray");
System.out.println("Creating concordanceArray");
int NUM_LINES = getNumberOfLines(input);
String [] concordanceArray = new String[NUM_LINES];
readInLines(input, concordanceArray);
System.out.println("Finished creating concordanceArray");
System.out.println("Creating invertedIndex");
int [][] invertedIndex = new int[NUM_DISTINCT_WORDS][10];
int [] wordCountArray = new int[NUM_DISTINCT_WORDS];
int lineNum = 0;
while (lineNum<concordanceArray.length) {
Scanner scan = new Scanner(concordanceArray[lineNum]);
while (scan.hasNext()) {
int wordPos = Arrays.binarySearch(vocabArray, scan.next());
wordCountArray[wordPos]+=1;
for(int i = 0; i < invertedIndex.length; i++) {
for(int j = 0; j < invertedIndex[i].length; j++) {
if (invertedIndex[i][j] == 0) {
invertedIndex[i][j] = lineNum;
break;
} } }
}
lineNum++;
}
System.out.println("Finished creating invertedIndex");
}
System.out.println("Enter a word to be searched (type quit to exit program)");
Scanner keyboard = new Scanner(System.in);
String searchWord = keyboard.next();
while (!searchWord.equals("quit")) {
int counter = 0;
int wordPos = Arrays.binarySearch(allWordsArray, searchWord);
for (int j = 0; j<invertedIndex[wordPos].length; j++) {
if(invertedIndex[wordPos][j] != 0) {
int number = invertedIndex[wordPos][j];
String printOut = concordanceArray[number];
System.out.print(number);
System.out.print(" :");
System.out.println(printOut);
}
}
}
catch (FileNotFoundException exception) {
System.out.println("File Not Found");
}
} //main
} //class
From what I can see your getNumOfDistinctWords(String[] x) is wrong. This is returning a value of one less than it should be. Here is a modified version of the code:
import java.util.*;
import java.io.*;
public class SearchEngine {
//Counts the number of words in the file
public static int getNumberOfWords (File f) throws FileNotFoundException {
int numWords = 0;
Scanner scan = new Scanner(f);
while (scan.hasNext()) {
numWords++;
scan.next();
}
scan.close();
return numWords;
}
public static void readInWords (File input, String[] x) throws FileNotFoundException {
Scanner scan = new Scanner(input);
int i = 0;
while (scan.hasNext() && i < x.length) {
x[i] = scan.next();
i++;
}
scan.close();
}
public static String[] getNumOfDistinctWords (String[] x) throws FileNotFoundException {
HashSet<String> distinctWords = new HashSet<String>();
for(int i=0; i<x.length; i++){
distinctWords.add(x[i]);
}
String[] distinctWordsArray = new String[distinctWords.size()];
int i = 0;
for(String word : distinctWords){
distinctWordsArray[i] = word;
i++;
}
return distinctWordsArray;
}
public static int getNumberOfLines (File input) throws FileNotFoundException {
int numLines = 0;
Scanner scan = new Scanner(input);
while (scan.hasNextLine()) {
numLines++;
scan.nextLine();
}
scan.close();
return numLines;
}
public static void readInLines (File input, String [] x) throws FileNotFoundException {
Scanner scan = new Scanner(input);
int i = 0;
while (scan.hasNextLine() && i<x.length) {
x[i] = scan.nextLine();
i++;
}
scan.close();
}
public static void main(String [] args) {
try {
//gets file name
System.out.println("Enter the name of the text file you wish to search");
Scanner kb = new Scanner(System.in);
String fileName = kb.nextLine();
String TXT = ".txt";
if (!fileName.endsWith(TXT)) {
fileName = fileName.concat(TXT);
}
File input = new File(fileName);
//First part of creating index
System.out.println("Creating vocabArray");
int NUM_WORDS = getNumberOfWords(input);
//Output the number of words in the file
System.out.println("Number of words is: " + NUM_WORDS);
String[] allWordsArray = new String[NUM_WORDS];
readInWords(input, allWordsArray);
Arrays.sort(allWordsArray);
String[] distinctWordsArray = getNumOfDistinctWords(allWordsArray);
//Output the number of distinct words
System.out.println("Number of distinct words is: " + distinctWordsArray.length);
System.out.println("Finished creating distinctWordsArray");
System.out.println("Creating concordanceArray");
int NUM_LINES = getNumberOfLines(input);
String[] concordanceArray = new String[NUM_LINES];
readInLines(input, concordanceArray);
System.out.println("Finished creating concordanceArray");
System.out.println("Creating invertedIndex");
int [][] invertedIndex = new int[distinctWordsArray.length][10];
int [] wordCountArray = new int[distinctWordsArray.length];
int lineNum = 0;
while (lineNum < concordanceArray.length) {
Scanner scan = new Scanner(concordanceArray[lineNum]);
while (scan.hasNext()) {
//Find the position the word appears on the line, if word not found returns a number less than 0
int wordPos = Arrays.binarySearch(distinctWordsArray, scan.next());
if(wordPos > -1){
wordCountArray[wordPos] += 1;
}
for(int i = 0; i < invertedIndex.length; i++) {
for(int j = 0; j < invertedIndex[i].length; j++) {
if (invertedIndex[i][j] == 0) {
invertedIndex[i][j] = lineNum;
break;
} } }
}
lineNum++;
}
System.out.println("Finished creating invertedIndex");
}
catch (FileNotFoundException exception) {
System.out.println("File Not Found");
}
} //main
} //class
I should also point out the fact that Arrays.binarySearch(distinctWordsArray, scan.next()); will return a number less than 0 if the word is not found on that line. This is why you are getting the Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1 as wordCountArray is being referenced at index -1 which of course doesn't exist!
The code after this also looks buggy but I'll let you fix that!!
Without knowing exactly where line 126 is, finding this specific bug is just too much hassle. But I've got some advice for the rest of the code:
int NUM_DISTINCT_WORDS = getNumOfDistinctWords(input, wordArray);
Normally, variables in all-caps are constants that are assigned at compile time. It's a tradition that comes from C days, when it was wonderful to know which "variables" were actually replaced by the preprocessor. But the convention has proven to be useful in other languages, and most programmers would expect NUM_DISTINCT_WORDS to be assigned a specific value at compile time.
This code is simply unreadable:
for(int i = 0; i < invertedIndex.length; i++) {
for(int j = 0; j < invertedIndex[i].length; j++) {
if (invertedIndex[i][j] == 0) {
invertedIndex[i][j] = lineNum;
break;
} } }
A more idiomatic way to show these nested loops is:
for (int i = 0; i < invertedIndex.length; i++) {
for (int j = 0; j < invertedIndex[i].length; j++) {
if (invertedIndex[i][j] == 0) {
invertedIndex[i][j] = lineNum;
break;
}
}
}
Because I use the standard Lindent script to do re-indenting, I get tabs. You don't have to use tabs, but they are convenient to add and delete with a single keystroke, and they are deep enough to be obviously visible even with smallish type faces. You'll find your code far easier to work with if you follow the standard indenting idioms.
The following piece of code is extremely unfortunate:
catch(FileNotFoundException exception) {
System.out.println("File Not Found");
}
It would be better to catch a higher-level exception and include the exception message. You can more easily handle dozens of errors if you catch an exception higher in the hierarchy, and the error messages will be far more informative.
Your main() method performs a lot of detailed work. I think your code would be easier to test, easier to debug, and easier to read, if you break it apart into more methods. Try to get the main() to read practically like a high-level description of your code.
With the line with the bug on it now easily visible, I can spot the problem:
int wordPos = Arrays.binarySearch(vocabArray, scan.next());
wordCountArray[wordPos]+=1;
You've looked up the wordPos in the vocabArray, but modified content in the wordCountArray. Are you sure they are the same size and have the same meanings?
I am solving this question.
This is my code:
import java.io.IOException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int k = sc.nextInt();
int[] t = new int[n];
int count = 0;
for (int i = 0; i < n; i++) {
t[i] = sc.nextInt();
if (t[i] % k == 0) {
count++;
}
}
System.out.println(count);
}
}
But when I submit it, it get's timed out. Please help me optimize this to as much as is possible.
Example
Input:
7 3
1
51
966369
7
9
999996
11
Output:
4
They say :
You are expected to be able to process
at least 2.5MB of input data per
second at runtime.
Modified CODE
Thank you all...I modified my code and it worked...here it is....
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] input = br.readLine().split(" ");
int n = Integer.parseInt(input[0]);
int k = Integer.parseInt(input[1]);
int count = 0;
for (int i = 0; i < n; i++) {
if (Integer.parseInt(br.readLine()) % k == 0) {
count++;
}
}
System.out.println(count);
}
regards
shahensha
This could be slightly faster, based on limc's solution, BufferedReader should be faster still though.
import java.io.IOException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int k = sc.nextInt();
int count = 0;
while (true) {
try {
if (sc.nextInt() % k == 0) {
count++;
}
} catch (NoSuchElementException e) {
break;
}
}
System.out.println(count);
}
}
How about this?
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int k = sc.nextInt();
int count = 0;
for (int i = 0; i < n; i++) {
if (sc.nextInt() % k == 0) {
count++;
}
}
System.out.println(count);
You may consider reading big chunks of input and then get the numbers from there.
Other change is, you may use Integer.parseInt() instead of Scanner.nextInt() although I don't know the details of each one, somethings tells me Scanner version performs a bit more computation to know if the input is correct. Another alternative is to convert the number yourself ( although Integer.parseInt should be fast enough )
Create a sample input, and measure your code, change a bit here and there and see what the difference is.
Measure, measure!
BufferedReader is supposed to be faster than Scanner. You will need to parse everything yourself though and depending on your implementation it could be worse.