Using Scanner to read from text file - java

I am writing a program that takes a year as user input and returns the super bowl winner for that year (using a text file of a list of super bowl winners). It compiles correctly but when I try to execute the program I get the error:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at Hw5pr4.main(Hw5pr4.java:17)
What am I doing wrong?
Text file:
1967 Green Bay Packers
1968 Green Bay Packers
1969 New York Jets
1970 Kansas City Chiefs
1971 Baltimore Colts
1972 Dallas Cowboys
1973 Miami Dolphins
1974 Miami Dolphins
1975 Pittsburgh Steelers
1976 Pittsburgh Steelers
1977 Oakland Raiders
1978 Dallas Cowboys
1979 Pittsburgh Steelers
1980 Pittsburgh Steelers
1981 Oakland Raiders
1982 San Francisco 49ers
1983 Washington Redskins
1984 Los Angeles Raiders
1985 San Francisco 49ers
1986 Chicago Bears
1987 New York Giants
1988 Washington Redskins
1989 San Francisco 49ers
1990 San Francisco 49ers
1991 New York Giants
1992 Washington Redskins
1993 Dallas Cowboys
1994 Dallas Cowboys
1995 San Francisco 49ers
1996 Dallas Cowboys
1997 Green Bay Packers
1998 Denver Broncos
1999 Denver Broncos
2000 St. Louis Rams
2001 Baltimore Ravens
2002 New England Patriots
2003 Tampa Bay Buccaneers
2004 New England Patriots
2005 New England Patriots
2006 Pittsburgh Steelers
2007 Indianapolis Colts
2008 New York Giants
2009 Pittsburgh Steelers
2010 New Orleans Saints
2011 Green Bay Packers
2012 New York Giants
2013 Baltimore Ravens
2014 Seattle Seahawks
2015 New England Patriots
Source code:
import java.util.*;
import java.io.*;
public class Hw5pr4
{
public static void main(String[] args) throws IOException{
File winners = new File("SuperBowlWinners.txt");
Scanner reader = new Scanner(winners);
String[][] data = new String[49][2];
int index = 0;
while(reader.hasNext()){
int yr = reader.nextInt();
String year = Integer.toString(yr);
data[index][0] = year;
reader.nextLine();
data[index][1] = reader.nextLine();
index++;
}
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a year, or to exit, enter STOP");
String input = keyboard.nextLine();
String winner = "Not found";
boolean found = false;
while(input!="STOP"){
for(int i=0; i<49; i++){
if(input.equals(data[i][0])){
winner = data[i][1];
found = true;
}
}
System.out.println("Enter a year, or to exit, enter STOP");
input = keyboard.nextLine();
}
if(found)
System.out.println(winner);
else
System.out.println("Error: the year is not in the data.");
}
}

First of all you are reading next line to many time:
while(reader.hasNext()){
int yr = reader.nextInt();
String year = Integer.toString(yr);
data[index][0] = year;
reader.nextLine();
data[index][1] = reader.nextLine();
index++;
}
Try to remove first reader.nextLine() because you read next line in data[index][1] = reader.nextLine();
You also have another bug - while(input!="STOP"). For string comparison you must use while(!input.equals("STOP").
I also noticed that you have some other mistakes in your code. For example I think you must put this piece of code
if(found)
System.out.println(winner);
else
System.out.println("Error: the year is not in the data.");
in while loop to print team for input year. You must also set found to false at the begining of every iteration of while loop. You will find other mistakes by yourself.
EDIT: here is a code sample how you should write your code in JAVA (it is not perfect but you can see what should be considered):
File winners = new File("D:\\stack.txt");
Scanner reader = new Scanner(winners);
HashMap<Integer, String> map = new HashMap<>();
while (reader.hasNext()) {
map.put(reader.nextInt(), reader.nextLine().trim());
}
Scanner keyboard = new Scanner(System.in);
String input = "";
do {
System.out.println("Enter a year, or to exit, enter STOP");
try {
input = keyboard.nextLine().toUpperCase();
if(map.containsKey(Integer.parseInt(input))){
System.out.println(map.get(Integer.parseInt(input)));
} else {
System.out.println("Error: the year is not in the data.");
}
} catch (Exception e) {
//This is just an example of handling exception, you must handle it better
//e.printStackTrace();
if(!input.equals("STOP"))
System.out.println("You must enter a valid number...");
}
} while (!input.equals("STOP"));

You fire nextLine more than once. You should store nextLine() in a variable at the start of your while() structure and use that.
If you are, by example, at line 10 you will try to read line 10 and line 11.

Related

How do I read each line?

I'm trying to add the total of each row, but I can only compute the first row total? How do I make it so that the program goes and reads each line to compute the total?
Once I do that...I want to put a if else statement in there. I want it to ask each row if there is an int that is above 30,000. For each int that is above 30,000 I want the total to add 1,000.
package finalProg;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.util.Scanner;
public class test
{
public static void main(String[] args)
{
readFromFile("sales.txt");
}
private static void readFromFile(String filename)
{
LineNumberReader lineNumberReader = null;
try
{
//Construct the LineNumberReader object
lineNumberReader = new LineNumberReader(new FileReader(filename));
//Setting initial line number
lineNumberReader.setLineNumber(0);
//Read all lines now; Every read increase the line number by 1
String line = null;
while ((line = lineNumberReader.readLine()) != null)
{
System.out.println("Store " + lineNumberReader.getLineNumber() + ": " + line);
File inputFile = new File("sales.txt");
Scanner a = new Scanner(inputFile);
int jan = a.nextInt();
int feb = a.nextInt();
int mar = a.nextInt();
int apr = a.nextInt();
int may = a.nextInt();
int jun = a.nextInt();
int jul = a.nextInt();
int aug = a.nextInt();
int sept = a.nextInt();
int oct = a.nextInt();
int nov = a.nextInt();
int dec = a.nextInt();
System.out.println(jan + feb + mar + apr + may + jun + jul + aug + sept + oct + nov + dec + "\n");
}
}
catch (Exception ex)
{
ex.printStackTrace();
} finally
{
//Close the LineNumberReader
try {
if (lineNumberReader != null){
lineNumberReader.close();
}
} catch (IOException ex){
ex.printStackTrace();
}
}
}
}
20000 35000 23000 50000 45000 24000 41000 39000 36000 42000 41000 39000
35000 42000 38000 41000 50000 51000 53000 50000 54000 55000 54000 56000
20000 10000 15000 12000 13000 14000 13000 14000 15000 19000 20000 21000
44000 45000 46000 42000 44000 48000 47000 46000 44000 43000 48000 49000
33000 34000 35000 36000 40000 41000 42000 40000 44000 42000 41000 39000
50000 53000 51000 52000 55000 56000 52000 54000 51000 56000 55000 53000
So far the output looks like this:
Store 1: 20000 35000 23000 50000 45000 24000 41000 39000 36000 42000 41000 39000
435000
Store 2: 35000 42000 38000 41000 50000 51000 53000 50000 54000 55000 54000 56000
435000
Store 3: 20000 10000 15000 12000 13000 14000 13000 14000 15000 19000 20000 210000
435000
Store 4: 44000 45000 46000 42000 44000 48000 47000 46000 44000 43000 48000 49000
435000
Store 5: 33000 34000 35000 36000 40000 41000 42000 40000 44000 42000 41000 39000
435000
Store 6: 50000 53000 51000 52000 55000 56000 52000 54000 51000 56000 55000 53000
435000
First of all, it's better to declare jan, feb etc. variables out of the method because it really looks like that values are not refreshed.
But I would recommend you something like this:
public class test(){
private int sum;
public static void main(String[] args)
{
readFromFile("sales.txt");
}
//You don't need this void to be static!
private void readFromFile(String filename){
LineNumberReader lineNumberReader = null;
try
{
//Construct the LineNumberReader object
lineNumberReader = new LineNumberReader(new FileReader(filename));
//Setting initial line number
lineNumberReader.setLineNumber(0);
//Read all lines now; Every read increase the line number by 1
String line = null;
while ((line = lineNumberReader.readLine()) != null)
{
System.out.println("Store " + lineNumberReader.getLineNumber() + ": " + line);
File inputFile = new File("sales.txt");
Scanner a = new Scanner(inputFile);
for (int i = 0; i < 12; i++){
sum =+ a.nextInt();
}
System.out.println(sum);
sum = 0;
}
}
catch (Exception ex)
{
ex.printStackTrace();
} finally
{
//Close the LineNumberReader
try {
if (lineNumberReader != null){
lineNumberReader.close();
}
} catch (IOException ex){
ex.printStackTrace();
}
}
}
}
This should be better.
There are a number of things that could be done differently here.
First off, consider dropping the idea of using two specific data file
readers. There is no point in this when only one file reader will do.
Take your pick and stick with it.
Whichever file reader you decide to use, make sure you close it when
done.
Don't open your data file with a new instance of a reader for every
iteration of a while loop. You're creating a hook onto that file
every time you do that and it will remain there until each reader
instance is closed or your application ends.
Declaring 12 specific int variables to hold monthly values can be best suited with the use of an Array. You need to also consider the fact that there could possibly (just possibly at some point) be a typo or error within the data which will not produce a valid integer value. This could throw a real wack-a-doodle into the workings of your code if not handled.
Below is some code that demonstrates one way you can accomplish the task at hand. It is well commented so you can see what is going on:
// Create a months header string for display purposes.
String header = String.format("%-8s %-8s %-8s %-8s %-8s %-8s %-8s %-8s %-8s %-8s %-8s %-8s",
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep",
"Oct", "Nov", "Dec");
// Create a header underline for display purposes.
String underline = String.join("", Collections.nCopies(header.length(), "="));
//Display a 'Start' underline for the Console display.
System.out.println(underline);
// Read the 'sales.txt' data file for monthly data of 6 stores.
// Trap the 'FileNotFoundException'.
try (Scanner reader = new Scanner(new File("sales.txt"))) {
int storeCounter = 0; // Keep track of the Store count.
long overallTotal = 0; // Maintain an Over-All total for all Stores
String line; // Used to hold current read in line data
// Iterate through the data file one line ata a time...
while (reader.hasNextLine()) {
line = reader.nextLine().trim(); // Trim leading/trailing whitespaces from read line.
if (line.equals("")) { continue; } // Skip blank lines (if any).
/* Split the line data into a String[] Array.
"\\s+" is used to split on one (or more)
whitespaces. */
String[] lineMonths = line.split("\\s+");
int yearTotal = 0; // Keep track of the line's yearly total.
storeCounter++; // Increment the Store Counter by 1.
int monthsOver30000 = 0; // Number of Months over 30000.
System.out.println("Store: " + storeCounter); // Display the Current Store Number in Console.
System.out.println(header); // Display the months header line in console.
// Display the current Store's monthly data in Console...
for (String month : lineMonths) {
// Display the current month.
System.out.printf("%-8s ", month);
// Add the current month value to the Yearly Total
// but first make sure it is in fact a valid integer
// value otherwise ignore it (don't add it to yearly).
if (month.matches("\\d+")) {
int monthValue = Integer.parseInt(month); // Convert the month value from string to integer
// Is the month value more than 30,000?
if (monthValue > 30000) {
// Yes, so add 1,000 to the Month Value
monthValue += 1000;
monthsOver30000++;
}
yearTotal += monthValue;
}
}
System.out.println(); // Add a newline to all the above printf's.
// If there were months that were over 30,000...
if (monthsOver30000 > 0) {
// Display information about it in Console.
System.out.println(); // Add a newline to separate this section.
System.out.println("There were " + monthsOver30000 + " months "
+ "for this Store where Monthly values were over 30000"
+ " therefore " + (monthsOver30000 * 1000) + " was added "
+ "to the");
System.out.println("Yearly Total.");
System.out.println(); // Add a newline to separate this section.
}
System.out.println("Yearly Total: --> " + yearTotal); // Display the yearly total in Console.
System.out.println(underline); // Display a underline so as to start a new data line.
// Add the current Year Total to the All Stores Over-All
// Total. Will be used for averaging later on.
overallTotal += yearTotal;
} // Continue iterating through data file until end of file is reached.
// Display the over-all total for all Stores Yearly totals in Console.
System.out.println("The over-all total for all " + storeCounter + " Stores: --> " + overallTotal);
// Display the yearly average for all stores contained within the data file.
System.out.println("The yearly average for all " + storeCounter + " Stores: --> " + overallTotal/storeCounter);
}
// Catch the 'FileNotFoundException' exception (if any).
catch (FileNotFoundException ex) {
// Display the Exception message if the exception was thrown.
System.err.println(ex.getMessage());
}
Based on the data you provided in your post, the outputto Console should look something like this:
===========================================================================================================
Store: 1
Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
20000 35000 23000 50000 45000 24000 41000 39000 36000 42000 41000 39000
There were 9 months for this Store where Monthly values were over 30000 therefore 9000 was added to the
Yearly Total.
Yearly Total: --> 444000
===========================================================================================================
Store: 2
Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
35000 42000 38000 41000 50000 51000 53000 50000 54000 55000 54000 56000
There were 12 months for this Store where Monthly values were over 30000 therefore 12000 was added to the
Yearly Total.
Yearly Total: --> 591000
===========================================================================================================
Store: 3
Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
20000 10000 15000 12000 13000 14000 13000 14000 15000 19000 20000 21000
Yearly Total: --> 186000
===========================================================================================================
Store: 4
Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
44000 45000 46000 42000 44000 48000 47000 46000 44000 43000 48000 49000
There were 12 months for this Store where Monthly values were over 30000 therefore 12000 was added to the
Yearly Total.
Yearly Total: --> 558000
===========================================================================================================
Store: 5
Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
33000 34000 35000 36000 40000 41000 42000 40000 44000 42000 41000 39000
There were 12 months for this Store where Monthly values were over 30000 therefore 12000 was added to the
Yearly Total.
Yearly Total: --> 479000
===========================================================================================================
Store: 6
Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
50000 53000 51000 52000 55000 56000 52000 54000 51000 56000 55000 53000
There were 12 months for this Store where Monthly values were over 30000 therefore 12000 was added to the
Yearly Total.
Yearly Total: --> 650000
===========================================================================================================
The over-all total for all 6 Stores: --> 2908000
The yearly average for all 6 Stores: --> 484666

Java encountering runtime errors while trying to read text file

I'm currently trying to write a Java assignment that is supposed to, in order;
Read each line of a prewritten text file
Turn each line into a string
Turn each part of each line into its own individual string/int/double
Assign those variables in an object (Which is part of an array of objects) of a class which I have also created as part of this assignment
Print each variable of the object using one of the class' methods
However, I am repeatedly running into a runtime problem where I am getting this error message;
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1371)
at Lab2.main(Lab2.java:27)
This leads me to believe I am probably reading the text file wrong. However, no matter what I do I can't seem to get it to read correctly. It's supposed to read a first name, a last name, three separate components of an address (which it concatenates into one string), a city, a state, a zip code (as an integer), a phone number (as a string) and a dollar amount (as a double).
I believe that the problem might arise from the city names, as some of them have a space between them. I thought I had solved this by setting the delimiter of the Scanner that reads each individual string to a tab (which is what every other element is separated by) but this has either not worked (And is thus trying to turn state names into an integer via the Integer.parseInt() static method) or is not the problem. As I said, I am out of ideas and would be greatly appreciative towards anyone who could help me out here!
I will list the code below. First here is the main file;
public class Lab2
{
public static void main(String[] args) throws IOException
{ String FirstName, LastName, Address1, Address2, Address3, AddressFull, City, State, Phone, ZipString, DonString, line = "blank";
int Zip;
double Donation;
Scanner fileScan = new Scanner(new File("Lab2.txt")), lineScan = new Scanner(line);
lineScan.useDelimiter("\t");
PersonStats[] Donators = new PersonStats[25];
for (int i = 0; i < Donators.length; i++)
{ line = fileScan.nextLine();
FirstName = lineScan.next();
LastName = lineScan.next();
Address1 = lineScan.next();
Address2 = lineScan.next();
Address3 = lineScan.next();
AddressFull = Address1 + " " + Address2 + " " + Address3;
City = lineScan.next();
State = lineScan.next();
ZipString = lineScan.next();
Zip = Integer.parseInt(ZipString);
Phone = lineScan.next();
DonString = lineScan.next();
Donation = Double.parseDouble(DonString);
Donators[i] = new PersonStats(FirstName, LastName, AddressFull, City, State, Zip, Phone, Donation);
Donators[i].PrintOut();
}
}
}
Next, the class file I've written up for the assignment;
public class PersonStats
{ private String FirstName, LastName, Address, City, State, Phone;
private int Zip;
private double Donation;
public PersonStats(String first, String last, String area, String town, String feifdom, int postcode, String telegraph, double given)
{ FirstName = first;
LastName = last;
Address = area;
City = town;
State = feifdom;
Zip = postcode;
Phone = telegraph;
Donation = given;
}
public void PrintOut()
{ System.out.println(FirstName + " " + LastName);
System.out.println(Address);
System.out.println(City + ", " + State + " " + Zip + "\n");
System.out.println(Phone + " " + Donation);
}
}
And then finally the text file the program is supposed to be reading from (Might be a little bit difficult to read, just remember each space except for the ones in city names is actually a tab);
Rick James 8276 Carlos Ave Las Vegas NV 87126 5553451567 23.95
John Gibson 9127 Oak Dr Corvallis OR 97330 5552812313 156.78
Ron Wills 1155 Ivy Pl Atlantic Ga 37339 5552123145 189.56
Rita Jones 1259 Chase Ave Las Vegas NV 87126 5554445671 2145.60
Jason Knight 7154 Pine Dr Gresjam OR 97380 5558124545 3157.44
Clara Swanson 1944 Main Pl Springfield OR 97339 5552123144 212.99
Robert Peck 1866 First Ave Las Vegas NV 87126 5553455425 250.00
Dora Garcia 2179 Fir Dr Corvallis OR 97330 5552812919 350.00
Peter Keck 1465 Circle Pl Gold Beach OR 97339 5552123256 2150.00
Stuart Smith 2387 Sweek Ave Las Vegas NV 87126 5553455489 650.99
Tyler Wild 1313 Spooky Ln Corvallis OR 97330 5552813213 587.45
Laretta Peters 2224 Chase Pl Monmouth OR 97361 5552124465 123.45
Kristi Emry 3465 Cerrito Ave Las Vegas NV 87126 5553455567 3212.65
Kelli Gard 1894 Elm Dr Corvallis OR 97330 5552816678 51.00
Jacob Andrews 8159 Rose Ct Mill City OR 97322 5552127879 64.00
Ryan Perkins 7546 Prince Ave Las Vegas NV 87126 5553451989 13.00
Joshua Gilbert 9278 Monroe Dr Corvallis OR 97330 5552832656 95.00
Miles Crain 4578 Chester Dr Corvallis OR 97331 5552345678 1544.00
Butch Cassidy 5498 Sutton Pl Gresham OR 97380 5416565797 1798.56
Perry Winkle 8185 Shaver Ave Las Vegas NV 87126 5553812346 195.66
Loni Day 4598 Holmen Dr Corvallis OR 97330 5555289741 1878.50
Nikita Benson 1787 Grant Pl Portland OR 97321 5553569898 1500.00
Rusty Krouger 8829 Simeon Ave Las Vegas NV 87126 5555677847 2100.00
Wally Wallace 2898 Wilson Blvd Jackson Center OH 23466 5552222222 2222.22
Joe Jones 1212 Water St Millersburg OR 97366 5555555555 55.55
Again, thanks in advance if there's anyone out there who can help me with this, your advice might save a life!... or at least the score of this lab :S
here is a tip: When using Scanner use the hasNextXXX method before invoking next methods to check if elements exists
https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
No Such Element Exception?
Okay, here it is
import java.io.IOException;
import java.io.*;
import java.util.Scanner;
public class Lab2
{
public static void main(String[] args) throws IOException
{ String FirstName, LastName, Address1, Address2, Address3, AddressFull, City, State, Phone, ZipString, DonString, line = "blank";
int Zip;
double Donation;
Scanner fileScan = new Scanner(new File("F:/test.txt")).useDelimiter("\n");
PersonStats[] Donators = new PersonStats[5];
String tempVal="";
int i = 0;
while(fileScan.hasNext())
{
tempVal = fileScan.next(); //Storing person records one at a time in the string line by line
String tempArr[] = tempVal.split("\t"); //Splitting each person record string by tab and storing it in a String array
FirstName = tempArr[0];
LastName = tempArr[1];
Address1 = tempArr[2];
Address2 = tempArr[3];
Address3 = tempArr[4];
AddressFull = Address1 + " " + Address2 + " " + Address3;
City = tempArr[5];
State = tempArr[6];
ZipString = tempArr[7];
Zip = Integer.parseInt(ZipString);
Phone = tempArr[8];
DonString = tempArr[9];
Donation = Double.parseDouble(DonString);
Donators[i] = new PersonStats(FirstName, LastName, AddressFull, City, State, Zip, Phone, Donation);
Donators[i].PrintOut();
i++;
}
}
}
First of all, I would like to point out that your variable names should start with lower case. I did not edit them in the code since they were used in many places. Make an habit to declare String firstName instead of String FirstName
To the code, in your code you had used a "\t" delimter which I replaced with "\n" since in the text file each line holds entire Person details. You could have used "\t" if the donation of the first person and first name of the second person were separated by the same, but they are separated by "\n"
So now Scanner fileScan will read the file line by line which I will store in String tempVal and while(fileScan.hasNext()) assures that the Scanner will keep reading only as long as there are lines to be read.
Now, every line has different information separated by "\t". So I used tempVal.split("\t") to separate them. Also, used a counter int i and removed the for loop. I guess rest of the code is pretty basic and not much different from yours.
**EDIT****
Here is the output
Rick James
8276 Carlos Ave
Las Vegas, NV 87126
5553451567 23.95
John Gibson
9127 Oak Dr
Corvallis, OR 97330
5552812313 156.78
Ron Wills
1155 Ivy Pl
Atlantic, Ga 37339
5552123145 189.56
Rita Jones
1259 Chase Ave
Las Vegas, NV 87126
5554445671 2145.6
Jason Knight
7154 Pine Dr
Gresjam, OR 97380
5558124545 3157.44
And here is the sample text.file that I used.
Rick James 8276 Carlos Ave Las Vegas NV 87126 5553451567 23.95
John Gibson 9127 Oak Dr Corvallis OR 97330 5552812313 156.78
Ron Wills 1155 Ivy Pl Atlantic Ga 37339 5552123145 189.56
Rita Jones 1259 Chase Ave Las Vegas NV 87126 5554445671 2145.60
Jason Knight 7154 Pine Dr Gresjam OR 97380 5558124545 3157.44
Scanner fileScan = new Scanner(new File("Lab2.txt"));
//PersonStats[] Donators = new PersonStats[25];
while(fileScan.hasNext()) {
line = fileScan.nextLine();
String parts[] = line.split("\t");
if(parts.length == 10) {
FirstName = parts[0];
...
}
There are some problems in addion.
First: String ist immutable. So your lineScanner will created with an empty String. If you later change this string, nothing appens for this scanner, because you create a new string with this step.
Second you have to check for an next element. (see my while loop)
To parse your data it is easyer to split the string in parts and use this to fill your Class. But if you want to use the Scanner class, you have to create on instance per line in your file.(in the while loop)

Array IndexOutOfBoundsException on Textfile Parse

I have a simple textfile:
John Jobs 225 Louis Lane Road
Amy Jones 445 Road Street
Corey Dol 556 The Road
Where I have people with First, last names, and address
I'm trying to parse them like this:
public void parseText() {
try {
File file = new File("test.txt");
String[] splitted;
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
String s = sc.nextLine();
splitted = s.split("\\s+");
System.out.println(splitted[0]);
}
sc.close();
} catch (FileNotFoundException e) {
System.out.println("Error"); }
}
splitted[0] works fine, which prints out the firstnames of the people.
splitted[1] prints out the last names, but gives me a IndexOutOfBoundsException.
spitted[2] prints out the first integer values of each address, but again gives me an exception.
So Then I tried doing this:
String[] splitted = new String[4];
and once again tried accessing any index greater than 0, but still got that problem.
What am I doing wrong?
This is your file's content :
John Jobs 225 Louis Lane Road
Amy Jones 445 Road Street
Corey Dol 556 The Road
When each line is read and split , splitted will contain 6 elements for the first run and 5 for the next runs. so if you don't use indexes carefully you'll obviously get IndexOutOfBoundsException.
Better approach would be to use a foreach loop :
while (sc.hasNextLine()) {
String s = sc.nextLine();
splitted = s.split("\\s+");
//System.out.println(Arrays.toString(splitted));
for (String string : splitted) {
System.out.print(string+" ");
}
System.out.println();
.....rest of code

Sort a some words in a string

Assuming there is a file:
Virginia Tyler Taylor Wilson
Ohio Grant Hayes Garfield Harrison_B McKinley Taft Harding
Massachusetts Kennedy Bush_GHW
New_York VanBuren Fillmore Roosevelt_T Roosevelt_F
I need to sort it in order, and below is my code:
TreeMap<String, String> map = new TreeMap<String, String>();
while (infile1.ready()){
String line = infile1.readLine();
String s = line.substring(0, line.indexOf(" "));
String p = line.substring(line.indexOf(" "));
map.put(s, p);
}
for (String p : map.keySet()){
System.out.println(p + " " + map.get(p));
}
My output is:
Massachusetts Kennedy Bush_GHW
New_York VanBuren Fillmore Roosevelt_T Roosevelt_F
Ohio Grant Hayes Garfield Harrison_B McKinley Taft Harding
Virginia Tyler Taylor Wilson
The expected output is:
Massachusetts **Bush_GHW Kennedy**
New_York **Fillmore Roosevelt_F Roosevelt_T VanBuren**
Ohio **Garfield Grant Harding Harrison_B Hayes McKinley Taft**
Virginia **Taylor Tyler Wilson**
The only difference is the order in the value, where I bold it in the expected output.
Is there a fast way to sort String p and puts it into the map?
you can write in short way
Arrays.sort(line.substring(line.indexOf(" ")).split(" "));
try this
String[] ps = line.substring(line.indexOf(" ")).split(" ");
Arrays.sort(ps);
then try combine ps to p with " ";
Massachusetts **Bush_GHW Kennedy**
New_York **Fillmore Roosevelt_F Roosevelt_T VanBuren**
Ohio **Garfield Grant Harding Harrison_B Hayes McKinley Taft**
Virginia **Taylor Tyler Wilson**
In your above expected output how Bush Comes after mass..
So please explore output correctly.

InputMismatchException Error in Java

public static void readStaffsFromFile() {
String inFileName = "startup.txt";
int numStaff, staffID;
String name, address;
Staff newStaff;
boolean fileExists;
Scanner inFile = null;
File databaseFile = new File(inFileName);
fileExists = databaseFile.exists();
if (fileExists) {
try {
inFile = new Scanner(databaseFile);
} catch (FileNotFoundException fnfe) {
JOptionPane.showMessageDialog(null, "The file startup.txt has just now been deleted.");
return; // cannot do anything more.
}
numStaff = inFile.nextInt();
inFile.nextLine();
for (int i = 0; i < numStaff; i++) {
staffID = inFile.nextInt();
name = inFile.nextLine();
address = inFile.nextLine();
// try{
newStaff = new Staff(staffID, name, address);
addStaff(newStaff);
// } catch (StaffException se)
// {
// System.out.println("Unable to add staff: " + name +
// " to the system.");
// }
}
}
JOptionPane.showMessageDialog(null, "System has been set up with default data from startup.txt.");
}
I have this method and when I try to call this method from main, it gives me this error.
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at SystemStartUp.readStaffsFromFile(SystemStartUp.java:195)
at SystemStartUp.loadFromFile(SystemStartUp.java:160)
at StartUp.main(StartUp.java:9)
The error line of error states that my error starts from the line of "staffID = inFile.nextInt();"
The input file looks like this.
13
11111111
Chris Ling
999 Dandenong Road
22222222
Des Casey
100 Silly Drive
33333333
Maria Indrawan
90 Programming Road
44444444
Campbell Wilson
2/5 Database Street
55555555
Janet Fraser
21 Web Drive
66666666
Judy Sheard
34 Hos Road
77777777
Ngoc Minh
24 Message Street
88888888
Martin Atchinson
45 Martine Street
99999999
Aleisha Matthews
1/6 Admin Road
10101010
Denyse Cove
100 Reception Street
12121212
Cornelia Liou
232 Reception Road
23232323
Trudi Robinson
111 Manager Street
34343434
Henry Linger
2/4 HDR Street
Probably the staffID doesn't always contains numbers. Please check the input file.
After staffID, you have to add inFile.nextLine(); to consume the new line character after of the line with number. Otherwise, you will get the error on the second loop.

Categories

Resources