NumberFormatException for input String, confused as to why? - java

I made a method within a class that is supposed to parse a file with the format: name, xxx-xxx-xxxx
for every line. I'm trying to grab the phone number and put every digit into an array of ints and return that array. Here is my code.
This is the line that causes the error---
theIntNumber=Integer.parseInt(justAnotherString);
If I had: Nicholas James, 912-345-6789
then....
justAnotherString = "9123456789" and it throws an error when trying to parse that string for an int. I'm confused as to why this is happening, shouldn't it parse the int from this string?
Thank you for any answers.
public int[] getPhoneNumberArray() throws FileNotFoundException
{
Scanner scan = new Scanner(file);
while(scan.hasNextLine())
{
String thePhoneNumber = "";
String justAnotherString = "";
int theIntNumber=0;
String line = scan.nextLine();
Scanner parser = new Scanner(line);
parser.useDelimiter(",");
parser.next();
parser.useDelimiter(" ");
parser.next();
thePhoneNumber = parser.next();
Scanner lol = new Scanner(thePhoneNumber);
lol.useDelimiter("-");
justAnotherString += lol.next();
justAnotherString += lol.next();
justAnotherString += lol.next();
theIntNumber=Integer.parseInt(justAnotherString);
for(int i=10;i>0;i--)
{
phoneNumberArray[i-1]=theIntNumber%10;
}
}
for(int a=0;a<10;a++)
{
System.out.println("Phone Number: ");
}
return phoneNumberArray;
}
EDIT: Previous number was 123-456-7890. The number I had before was larger than the 2.1 billion that java can handle. 987-654-3210 is a better example.
This is the error I'm getting.
Exception in thread "main" java.lang.NumberFormatException: For input string: "9876543210"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at exam2.Contact.getPhoneNumberArray(Contact.java:71)
at exam2.ExamTwoInput.main(ExamTwoInput.java:83)

Your code is working here, the only issue I see is that your formula for converting the digits of the int number to an array appears flawed. You don't need the int anyway, since you have it as justAnotherString. Basically, you could use Character.digit(char, int) like -
int[] phoneNumberArray = new int[justAnotherString.length()];
for (int i = 0; i < justAnotherString.length(); i++) {
phoneNumberArray[i] = Character.digit(justAnotherString.charAt(i), 10);
}
System.out.println(Arrays.toString(phoneNumberArray));
Of course, you could also parse the telephone number with something like
String line = "Nicholas James, 123-456-7890";
// get everything after the last space.
String phone = line.substring(line.lastIndexOf(' ') + 1);
phone = phone.replace("-", ""); // remove the '-' symbols
int[] phoneNumberArray = new int[phone.length()];
for (int i = 0; i < phone.length(); i++) {
phoneNumberArray[i] = Character.digit(phone.charAt(i), 10);
}
System.out.println(Arrays.toString(phoneNumberArray));
which has the advantage that it will work with (and without) dashes.

As an aside, you can't store a telephone number in an integer. It loses both leading zeroes, and the plus sign.
For instance, imagine you were given the number for the British Prime Minister, +44 20 7925 0918. The plus sign there indicates that the call is an international call. It would be replaced by 011 in the North American Numbering Plan, or by 00 in the European Telephony Numbering Space. How would you represent that telephone number as an int?

I know this question is so old, but till now not have accepted answer.
as your note:
EDIT: Previous number was 123-456-7890. The number I had before was larger than the 2.1 billion that java can handle. 987-654-3210 is a better example.
so, please use Long.valueOf(str) instead of Integer.parseInt(str) or Integer.valueOf(str)
hope this help u all :)

Related

Is there a function in Java that allows you to transform a string to an Int considering the string has chars you want to ignore?

I'm doing a project for a Uni course where I need to read an input of an int followed by a '+' in the form of (for example) "2+".
However when using nextInt() it throws an InputMismatchException
What are the workarounds for this as I only want to store the int, but the "user", inputs an int followed by the char '+'?
I've already tried a lot of stuff including parseInt and valueOf but none seemed to work.
Should I just do it manually and analyze char by char?
Thanks in advance for your help.
Edit: just to clear it up. All the user will input is and Int followed by a + after. The theme of the project is to do something in the theme of a Netflix program. This parameter will be used as the age rating for a movie. However, I don't want to store the entire string in the movie as it would make things harder to check if a user is eligible or not to watch a certain movie.
UPDATE: Managed to make the substring into parseInt to work
String x = in.nextLine();
x = x.substring(0, x.length()-1);
int i = Integer.parseInt(x);
Thanks for your help :)
Try out Scanner#useDelimiter():
try(Scanner sc=new Scanner(System.in)){
sc.useDelimiter("\\D"); /* use non-digit as separator */
while(sc.hasNextInt()){
System.out.println(sc.nextInt());
}
}
Input: 2+33-599
Output:
2
33
599
OR with your current code x = x.substring(0, x.length()-1); to make it more precise try instead: x = x.replaceAll("\\D","");
Yes you should manually do it. The methods that are there will throw a parse exception. Also do you want to remove all non digit characters or just plus signs? For example if someone inputs "2 plus 5 equals 7" do you want to get 257 or throw an error? You should define strict rules.
You can do something like: Integer.parseInt(stringValue.replaceAll("[^\d]","")); to remove all characters that are no digits.
Hard way is the only way!
from my Git repo line 290.
Also useful Javadoc RegEx
It takes in an input String and extracts all numbers from it then you tokenize the string with .replaceAll() and read the tokens.
int inputLimit = 1;
Scanner scan = new Scanner(System.in);
try{
userInput = scan.nextLine();
tokens = userInput.replaceAll("[^0-9]", "");
//get integers from String input
if(!tokens.equals("")){
for(int i = 0; i < tokens.length() && i < inputLimit; ++i){
String token = "" + tokens.charAt(i);
int index = Integer.parseInt(token);
if(0 == index){
return;
}
cardIndexes.add(index);
}
}else{
System.out.println("Please enter integers 0 to 9.");
System.out.print(">");
}
Possible solutions already have been given, Here is one more.
Scanner sc = new Scanner(System.in);
String numberWithPlusSign = sc.next();
String onlyNumber = numberWithPlusSign.substring(0, numberWithPlusSign.indexOf('+'));
int number = Integer.parseInt(onlyNumber);

Cant get my program to take more than one integer

ok so the goal of my program (very basic at this point) is to take in a string of words for example: ("i give you 34 and you give me 50") and what i want is to populate my array with every occurrence of a number in the string. all this gives me back is the last number i give the code ive checked the whole array and all i can ever get back is the last number.
public static void main(String[] args) throws IOException {
BufferedReader read= new BufferedReader(new InputStreamReader(System.in));
String phrase;
int count = 0;
int[] numbers = new int[5];
phrase = read.readLine();
for (int i = 0; i < phrase.length()-1; i++){
if (phrase.substring(i).matches("((-|\\+)?[0-9]+(\\.[0-9]+)?)+")){
numbers[count] = Integer.parseInt(phrase.substring(i));
count++;
System.out.println(numbers[0]);
}
}
}
Some things to point out.
I don't know why you are using a substring method on the input.
You only printed numbers[0]. An array isn't good anyway because you never know how many numbers the input will have.
You are using parseInt, when you group on decimal numbers.
Pattern & Matcher would be recommended over String#matches
Here is the corrected code
List<Double> numbers = new ArrayList<>();
Pattern p = Pattern.compile("([-+]?[0-9]+(?:\\.[0-9]+)?)");
String phrase = "I give you 30, you give me 50. What about 42.1211?";
Matcher m = p.matcher(phrase);
while (m.find()) {
numbers.add(Double.parseDouble(m.group()));
}
System.out.println(numbers); // [30.0, 50.0, 42.1211]

java, correct number of inputs on one line entry

Forgive me if this has already been asked, but I am trying to fill an array of user defined size, but I want to make sure any extra input is either dumped or triggers an error to reprompt for input. My assignment requires that all input for an array is done on one line, with spaces separating individual values. The program works fine, and seeing how we are still in the beginning of the class I don't think that we are expected to know how to filter the quantity of inputs on a single line, but it is something that still bugs me.
I have searched for some time now for a solution, but everything thing I find is not quite what I am looking for. I thought doing a while(scannerVariable != "\n") would work, but once I thought about it more I realized that wouldn't do anything for my problem since the new line character is only being encountered once per array regardless of the number of inputs. The snippet with the problem is below:
public static double[] getOperand(String prompt, int size)
{
System.out.print(prompt);
double array[];
array = new double[size];
for(int count = 0; count < size; count++)
{
array[count] = input.nextDouble();
}
return array;
}
All I need is some way of validating the number of inputs or dumping/ignoring extra input, so that there is no trash in the buffer to skip input that follows. The only way I can think of is counting the number of spaces and comparing that against the size of the array -1. I don't think that would be reliable though, and I'm not sure how to extract a whitespace character for the count unless I were to have all the input go into a string and parse it. I can post more code or provide more details if needed. As always, thanks for any help!
This can help you. Function that allows the entry of numbers on a line separated by spaces. Valid numbers are stored in a list of type Double.
public static void entersDouble () {
Scanner input = new Scanner(System.in);
String s;
ArrayList<Double> numbers= new ArrayList<>();
System.out.print("Please enter numbers: ");
s=input.nextLine();
String [] strnum = s.split("\\s+");
int j=0;
while(j<strnum.length){
try {
numbers.add(Double.parseDouble(strnum[j++]));
}
catch(Exception exception) {
}
}
for (Double n : numbers)
System.out.println(n);
}
It seems to me that rather than trying to work out the number of inputs up front you would be better off trying to read them one by one and then taking appropriate action if it's too long or too short.
For example
public static double[] getOperands(String prompt, int size) {
double[] operands = new operands[size];
while (true) {
System.out.println(prompt);
Scanner scanner = new Scanner(System.in);+
int operandCount = 0;
while (scanner.hasNextDouble()) {
double val = scanner.nextDouble();
if (operandCount < size)
operands[operandCount++] = val;
}
if (operandCount == size)
return operands;
else
System.out.println("Enter " + size + " decimals separated by spaces.");
}
}

Trying to create an Acronym out of user input

Hello I am working on an assignment and I'm running into issues I was hoping for a little direction...
The purpose is to have user input a phrase and create an acronym out of that phrase. Anything over three words will be ignored.
I'm having issues with the acronym part, I am able to get the first character and figured that I would loop through the user input and grab the character after a space, but that is not working. All I am getting is the first character, which is obvious because I grab that first, but I can't figure out how to "save" the other two characters. Any help is greatly appreciated.
*********UPDATE************************
So thanks to an answer below I have made progress with using the StringBuilder. But, now if I enter "Your Three Words" the Output is: YYYYYTYYYYYWYYYY
Which is progress but I can't understand why it's repeating those first characters so many times??
I edited the code too.
*********UPDATE*****************************
public class ThreeLetterAcronym {
public static void main(String[] args) {
String threeWords;
StringBuilder acronym = new StringBuilder();
Scanner scan = new Scanner(System.in);
System.out.println("Enter your three words: ");
threeWords = scan.nextLine();
for(int count = 0; count < threeWords.length(); count++) {
acronym.append(threeWords.charAt(0));
if(threeWords.charAt(count) == ' ') {
++count;
acronym.append(threeWords.charAt(count));
}
}
System.out.println("The acronym of the three words you entered is: " + acronym);
}
}
You can't save the other characters because char is supposed to store only one character.
You can use a StringBuilder in this case
StringBuilder acronym = new StringBuilder();
Then in your loop simply replace it with
String[] threeWordsArray = threeWords.split(" ");
for(String word : threeWordsArray) {
acronym.append( word.substring(0, 1) );
}
**updated
You store the character at the current index in space:
char space = threeWords.charAt(count);
Then you compare the value of space with the integer value 3:
if(space < 3)
This will almost certainly never be true. You are asking for the numeric value of a character. Assuming it is a letter it will be at least 65. I suspect that your intention is to store something different in the variable space.

Error in Java while trying to read input

This program should count amount of digits in a number.
Here is my code:
import java.util.Scanner;
public class Converter {
public static void main(String[] args) {
Scanner marty = new Scanner(System.in);
float sk;
System.out.println("Enter start number: ");
sk = marty.nextFloat();
int numb = (int)Math.log10(sk)+1;
System.out.println(numb);
marty.close();
}
}
I am getting this kind of error, while tryin to input number with 4 or more digits before comma, like 11111,456:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextFloat(Unknown Source)
at Converter.main(Converter.java:11)
Any ideas about what the problem may be?
Taking the log (base10) of a number and adding 1 is not going to give you the correct answer for the number of digits of the input number anyway.
Your given example of 11111.465 has 8 digits. The log10 of this number is 4.045... adding 1 gives you the answer of 5.
Another example: 99, Log10(99) = 1.99, cast as int = 2, add 1 = 3... clearly is only 2 digits.
You could just read the input as a String then do something like the following instead
int count = 0;
String s = /* (Input Number) */
for(char c : s.toCharArray())
{
if(Character.isDigit(c))
count++;
}
You would have to also have to check it is actually a number though by checking its pattern...
When inputting a number, you aren't supposed to include commas unless you expect to split it. If you want a decimal, use a "." instead. If you want a number greater than 999, don't include a comma
Like many people have said, the comma is messing you up.
One option you may consider if your input needs comma is replacing the commas from the input string before try to count the number of digits.
System.out.println("Enter start number: ");
String input = marty.nextLine();
float sk = Float.parseFloat(input.replace(",", ".")); // use input.replace(",", "") if you want to remove commas
int numb = (int)Math.log10(sk)+1;
System.out.println(numb);

Categories