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;
}
}
Related
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.
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!
I'm very new to Java but this has had me stumped for the last half an hour or so. I'm reading in lines from a text file and storing them as String Arrays. From here I'm trying to use the values from within the arrays to be used to initialise another class I have. To initialise my Route class (hence using routeName) I need to take the first value from the array and pass it as a string. When I try to return s[0] for routeName, I'm given the last line of from my text file. Any ideas on how to fix this would be greatly appreciated. I'm in the process of testing still so thats why my code is barely finished.
My text file is as follows.
66
Uq Lakes, Southbank
1,2,3,4,5
2,3,4,5,6
and my code:
import java.io.*;
import java.util.*;
public class Scan {
public static void main(String args[]) throws IOException {
String routeName = "";
String stationName = " ";
Scanner timetable = new Scanner(new File("fileName.txt"));
while (timetable.hasNextLine()) {
String[] s = timetable.nextLine().split("\n");
routeName = s[0];
}
System.out.println(routeName);
}
}
The method you are calling timetable.nextLine.split("\n") will return the Array of String.
So every time when you call this method is overwrites your array with new line in file and as the last line is added finally in your array you are getting the lat line at the end.
below is the code you can use.
public static void main(String[] args) throws FileNotFoundException {
String routeName = "";
Scanner timetable;
int count = 0;
String[] s = new String[10];
timetable = new Scanner(new File("fileName.txt"));
while (timetable.hasNextLine()) {
String line = timetable.nextLine();
s[count++] = line;
}
routeName = s[0];
System.out.println(routeName);
}
Scanner.nextLine() returns a single line so splitting by '\n' will always give a single element array, e.g.:
timetable.nextLine().split("\n"); // e.g., "1,2,3,4,5" => ["1,2,3,4,5"]
Try splitting by the ',' instead, e.g.:
timetable.nextLine().split(","); // e.g., "1,2,3,4,5" => ["1", "2", "3", "4", "5"]
NOTE: If you are intending for the array to contain individual lines, then check out this SO post.
Scanner s = new Scanner(new File(filename));
List<String> lines = new ArrayList<String>(); // A List can be dynamically resized
while(s.hasNextLine()) lines.add(s.nextLine()); // Store each line in the list
String[] arr = lines.toArray(new String[0]); // If you really need an Array, use this
Your while loop itterates over all lines and sets the current line to the routeName. Thats why you habe the last line in you string. What you could do is calling a break, when you habe read the first line oft the file. Then you will have the first line.
This question already has answers here:
Scanner skipping every second line from file [duplicate]
(5 answers)
Closed 4 years ago.
I have the following code, I am suppose to give the input though system.in, however, the program skit the frist input, but it reads the secod one, it skips the 3rd input but it reads the forth one and so on. I can not figure out the problem.
here is my code:
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Scanner;
public class problem1a {
private static HashMap<String,Integer> ales;
private static int counter = 0;
private static ArrayList<String> names;
private static ArrayList<String> city;
private static ArrayList<Integer> count;
public static void main(String[] args) throws FileNotFoundException{
Scanner sc = new Scanner(System.in);
// initialize name,line variables
names = new ArrayList<String>();
ales = new HashMap<String,Integer>();
//store the names of the city and the corresponding student
while(sc.hasNextLine() ){
String s = removeNumbers(sc.nextLine());
Integer c = ales.get(s);
if(c == null){
ales.put(s, 1);
}
else{
ales.put(s, c.intValue() + 1);
}
if(sc.nextLine().equals(""))
break;
System.out.println(ales.toString());
}
}
}
so here is my input and the output:
input: 3456345 Delft Jan
input: 435243 Delft Tim
{Delft Jan=1}
input: 54322 Delft Tim
input: 3453455 Delft Tim
{Delft Tim=1, Delft Jan=1}
input: 3456345 Delft Jan
input: 3456345 Delft Jan
{Delft Tim=1, Delft Jan=2}
can some one please explain to me what is going wrong?
I fixed the problem, the issue was according to the comments that I was using sc.nextLine() twice inside the loop and thats why it would miss the 1st input and read the second one.
the new correct code is this and it works just fine, so thank you guys.
public static void main(String[] args) throws FileNotFoundException{
Scanner sc = new Scanner(System.in);
// initialize name,line variables
names = new ArrayList<String>();
ales = new HashMap<String,Integer>();
//store the names of the city and the corresponding student
while(sc.hasNextLine() ){
String s = removeNumbers(sc.nextLine());
Integer c = ales.get(s);
if(c == null){
ales.put(s, 1);
}
else{
ales.put(s, c.intValue() + 1);
}
if(s.equals(""))
break;
System.out.println(ales.toString());
}
}
That's because you call sc.nextLine() twice inside your loop.
You should call it only once per line:
String nextLine = sc.nextLine();
String s = removeNumbers(nextLine);
...
if("".equals(nextLine)) {
break;
}
while(sc.hasNextLine() ){
String s = removeNumbers(sc.nextLine());
// ...
if(sc.nextLine().equals(""))
break;
}
You're calling sc.nextLine() twice inside the while loop. Assign nextLine() to a variable once, and then replace all the calls inside the loop with the variable. Like so:
while(sc.hasNextLine() ){
String line = sc.nextLine();
String s = removeNumbers(line);
// ...
if(line.equals(""))
break;
}
It does read them. The problem is more like it reads the some inputs in the wrong places!
String s = removeNumbers(sc.nextLine()); //this line reads the 1st, 3rd, 5th... line
if(sc.nextLine().equals("")) //this line reads the 2nd, 4th, 6th... lines
You should assign the read line into a String variable instead and use it to remember which line you read last. In fact, you already do it with s. Have you tried if(s.equals(""))?
Code sc.nextLine() is executed twice in while - loop, that's the root cause for your issue. Take care of this, and make some neccessary chance and go ahead.
while(sc.hasNextLine() ){
String s = removeNumbers(sc.nextLine());
Integer c = ales.get(s);
if(c == null){
ales.put(s, 1);
}
else{
ales.put(s, c.intValue() + 1);
}
if(sc.nextLine().equals(""))
break;
System.out.println(ales.toString());
}
I'm trying to use a Delimiter to pull out the first numbers in a document with 31 rows looking something like "105878-798##176000##JDOE" and put it in an int array.
The numbers I'm interesed in are "105878798", and the number of numbers is not consistent.
I wrote this but can't figure out how to change the line when i reach the first delimiter (of the line).
import java.util.*;
import java.io.*;
public class Test {
public static void main(String[] args) throws Exception {
int n = 0;
String rad;
File fil = new File("accounts.txt");
int[] accountNr = new int[31];
Scanner sc = new Scanner(fil).useDelimiter("##");
while (sc.hasNextLine()) {
rad = sc.nextLine();
rad.replaceAll("-","");
accountNr[n] = Integer.parseInt(rad);
System.out.println(accountNr[n]);
n++;
System.out.println(rad);
}
}
}
Don't use the scanner for this, use the StringTokenizer and set the delimiter to ##, then just keep calling .nextElement() and you will get the next number no matter how long it is.
StringTokenizer st2 = new StringTokenizer(str, "##");
while (st2.hasMoreElements()) {
log.info(st2.nextElement());
}
(Of course, you can iterate in different ways..)
I would suggest for each line use line.split("[#][#]")[0] (of course haldle your exceptions).
also, rad.replaceAll(...) returns a new String, because String is an imutable object. you should execute parseInt on the returned String and not on rad.
just use the following instead of the equivalent 2 lines in your code:
String newRad = rad.replaceAll("-","");
accountNr[n] = Integer.parseInt(newRad);