NumberFormatException after using String.split [duplicate] - java

This question already has an answer here:
Java: UTF-8 and BOM
(1 answer)
Closed 5 years ago.
I keep on getting a NumberFormatException in my code, but I can't seem to figure out why.
import java.io.*;
import java.util.*;
public class SongCollection
{
ArrayList<Song> songs;
public SongCollection(ArrayList<Song> songs) {
this.songs = songs;
}
public void addSong(String line) {
String[] parts = line.split("\t");
int year = Integer.parseInt(parts[0]);
int rank = Integer.parseInt(parts[1]);
String artist = parts[2];
String title = parts[3];
Song addedSong = new Song(year, rank, artist, title);
songs.add(addedSong);
}
public void printSongs(PrintStream output) {
for (int i = 0; i < songs.size(); i++) {
Song song = songs.get(i);
output.println(song.toString());
}
}
}
The string I used for the addSong method was from this input file:
The error I get is "java.lang.NumberFormatException: For input string "1965" (in java.lang.NumberFormatException)"
EDIT (adding debugger window picture):
Thank you for your help!

your input "1965" doesn't contain "\t". so the value of line will be 1965,
int year = Integer.parseInt(parts[0]);
parts[0] will have 1965 value, and it will be complied successfully, but
int rank = Integer.parseInt(parts[1]);
part[1] will not have any thing so the NumberFormatException will occur, make sure your input should contain '\t' character and numbers so that the values of parts[0] and parts[1] should be numbers.

I see why I kept on getting an error. I needed to remove the BOM from the file since I was using Notepad to open it. Everything works now, thanks for all the help!

Related

How can I randomly display a single character from a given word

Here is an update as to where I am at and what I am stuck on based on what #camickr suggested. The issue that I am coming across now is that since I have to have a return statement at the end I can only return the ArrayList letters.
Also every time the hint button is pressed only one character appears in the solution location and it is [], yet no actual letters that make up the solution appear.
public String generateLetterHint(int count, String word) {
String[] answerArray = word.split("");
ArrayList<String> letters = new ArrayList<String>(Arrays.asList(answerArray));
//StringBuilder string = new StringBuilder();
Collections.shuffle(letters);
while (!letters.isEmpty()) {
String letter = letters.remove(0);
System.out.println(letter);
}
return letters.toString();
}
Any help is appreciated!
One way it to add each (unique) letter of the String to an ArrayList.
Then you can use the Collections.shuffle(...) method to randomize the letters.
Each time the "Hint" button is pressed you:
get the letter at index 0
"remove" the letter from position 0
give the hint.
Now the next time the "Hint" button is clicked there will be a different letter at index 0.
Of course each time the user guesses a correct letter you would need to "remove" that letter from the ArrayList as well.
Edit:
Simple example showing proof of concept:
import java.util.*;
public class Main
{
public static void main(String[] args) throws Exception
{
String answer = "answer";
String[] answerArray = answer.split("");
ArrayList<String> letters = new ArrayList<String>(Arrays.asList(answerArray));
Collections.shuffle( letters );
while (!letters.isEmpty())
{
String letter = letters.remove(0);
System.out.println(letter);
}
}
}
In you real code you would only create the ArrayList once and do the shuffle once when you determine what the "answer" word is.
Then every time you need a hint you can simply invoke a method that does:
public String getHint(ArrayList letters)
{
return (letters.isEmpty() ? "" : letters.remove(0);
}
This will simply return an empty string if there are no more hints. Although a better solution would be to disable the hint button once the hints are finished.
Its working for only one answer. You can modify then work with multiple answer at the same time. When you you send a string to function, it gives you a letter that is unique inside from the string.
package com.Stackoverflow;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class RandomlyString {
private static List<Character> selectableLetters; // it store randomly selectable letters
private static boolean isFirst = true;
private static char letterHint(String answer) {
Random rnd = new Random();
// when function starts in first time, split the string letter by letter
if (isFirst) {
selectableLetters = splitString(answer);
}
isFirst = false;
if(!selectableLetters.isEmpty()) {
int hintIndex = rnd.nextInt(selectableLetters.size()); // select a letter randomly
char hint = selectableLetters.get(hintIndex); // put this letter to hint
selectableLetters.remove(hintIndex); // then remove this letter from selectableLetters, this is for don't select the same letter twice
return hint;
} else {
System.out.println("There is no hint!");
return ' ';
}
}
private static List<Character> splitString(String string) {
List<Character> chars = new ArrayList<>();
// split the string to letters and add to chars
for (char c: string.toCharArray()) {
chars.add(c);
}
return chars;
}
public static void main(String[] args) {
String answer = "Monkey";
for(int i=0; i<7; i++) {
System.out.println("Hints: " + letterHint(answer)); // it writes hint to screen
System.out.println("Other letters: " + selectableLetters); // currently selectable letters for hint
}
}
}

Java, Reading two different types of variables from a file and using them as objects later

I working on a project that is based on reading a text from a file and putting it as objects in my code.
My file has the following elements:
(ignore the bullet points)
4
Christmas Party
20
Valentine
12
Easter
5
Halloween
8
The first line declares how many "parties" I have in my text file (its 4 btw)
Every party has two lines - the first line is the name and the second one is the number of places available.
So for example, Christmas Party has 20 places available
Here's my code for saving the information from the file as objects.
public class Parties
{
static Scanner input = new Scanner(System.in);
public static void main(String[] args) throws FileNotFoundException
{
Scanner inFile = new Scanner(new FileReader ("C:\\desktop\\file.txt"));
int first = inFile.nextInt();
inFile.nextLine();
for(int i=0; i < first ; i++)
{
String str = inFile.nextLine();
String[] e = str.split("\\n");
String name = e[0];
int tickets= Integer.parseInt(e[1]); //this is where it throw an error ArrayIndexOutOfBoundsException, i read about it and I still don't understand
Party newParty = new Party(name, tickets);
System.out.println(name+ " " + tickets);
}
This is my SingleParty Class:
public class SingleParty
{
private String name;
private int tickets;
public Party(String newName, int newTickets)
{
newName = name;
newTickets = tickets;
}
Can someone explain to me how could I approach this error?
Thank you
str only contains the party name and splitting it won't work, as it won't have '\n' there.
It should be like this within the loop:
String name = inFile.nextLine();
int tickets = inFile.nextInt();
Party party = new Party(name, tickets);
// Print it here.
inFile().nextLine(); // for flushing
You could create a HashMap and put all the options into that during your iteration.
HashMap<String, Integer> hmap = new HashMap<>();
while (sc.hasNext()) {
String name = sc.nextLine();
int tickets = Integer.parseInt(sc.nextLine());
hmap.put(name, tickets);
}
You can now do what you need with each entry in the HashMap.
Note: this assumes you've done something with the first line of the text file, the 4 in your example.
nextLine() returns a single string.
Consider the first iteration, for example, "Christmas Party".
If you split this string by \n all you're gonna get is "Christmas Party" in an array of length 1. Split by "blank space" and it should work.

java.util.InputMismatchException; null (in java.util.Scanner) [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 6 years ago.
I have an assignment where I have to read in a file with information about hurricanes from 1980 to 2006. I can not figure out what the error is. I have a section of code like this:
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
public class Hurricanes2
{
public static void main(String[] args)throws IOException
{
//declare and initialize variables
int arrayLength = 59;
int [] year = new int[arrayLength];
String [] month = new String[arrayLength];
File fileName = new File("hurcdata2.txt");
Scanner inFile = new Scanner(fileName);
//INPUT - read data in from the file
int index = 0;
while (inFile.hasNext()) {
year[index] = inFile.nextInt();
month[index] = inFile.next();
}
inFile.close();
That is just the first part. But in the section with the while statement, there is an error with the year[index] = inFile.nextInt(). I have no idea what the error means and I need help. Thanks in advance.
Try adding index++ as the last line of your while loop. As it is now, you never increment it, so you're only filling and replacing the first numbers in your array.
I personally wouldn't use Scanner() but instead Files.readAllLines(). It might be easier to implement if there is some sort of delimiting character to split the hurricaine data on.
For instance, let's say your text file is this:
1996, August, 1998, September, 1997, October, 2001, April...
You can do the following if these assumptions I've made hold true:
Path path = Paths.get("hurcdata2.txt");
String hurricaineData = Files.readAllLines(path);
int yearIndex = 0;
int monthIndex = 0;
// Splits the string on a delimiter defined as: zero or more whitespace,
// a literal comma, zero or more whitespace
for(String value : hurricaineData.split("\\s*,\\s*"))
{
String integerRegex = "^[1-9]\d*$";
if(value.matches(integerRegex))
{
year[yearIndex++] = value;
}
else
{
month[monthIndex++] = value;
}
}

Java Error - array required, but java.lang.String found

I've been working on this problem for a while and managed to get rid of almost all the errors on this program. Every time I compile I seem to get this error saying "array required, but java.lang.String found." I'm really confused on what this means. Can someone help me please? I've been struggling a lot.
import java.util.Scanner;
public class Period
{
private static String phrase;
private static String alphabet;
public static void main(String [] args)
{
Scanner keyboard = new Scanner(System.in);
String userInput;
int[] letter = new int [27];
int number = keyboard.nextInt();
System.out.println("Enter a sentence with a period at the end.");
userInput = keyboard.nextLine();
userInput.toLowerCase();
}
public void Sorter(String newPhrase)
{
phrase=newPhrase.substring(0,newPhrase.indexOf("."));
}
private int charToInt(char currentLetter)
{
int converted=(int)currentLetter-(int)'a';
return converted;
}
private void writeToArray()
{
char next;
for (int i=0;i<phrase.length();i++)
{
next=(char)phrase.charAt(i);
sort(next);
}
}
private String cutPhrase()
{
phrase=phrase.substring(0,phrase.indexOf("."));
return phrase;
}
private void sort(char toArray)
{
int placement=charToInt(toArray);
if (placement<0)
{
alphabet[26]=1; // This is here the error occurs.
}
else
{
alphabet[placement] = alphabet[placement] + 1; // This is where the error occurs.
}
}
public void entryPoint()
{
writeToArray();
displaySorted();
}
private void displaySorted()
{
for (int q=0; q<26;q++)
{
System.out.println("Number of " + (char)('a'+q) +"'s: "+alphabet[q]); //this is where the error occurs.
}
}
}
replace
private static String alphabet;
with
private static char[] alphabet = new char [27];//to keep it in sync with letter
it should work.
You can't use a String as an array. There are two options here to fix this:
1) Make alphabet char[] instead of String.
or
2) Don't treat alphabet like an array. Instead of trying to reference a character as if it was stored in an array, use alphabet.charAt(placement). You can't use charAt() to replace one character with another, though, so instead of:
alphabet[placement] = alphabet[placement] + 1;
use this:
alphabet = alphabet.substring(0, placement+1) + "1" + alphabet.substring(placement+1);
That's assuming you want to insert "1" after the specified character in alphabet (it isn't entirely clear to me what you're trying to achieve here). If you meant instead to have that line of code replace the character you've referred to as alphabet[placement] with the one that follows it, you would want to do this instead:
alphabet = alphabet.substring(0, placement+1) + alphabet.charAt(placement+1) + alphabet.substring(placement+1);
Alternatively, you could set alphabet to be a StringBuilder rather than a String to make it easier to modify. If alphabet is a StringBuilder, then the first alternative to the line in question (inserting "1") could be written like this:
alphabet = alphabet.insert(placement, 1);
The second alternative (changing alphabet.charAt(placement) to match the following character could be written like this:
alphabet.setCharAt(placement, alphabet.charAt(placement+1));
Well, the problem is that you cannot threat String in java like an array (e.g., alphabet[i]).
String are immutable in Java. You can't change them.
You need to create a new string with the character replaced.
String myName = "domanokz";
String newName = myName.substring(0,4)+'x'+myName.substring(5);
Or you can use a StringBuilder:
StringBuilder myName = new StringBuilder("domanokz");
myName.setCharAt(4, 'x');
System.out.println(myName);
If I were you, I would have used the second method.

Writing a file in Java

Good day!
I have a project (game) that needs to be presented tomorrow morning. But I discovered a bug when writing in the high scores. I am trying to create a text file and write the SCORE NAME in descending order using score as the basis.
FOR EXAMPLE:
SCORE NAME RANK
230 God
111 Galaxian
10 Gorilla
5 Monkey
5 Monkey
5 Monkey
NOTE THERE'S ALSO A RANK
My code is as follows:
public void addHighScore() throws IOException{
boolean inserted=false;
File fScores=new File("highscores.txt");
fScores.createNewFile();
BufferedReader brScores=new BufferedReader(new FileReader(fScores));
ArrayList vScores=new ArrayList();
String sScores=brScores.readLine();
while (sScores!=null){
if (Integer.parseInt(sScores.substring(0, 2).trim()) < score && inserted==false){
vScores.add(score+"\t"+player+"\t"+rank);
inserted=true;
}
vScores.add(sScores);
sScores=brScores.readLine();
}
if (inserted==false){
vScores.add(score+"\t"+player+"\t"+rank);
inserted=true;
}
brScores.close();
BufferedWriter bwScores=new BufferedWriter(new FileWriter(fScores));
for (int i=0; i<vScores.size(); i++){
bwScores.write((String)vScores.get(i), 0, ((String)vScores.get(i)).length());
bwScores.newLine();
}
bwScores.flush();
bwScores.close();
}
But if i input three numbers: 60 Manny, the file would be like this:
60 Manny
230 God
111 Galaxian
10 Gorilla
5 Monkey
5 Monkey
5 Monkey
The problem is it can only read 2 numbers because I use sScores.substring(0, 2).trim()).
I tried changing it to sScores.substring(0, 3).trim()). but becomes an error because it read upto the character part. Can anyone help me in revising my code so that I can read upto 4 numbers? Your help will be highly appreciated.
What you should use is:
String[] parts = sScrores.trim().split("\\s+", 2);
Then you will have an array with the number at index 0, and the name in index 1.
int theNumber = Integer.parseInt(parts[0].trim();
String theName = parts[1].trim();
You could re-write the while-loop like so:
String sScores=brScores.readLine().trim();
while (sScores!=null){
String[] parts = sScrores.trim().split(" +");
int theNumber = Integer.parseInt(parts[0].trim();
if (theNumber < score && inserted==false){
vScores.add(score+"\t"+player+"\t"+rank);
inserted=true;
}
vScores.add(sScores);
sScores=brScores.readLine();
}
Personally, I would add a new HighScore class to aid in parsing the file.
class HighScore {
public final int score;
public final String name;
private HighScore(int scoreP, int nameP) {
score = scoreP;
name = nameP;
}
public String toString() {
return score + " " + name;
}
public static HighScore fromLine(String line) {
String[] parts = line.split(" +");
return new HighScore(Integer.parseInt(parts[0].trim()), parts[1].trim());
}
}
The format of each line is always the same : an integer, followed by a tab, followed by the player name.
Just find the index of the the tab character in each line, and substring from 0 (inclusive) to this index (exclusive), before parsing the score.
The player name can be obtained by taking the substring from the tab index +1 (inclusive) up the the length of the line (exclusive).
if above mentioned table is a file.
for first two score it will be fine but for 5 it start reading character. Might be that is causing problem.

Categories