Number format exception for large inputs - java

This code works fine for some inputs.
but I get a NumberFormatError for higher values of inputs such as 1000000.
The input (taken for s[]) ranges from values 1-2000000
What could be the reason?
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. */
try
{
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
int no=Integer.parseInt(read.readLine());
String s[]=read.readLine().split(" ");
int result=0;
for(int i=0; i<no; i++)
{
result+= Integer.parseInt(s[i]);
if(result<0)
result=0;
}
System.out.println(result);
}
catch(IOException e)
{
System.out.println(e.getMessage());
}
}
}

Inside your for-loop, your first entered digit is the size of the array. That's how your logic is so far. Unless you're actually loading in 2,000,000 numbers manually (or copy/pasting), this would throw an ArrayIndexOutOfBoundsException.
You would get a NumberFormatException if you were to type in non-digits as the second input, or a number larger than Integer.MAX_VALUE (2147483647) or less than Integer.MIN_VALUE (-2147483648).
Entering something like:
1000000
2 1 2 1 2 1 /*... 999990 digits later ...*/ 2 1 2 1
makes the program terminate correctly. Here's the input file I used, if anyone wants it: http://ge.tt/95Lr2Kw/v/0
The program was compiles and run manually from a command promt like so: java Solution < in.txt.
Edit: I just remembered that the input values in the array could be as large as 2000000. You would have to use a BigInteger to hold a result value as large as 2000000^2.

I am agree with #lzmaki.
I don't get any NumberFormatException for your value.
But, I get ArrayIndexOutofBoundException which actually caused from StackOverFlow when I tried like this:
1000000
1 2 3
then enter
as in that time, the system recognize that it have not enough memory in its stack for hold such huge number of data.
I got NumberFormatException for the following case:
1000000
enter twice
becuase not system get a non-number format to convert integer format which is "".
I hope my analysis help you to find your bug :)

Assuming it's not a buffer overflow, any non-numeric character passed to Integer.parseInt will throw a NumberFormatException. This includes whitespace and non-printable characters like newlines as well as decimal points (Since floating point numbers are not integers).
You can try validating your inputs by using .trim() when you call read.readLine(), as well as checking for null or empty string before passing to Integer.parseInt(). Something like:
String input = read.readLine();
if ( input != null )
input = input.trim();
if ( input.equals("") )
throw new IllegalArgumentException("Input must be a number");
int no=Integer.parseInt( input );
However you decide to validate input for the first line, also do for the second readLine() call. Hopefully you can narrow down exactly what's causing the problem.

Related

java: Scanner asks for an extra value when using useDelimiter

So I wanna create this program that stores 4 values. the first one being string and the remaining 3 being integers. However, when i enter 4 values and press enter, i get an error java.util.InputMismatchException but when I enter 5 values, i get the result for my for values. for example lets say i input the following values:
Japan,1,2,3
I will get the java.util.InputMismatchException error. And if I enter the following values:-
Japan,1,2,3,4
I get the output as I want:-
Japan,1,2,3
Why is this happening? Here is my code
public class satisfaction {
public static void main(String args[])
{
Scanner src= new Scanner(System.in);
src.useDelimiter("\\,|\\n");
String name=src.next();
int a=src.nextInt();
int b=src.nextInt();
int c=src.nextInt();
System.out.println(name+","+a+","+b+","+c);
}
}
I've tested this a bit myself, and I think the \n in the pattern is not matching the line ending used by your console.
For me, I had to use \r\n instead, but you could also use System.lineSeparator() e.g. like this:
src.useDelimiter(",|" + System.lineSeparator());
The way it's written, it needs another comma at the end of the input. I would recommend checking the string to make sure it ends in a comma, and if not, append one.
I believe that if you enter Japan,1,2,3, it will give you the output you want.

JAVA - Program functions as input output, input output; want to make it so program functions as input input, output, output, respectively

I've just started learning Java, and I wanted to overcome a hurdle that showed up when trying to create a Java program for this 'problem'. This is the problem I had to create a program for:
Tandy loves giving out candies, but only has n candies. For the ith person she gives a candy to, she gives i candies to that person. For example, she first gives Randy 1 candy, then gives Pandy 2 candies, then Sandy 3. Given n, how many people can she give candies to?
Input Format
The first line is an integer x, denoting the number of test cases.
The next x lines will contain a single positive integer, n.
SAMPLE INPUT
2
1
5
Output Format
x lines, with each line containing a single integer denoting the number of people Tandy can give candies to.
SAMPLE OUTPUT
1
2
To solve this problem, I created a program, and it functions well, but it doesn't match what the problem is asking for.
The code:
import java.util.Scanner;
public class PRB1CandyGame {
public static void main(String[] args)
{
Scanner cases = new Scanner(System.in);
int repeats = cases.nextInt();
while (repeats > 0)
{
int x = cases.nextInt();
int i = 1;
for(i = 1; x-i>=0; i++)
{
x = x-i;
}
System.out.println(i-1);
repeats--;
}
}
}
(Sorry if the code is messy!)
My code takes in the number of 'cases' and then that's how many times I can enter in a number of candies to get the number of people it can provide. However, my program takes the number of candies and then outputs the number of people right after, while I want it to take in all the inputs (number of inputs is based on what the user enters for the number of cases), and then output all the values, rather than what I have. If you can explain to me how I can do that, it will help a lot.
Thanks!
From my understanding, you want your input to be stored some where first before you start processing answers then output all answers at once.
I Honestly think the question wants you to process each test case as input then output the result. So you're presently on the right track.
But if you want to get all inputs then process each one then output, use an array since you know the size of the test case. You will also need to create an array of same size for output then process each ith item in the input array and store each result in the same ith position in the output array.
Hope this helps

Program Output Problems (Java)

I was given an assignment to write a program which will accept any number of input data until 999 has been read. Then the program should type out total number of zero's and various other requests, but the problem is I don't know the output command to tell it to read the number of zeros. All I have so far is
import java.util.Scanner;
public class MidtermI {
public static void main(String args[]) {
Scanner console = new Scanner(System.in);
int numbers = console.nextInt();
and then from there I'm lost.
Break it down into small steps, and check that each step works before going further:
The first thing you need to sort out is to be able to read multiple inputs, by looping. Your current code only reads a single number from the Scanner.
Next, you need to check for the special value 999, and stop looping when that is received.
When you have got that working, figure out how to count the zeros - either by counting them as they arrive, or collecting all the values and counting them afterwards.
You can then print out the required results using System.out.println() - but you'll probably want to use that for testing and debugging your code as you go along, anyway.
Create ArrayList to hold the zero values the print its size.
ArrayList<Integer> zeroValues = new ArrayList<Integer>();
Then loop n time to input n numbers:
for(int i=0; i<999; i++) {
int numbers = console.nextInt();
if(number == 0) {
zeroValues.add(number);
}
}
Then you could print the total of zero's values like:
System.out.println(zeroValues.size());

Java NetBeans: Why does my string array terminate prematurely?

I found the problem. Apparently, there were random spaces in some of the names in the csv file, which was causing breaks at the 257th entry, as well as several others later on. So, I just took out the spaces and everything works fine now. Thanks to all who tried to help.
I have this code that reads from a csv file, puts the values in String array, and prints them for me to see. It runs fine until it reaches the 257th member of the array (each member has 3 values: last name, first name, and birth year). Here is a functioning version of the code:
package testing.csv.files;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
//.csv comma separated values
String fileName = "C:/Users/Owner/Desktop/Data.csv";
File file = new File(fileName); // TODO: read about File Names
try {
Scanner inputStream = new Scanner(file);
inputStream.next(); //Ignore first line of titles
while (inputStream.hasNext()){
String data = inputStream.next(); // gets a whole line
String[] values = data.split(",");
System.out.println(data);
}
inputStream.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Now, when I change the line
System.out.println(data);
To this:
System.out.println(values[2]);
What I expected to happen was for only the birth years (3rd column) to be printed for every person in the array. However, it only prints out until the 257th person's birth year (out of over 18,000), and gives me the following error message:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at testing.csv.files.Test.main(Test.java:22)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
The "java: 22" seems to be referring to the above snippet of code I posted above that I changed. I am not really sure what the problem is. If my syntax is wrong, why did it print at all? The only thing I can think of is that perhaps a string array can only handle 257 different people each with their own 3 values. If that were the case, then I would need some kind of larger version of string to hold all of my data. Has anyone encountered this problem before? Is the problem somewhere in my syntax and loop?
If there are only two things in the values array, then the highest location that you can index into is 1.
For arrays, you can only index into size - 1 spots; that is, if your array was size ten, you could index into a location 9, or more verbose: array[9].
Change your indexing statement to this:
System.out.println(values[1]);
You might want to see the 257th record in the csv file. Would the split method create three tokens for it? If it should result in less than three tokens and you try to print the third token by typing
System.out.println(values[2]);
you will get an ArrayIndexOutOfBoundsException.
Change:
String data = inputStream.next(); // next() can read the input only till the space
to:
String data = inputStream.nextLine(); // nextLine() reads input including space between the words
Also better way is to iterate the array instead acess through index may be particular line in csv not containing the third column.

Why isn't the nextInt() method working?

I've typed it exactly as shown in Introduction to Java Programming (Comprehensive, 6e). It's pertaining to reading integer input and comparing user input to the integers stored in a text file named "lottery.txt"
An external link of the image: http://imgur.com/wMK2t
Here's my code:
import java.util.Scanner;
public class LotteryNumbers {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Defines and initializes an array with 100 double elements called isCovered.
boolean[] isCovered = new boolean[99];
// Prompts user for input and marks typed numbers as covered.
int number = input.nextInt();
while (number != 0) {
isCovered[number - 1] = true;
number = input.nextInt();
}
// Checks whether all numbers are covered.
boolean allCovered = true;
for (int i = 0; i < 99; i++)
if (!isCovered[i]) {
allCovered = false;
break;
}
// Outputs result.
if(allCovered) {
System.out.println("The tickets cover all numbers."); }
else {
System.out.println("The tickets do not cover all numbers."); }
}
}
I suspect the problem lies within the declaration of the array. Since lottery.txt does not have 100 integers, the elements from index 10 to 99 in the array are left blank. Could this be the problem?
Why does the program terminate without asking for user input?
Possible Solution:
After thinking for a while, I believe I understand the problem. The program terminates because it takes the 0 at the EOF when lottery.txt is feed in. Furthermore, the program displays all numbers not to be covered because the elements from 11 to 100 are blank. Is this right?
The program is written to keep reading numbers until a zero is returned by nextInt(). But there is no zero in the input file, so the loop will just keep going to the end of the file ... and then fail when it tries to read an integer at the EOF position.
The solution is to use Scanner.hasNextInt() to test whether you should end the loop.
And, make sure that you redirect standard input from your input file; e.g.
$ java LotteryNumbers < lottery.txt
... 'cos your program expects the input to appear on the standard input stream.

Categories