How do I stop NumberFormatException? [closed] - java

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I'll keep this short. I don't know why I'm getting NumberFormatException in my code. Any help would be much appreciated.
import java.io.IOException;
import java.util.Arrays;
public class Main {
public static void loadFiles() throws IOException {
Info i = new Info();
Song s = new Song();
int a = 1, b = 2, c = 3, d = 4, e = 5, f = 6, g = 7;
s.id = i.getSongTxt(a);
s.titulo = i.getSongTxt(b);
String ano = i.getSongTxt(c);
s.id1 = i.getSongArtistsTxt(a);
s.artista = i.getSongArtistsTxt(b);
s.id2 = i.getSongDetailsTxt(a);
String tempo = i.getSongDetailsTxt(b);
String explicita = i.getSongDetailsTxt(c);
String popularidade = i.getSongDetailsTxt(d);
String dancabilidade = i.getSongDetailsTxt(e);
String vivacidade = i.getSongDetailsTxt(f);
String volume = i.getSongDetailsTxt(g);
String[] ano1 = new String[ano.length()];
String[] tempo1 = new String[tempo.length()];
String[] explicita1 = new String[explicita.length()];
String[] popularidade1 = new String[popularidade.length()];
String[] dancabilidade1 = new String[dancabilidade.length()];
String[] vivacidade1 = new String[vivacidade.length()];
String[] volume1 = new String[volume.length()];
ano = ano.replaceAll("\\s+", "");
ano1 = ano.split(" ");
tempo1 = tempo.split("");
for(int n = 0; n < 7; n++){
s.ano[n] = Integer.parseInt(ano1[n]);
}
System.out.println(Arrays.toString(ano1));
}
public static void main(String[] args) throws IOException {
Info i = new Info();
loadFiles();
}
}
and this is what the error looks like.
Exception in thread "main" java.lang.NumberFormatException: For input string: "[2012,2013,2012,2013,2012,2013,2012]"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
at java.base/java.lang.Integer.parseInt(Integer.java:660)
at java.base/java.lang.Integer.parseInt(Integer.java:778)
at pt.ulusofona.aed.deisiRockstar2021.Main.loadFiles(Main.java:44)
at pt.ulusofona.aed.deisiRockstar2021.Main.main(Main.java:55)
Process finished with exit code 1
Any ideas as to why it's giving me this error?

Read the Javadoc.
Thrown to indicate that the application has attempted to convert a string to one of the numeric types, but that the string does not have the appropriate format.
Your input string "[2012,2013,2012,2013,2012,2013,2012]" is not a number. So that input cannot be processed as a number.
No more specific diagnosis can be made as you have shown too much code that does not matter, not enough code that does matter, and no example data.
I suggest reading the Help section of Stack Overflow to learn how to ask better questions. Specifically: How to create a Minimal, Reproducible Example.

"How do I stop it?"
Look at how you (supposedly) splitting the ano string.
ano = ano.replaceAll("\\s+", "");
ano1 = ano.split(" ");
That says:
Replace all whitespace with ... nothing. That is: remove all whitespace.
Split using a single space as the separator.
Which plainly doesn't make sense. You have removed the very characters that you are telling split to split on!
But that's wrong anyway, because the actual string you are attempting to process clearly also contains ',', '[' and ']' characters, and they shouldn't be part of the number strings.
So what you need to do is redesign the way you are splitting the ano string into a sequence of number strings ... so that it will work with your input.
Hint: find and read the javadocs for String.split(...) and Pattern.

Related

trying to print out the array in java [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
System.out.println("Please input the elements and seperate each by a comma.");
e = dk.nextLine();
String[] elems = new String[e.length()];
st = new StringTokenizer(e,",");
for (int i = 0; i<e.length(); i++) {
elems[i] = st.nextToken().toString();
}
for (int i=0; i<e.length(); i++){
System.out.println(elems[i]);
}
I am trying to print out the array elems[] but it wont work the error java.util.NoSuchElementException at java.util.StringTokenizer.nextToken(StringTokenizer.java:349 seems to be at line:
elems[i] = st.nextToken().toString();
can you help me identify and understand the problem?
A correct version:
String[] elems = e.split(",");
for(String elem : elems) {
System.out.println(elem);
}
The mistake you made is that e.length() returns the size of the string (its number of characters) so you ended up calling st.nextToken() more times than there are actual tokens separated by ",". Hence the exception.
#Jean posted a slim version of what you are trying, but ultimately to help to understand the error
e = dk.nextLine(); // input: Alfredo,Bauer,Cisco
String[] elems = new String[e.length()]; // length is 20
st = new StringTokenizer(e,","); // st has a length of 3
Now if you call it like this
for(int i = 0;i<e.length();i++){
elems[i] = st.nextToken().toString(); // NoSuchElementException
}
Because you try to call the nextToken() which does not exist.
The docs:
Returns the next token from this string tokenizer.
Throws:
NoSuchElementException - if there are no more tokens in this
tokenizer's string.
To fix your problem use the length of countTokens()
OR
while(st.hasMoreElements()){
elems[i] = st.nextToken().toString();
}
Another alternative.
String[] elems = e.split(",");
System.out.print(Arrays.toString(elems ));

Java - Convert an input string to Uppercase first letter and Lowercase other letters [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I know there has been a similar question before but it doesn't actually solve my problem. I only want to get my string input which represents an employee name and make sure the input is this form "Name". Not "name", not "Name". So i tried to do it but the output doesn't work. So here is the code :
Scanner scanner = new Scanner(System.in);
String ename; // input string
System.out.println("Enter Employee Name : (Type -Name-, not -name-, not -NAME-!!!");
ename = scanner.nextLine(); // read the string input
char[] Transform = new char[ename.length()]; // this array will contain the string split in characters
for (int i = 0;i < ename.length(); i++)
{
Transform[i] = ename.charAt(i); // Split the input to a char array
}
Transform[0] = Character.toUpperCase(Transform[0]); // First Letter Always Capital
for (int i = 1;i < ename.length(); i++)
{
Transform[i] = Character.toLowerCase(Transform[0]); // Other letters small
}
String name = new String(Transform); // convert the array to a new String variable
System.out.println("NEW STRING : " + name );
Output :
You need to change the Statement in the i loop to
Transform[i] = Character.toLowerCase(Transform[i]);
adding Transform[i] and not Transform[0] because you are inserting same first character again and again to the array
Demo
I don't know why you need all this code.
For example:
char[] transform = new char[ename.length()];
for (int i = 0; i < ename.length(); i++) {
transform[i] = ename.charAt(i);
}
is identical to
char[] transform = ename.toCharArray();
And your entire code can be rewritten as:
public static String capitalise(final String name) {
return name.substring(0, 1).toUpperCase() + name.substring(1).toLowerCase();
}
Test cases:
public static void main(String[] args) throws Exception {
System.out.println(capitalise("Name"));
System.out.println(capitalise("name"));
System.out.println(capitalise("NamE"));
System.out.println(capitalise("NAMe"));
}
Output:
Name
Name
Name
Naae

User Input and If-then and else [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I'm trying to create a simple 20 questions game, by taking user input to take user input and I'm fairly new to programming java.
I have set up all the strings for my questions and I want to ask the user if they want to play. I was trying to set up a if-then statement with the user input, with the number 1 being Yes and number 2 being No.
How could I set this up? I tried with my if(in.nextInt() = a) statement but I know that's not right. I know I need to reference the previous user input, but how do I do that? Thanks for all your help in advance.
import java.util.*;
public class twentyq {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
int a = 1;
int b = 2;
// all the Strings needed for Questions[represented by the Q(1-20) variable] and their Answers[represented by the AQ(1-20) variable]
String Q1;
String Q2;
String Q3;
String Q4;
String Q5;
String Q6;
String Q7;
String Q8;
String Q9;
String Q10;
String Q11;
String Q12;
String Q13;
String Q14;
String Q15;
String Q16;
String Q17;
String Q18;
String Q19;
String Q20;
String AQ1;
String AQ2;
String AQ3;
String AQ4;
String AQ5;
String AQ6;
String AQ7;
String AQ8;
String AQ9;
String AQ10;
String AQ11;
String AQ12;
String AQ13;
String AQ14;
String AQ15;
String AQ16;
String AQ17;
String AQ18;
String AQ19;
String AQ20;
// The questions and their answers in numerical order question first then answer immediately following.
Q1 = "Where would you find the Sea of Tranquility?";
AQ1 = "The Moon.";
Q2 = "What is the Capital of Spain";
AQ2 = "Madrid.";
Q3 = "What is the painting, La Gioconda, more usually known as?";
AQ3 = "The Mona Lisa.";
Q4 = "Which chess piece can only move diagonally?";
AQ4 = "A Bishop.";
Q5 = "What is the oldest surviving printed book in the world?";
AQ5 = "The Diamond Sutra, dated at 868 AD.";
Q6 = "Costing around $2,600 per pound, and made only to order by Knipschildt, what is the name of this chocolate truffle?";
AQ6 = "Chocopologie";
Q7 = "Who invented TV?";
AQ7 = "George Carey, a Boston civil servant, first thought up television in 1876. John Logie Baird is often quoted as its inventor but his ideas didn't come along until the 1920's.";
Q8 = "What is allspice alternatively known as?";
AQ8 = "Pimento.";
Q9 = "In publishing, what does POD mean?";
AQ9 = "Print on demand.";
Q10 = "What is John Leach famous for making?";
AQ10 = "Pottery.";
Q11 = "When was the euro introduced as legal currency on the world market?";
AQ11 = "1st January, 1999.";
Q12 = "How many valves does a trumpet have?";
AQ12 = "3.";
Q13 = "Which kind of bulbs were once exchanged as a form of currency?";
AQ13 = "Tulips.";
Q14 = "Name the director of the Lord of the Rings trilogy.";
AQ14 = "Peter Jackson.";
Q15 = "Name the largest fresh water lake in the world?";
AQ15 = "Lake Superior.";
Q16 = "Name the seventh planet from the sun.";
AQ16 = "Uranus.";
Q17 = "Which country is Prague in?";
AQ17 = "Czech Republic.";
Q18 = "What is the oldest film ever made, and when was it made?";
AQ18 = "Roundhay Garden Scene, made in 1888.";
Q19 = "Name the three primary colors.";
AQ19 = "Red, yellow and blue.";
Q20 = "How old is the world's oldest dictionary?";
AQ20 = "Cuniform tablets with bilingual Sumerian-Akkadian word-lists have been dated to 2300 BC.";
System.out.println("Welcome To KCH39's 20 Questions!");
System.out.println("Would you like to play? If yes, press 1 and enter. If not, press 2 and enter.");
in.nextInt();
if (in.nextInt() = a){
system.out.println(Q1);
}
}
}
You are using the assignment operator instead of the equals operator:
if (in.nextInt() == a){
system.out.println(Q1);
}
In your current code, change (in.nextInt() = a) to (in.nextInt() == a)
if(in.nextInt() == a){
System.out.println(q1);
}
= is an assignment operator and == (equality operator) is used for comparsion.
Source
Use equals operator (==) rather then assignment(=)....
in.nextInt();
if (in.nextInt() == a){
system.out.println(Q1);
}
other option is to assign that value first to another int and then check
int b == in.nextInt()
if(b==a)
Your program throws following compiler error. Insteed of comparing you are trying to assign value of 'a' into in.nextInt() which is impossible.
twentyq.java:120: error: unexpected type
if (in.nextInt() = a){
^
required: variable
found: value
1 error
So it must be fixed as follows(i.e use double equals):
if (in.nextInt() == a){
System.out.println(Q1);
}

Read first 100 string array, java i/o [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I was directed from to this website from a friend. The goal is to read the first 100 strings in the txt file and count how many times those words appear and print them off.
Thank you so much in advance. I've done very well with code but this has stumped me for some reason.
import java.util.Arrays;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Program6 {
public static void main(String[] args) throws FileNotFoundException {
WordAnalysis a = new WordAnalysis();
a.ReadFile();
}}
class WordAnalysis{
String[] coun = new String[1000];
int[] ana = new int[100];
void ReadFile() throws FileNotFoundException {
Scanner read = new Scanner(new File("myths.txt"));
int[] ana = new int[100];
String coun = new String();
String word=null;
while(read.hasNext()) {
word = read.next();
String[] arrWord = word.split(" ");
}
}
}
Procedure:
1: Read lines [0,99] via nextLine() from Scanner
2: Split up line with another Scanner and use next() to get each word. Alternatively, you can use split.
3: Put each word in a HashMap(String, Integer) where String is the word, and Integer is the number of times it has appeared
4: Iterate through HashMap and prints out key, value pairs
Check this, here I've used a map to keep word count.
int count = 0;
HashMap<String, Integer> wordCntMap = new HashMap();
while (read.hasNext()) {
count++;
word = read.next();
String[] arrWord = word.split(" ");
if (count == 100) {
break;
}
for (String str : arrWord) {
Integer num = wordCntMap.get(str);
if (num == null) {
wordCntMap.put(str, new Integer(1));
} else {
wordCntMap.put(str, num + 1);
}
}
}
System.out.println("Word Count " + wordCntMap);
Welcome to Stack Overflow, where no answer is too stupid and no comment too thoughtless.
It seems fairly clear however that you haven't finished writing this code. :-)
Now that you have your words in arrWord, you need to start using some sort of structure that will allow you to keep track of each word and how many times its been seen.
There are plenty of containers that let you use a string as a key and an integer as a value. For your purposes it doesn't matter which one you use.
For each word in arrWord, see if you can find it in your structure (Dictionary, Hashmap, whatever). If you can't find 'word', insert a new entry of [word, 1]. If you can find 'word' then increment the counter that you find.
When you are done, all you need to do is print out the key-value pair for each entry in your structure.
HTH!

if i entered numbers separated with commas, how could i extract the numbers? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
for example....
26, 15, 37
how could i get the numbers from a Scanner , ( lets say for instance i want to add or subtract,,,?)
Take a look at String.split().
If you want to use the Scanner API:
private static final Pattern COMMA_PATTERN = Pattern.compile("\\s*,\\s*");
public List<Integer> getIntegerList() {
// Assumes scanner is positioned at first integer in list.
List<Integer> integers = new ArrayList<Integer>();
for (;;) {
integers.add(scanner.nextInt());
if (scanner.hasNext(COMMA_PATTERN)) {
// Read and discard comma token, and continue parsing list.
scanner.next();
} else {
// Number is not followed by comma, stop parsing.
break;
}
}
return integers;
}
More error handling is needed, but hopefully, this example illustrates the approach.
You can also use Scanner.useDelimiter():
private static final Pattern COMMA_PATTERN = Pattern.compile("\\s*,\\s*");
public List<Integer> getIntegerList() {
// Assumes scanner is positioned at first integer in list.
List<Integer> integers = new ArrayList<Integer>();
Pattern oldDelimiter = scanner.delimiter();
scanner.useDelimiter(COMMA_PATTERN);
while (scanner.hasNextInt()) {
integers.add(scanner.nextInt());
}
// Reset delimiter
scanner.useDelimiter(oldDelimiter);
return integers;
}
Use Scanner.useDelimiter. It actually takes regex, so you'd want to learn some basics.
String text = "1 , 2 3, 4,5";
Scanner sc = new Scanner(text).useDelimiter("\\s*,?\\s*");
while (sc.hasNextInt()) {
System.out.println(sc.nextInt());
} // prints "1", "2", "3", "4","5"
See also
http://www.regular-expressions.info/ -- the best tutorial resource
Related questions
How do I keep a scanner from throwing exceptions when the wrong type is entered? (java)
Using hasNextInt() to prevent exception is much better than Integer.parseInt and catch NumberFormatException
String.split() is OK, but StringTokenizer works everywhere and in every version of Java.
StringTokenizer st = new StringTokenizer("26, 15, 37", ", ");
int sum = 0;
while (st.hasMoreTokens()) {
sum += Integer.parseInt(st.nextToken());
}
Try to set a delimiter for your scanner object:
Scanner s = new Scanner(System.in).useDelimiter(", *");
int first = s.nextInt();
int second = s.nextInt();
...
More examples can be found in Scanner documentation.
Look at useDelimiter. You need a regex that will match either whitespace or commas.

Categories

Resources