Integer.parseint exceptions - java

The question was :
Write a program that processes an input.txt file that contains data regarding ticket type followed by mileage covered and reports how many frequent-flier miles the person earns.
1 frequent flyer mile is earned for each mile traveled in coach.
2 frequent flyer miles are earned for each mile traveled in first class.
0 frequent flyer miles are earned on a discounted flight.
For example, given the data in input.txt below, your method must return 15600 (2*5000 + 1500 + 100 + 2*2000).
Input.txt:
firstclass 5000 coach 1500 coach
100 firstclass 2000 discount 300
My code gives me a problem with the parseint method. Any help would be appreciated :)
//InInteger class
import java.lang.NumberFormatException;
public class IsInteger {
public static boolean IsaInteger (String s)throws NumberFormatException
{
try
{
Integer.parseInt(s);//converts the string into an integer
return true;
}
catch (NumberFormatException e)
{
return false;
}
}
}
//main class
import java.io.*;
import java.util.StringTokenizer;
public class LA5ex2 {
public static void main(String[] args) throws FileNotFoundException {
BufferedReader input= new BufferedReader (new InputStreamReader (new FileInputStream("C:/Users/user/workspace/LA5ex2/input.txt")));
String str;
int TotalMiles=0;
try {
int mileage,lines=0;
String check,copy=null;
String word=null;
boolean isString=false;
while ((str = input.readLine()) != null)
{
lines++;
StringTokenizer token = new StringTokenizer(str);
while (token.hasMoreTokens())
{
if ((lines>1) && (isString))
{
//do nothing
}
else
{word= token.nextToken();
copy=word;}
if (token.hasMoreTokens())
mileage= Integer.parseInt(token.nextToken());
else
{
if (!(IsInteger.IsaInteger(word)))
{
copy=word;
isString=true;
}
break;
}
if (copy.equals("firstclass"))
TotalMiles+= (2*mileage);
else if (copy.equals("coach"))
TotalMiles+= (1*mileage);
else if (copy.equals("discount"))
TotalMiles+= (0*mileage);
}
}
System.out.println("Frequent-flier miles the person earns: "+ TotalMiles);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

This is the stacktrace that I get when running your code:
Exception in thread "main" java.lang.NumberFormatException: For input string: "firstclass"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:481)
at java.lang.Integer.parseInt(Integer.java:514)
at LA5ex2.main(LA5ex2.java:30)
I assume this is the error that you mention in your comment. However, the NumberFormatException does not occur in your IsaInteger() method in the IsInteger class (where you try-catch it by returning true or false), but in the LA5ex2 class (where you also try-catch it, but if it crashes, only the stacktrace gets printed). The exception occurs when Integer.parseInt() tries to parse the string firstclass as an integer, which of course fails:
if(token.hasMoreTokens()) mileage = Integer.parseInt(token.nextToken());
I rewrote your code in LA5ex2.java with two ArrayLists (to keep track of the various flier classes and the various mileages) using your IsaInteger method:
import java.io.*;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class LA5ex2 {
public static void main(String[] args) throws FileNotFoundException {
BufferedReader input = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt")));
String str = null;
String token = null;
int totalMiles = 0;
int lines = 0;
ArrayList<String> flierClasses = new ArrayList<String>();
ArrayList<Integer> mileages = new ArrayList<Integer>();
try {
while((str = input.readLine()) != null) {
lines++; // Why are we counting the lines, anyway?
StringTokenizer tokenizer = new StringTokenizer(str);
while(tokenizer.hasMoreTokens()) {
token = tokenizer.nextToken();
if(!(IsInteger.IsaInteger(token))) {
flierClasses.add(token); // if it's not an int, we assume it's a flier class
} else {
mileages.add(Integer.parseInt(token)); // if it's an int, it's a mileage
}
}
}
} catch(NumberFormatException ex) {
// TODO Auto-generated catch block
ex.printStackTrace();
} catch(IOException ex) {
// TODO Auto-generated catch block
ex.printStackTrace();
}
// Add everything up
for(int i = 0; i < flierClasses.size(); i++) {
totalMiles += calculateFlierMiles(flierClasses.get(i), mileages.get(i));
}
System.out.println("Frequent-flier miles the person earns: " + totalMiles);
}
private static int calculateFlierMiles(final String flierClass, final int mileage) {
if(flierClass.equals("firstclass")) return(2 * mileage);
else if(flierClass.equals("coach")) return(1 * mileage);
else if(flierClass.equals("discount")) return(0 * mileage);
return 0;
}
}
This code gives me the desired output: Frequent-flier miles the person earns: 15600

I'm assuming the problem is in IsaInteger (which should be stylized as isAnInteger). In that case, add a line that prints out the value of s before the try/catch and tell me what you get.
Also, why are you using tokens when you could use a BufferedReader and its nextLine() method?

Related

Character and String input in Java

I am new to Java and wrote a program for basic I/O operations of different data types. I want the program to input 1 a abcd and output them in in three different lines respectively. But when I input 1 a the program terminates and outputs 1 , a and an empty line in three different lines. I am not able to take a character input properly, which I think is the root of the problem.
Can someone please guide me as to where I got it wrong ?
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.StringTokenizer;
public class Main {
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
char nextChar() {
char c = ' ';
try {
c = (char)br.read();
}
catch (IOException e) {
e.printStackTrace();
}
return c;
}
String nextLine() {
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
public static void main(String[] args) {
FastReader in = new FastReader();
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt();
char c = in.nextChar();
String s = in.nextLine();
out.println(n);
out.println(c);
out.println(s);
out.close();
}
}
Refactor the code like below.
char c = in.nextChar();//Keep this line as same
in.nextLine();//(only add this line after the above line)Place this line otherwise your String abcd can't insert
output:
1
a
abcd
you mean like follow:
input: 1 a abcd
out:
1
a
abcd
you reference this code:
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
String inputLine = bufferedReader.readLine();
if (inputLine!=null && inputLine.length()>0) {
String[] splitInputLine = inputLine.split("\\ ");
for (String outLine : splitInputLine) {
System.out.println(outLine);
}
}
bufferedReader.close();
}

Getting values from LinkedList according to user input

Facing some issues with my lab codes
I've done trouble shooting to find that both there's nothing wrong with my filereader/bufferedreaders, Vehicle method and LinkedList values
I'm found out that I'm having Problems getting the if statement to work
I do not know How do I compare the current linkedlist data extracted from my file.txt using tokenizer to pass into given fields with userinput using if/else ?
Main method
package test6;
// import packages
import java.util.LinkedList;
import java.io.*;
import java.util.Scanner;
import java.util.StringTokenizer;
public class Lab6 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
// Declare variables for reading file
FileReader fr = null;
BufferedReader br = null;
String inFile = "Vehicle_Records.txt";
final String INPUT_PROMPT = "\nPlease enter the search word " + "that you would like to obtain more information on:";
String line;
StringTokenizer tokenizer;
// Declare variables to contain the record fields
String group;
String brand;
String model;
double rate;
// Declare and instantiate a new LinkedList
LinkedList<Vehicle> list = new LinkedList<Vehicle>();
try {
// Instantiate FileReader & BufferedReader objects
fr = new FileReader(inFile);
br = new BufferedReader(fr);
//read a line from the file
line = br.readLine();
// While line is not null
while (line != null) {
// Tokenize the records
tokenizer = new StringTokenizer(line, ",");
group = tokenizer.nextToken();
brand = tokenizer.nextToken();
model = tokenizer.nextToken();
rate = Double.parseDouble(tokenizer.nextToken());
// Create a new Vehicle object of the record
Vehicle newVehicle = new Vehicle(group, brand, model, rate);
System.out.println(newVehicle);
// Add this item object into the LinkedList
list.add(newVehicle);
// Read another line from file
line = br.readLine();
}
// Close BufferedReader
br.close();
}
catch (FileNotFoundException e)
{
System.out.println("The file" + inFile + "was not found");
}
catch (IOException e)
{
System.out.println("Reading error!" + e);
}
finally
{
//Check if FileReader is opened
if (fr != null) {
try {
//close FileReader
fr.close();
} catch (IOException e) {
System.out.println("Error closing file!");
}
}
}
// Print out the input prompt
System.out.println(INPUT_PROMPT);
try
{
// Create readers to read from user input
//FileReader ufr = new FileReader(INPUT_PROMPT);
BufferedReader ubr = new BufferedReader(new InputStreamReader (System.in));
// Read one line from user input
String uline=ubr.readLine();
// Loop through all the records in the LinkedList
for(int i = 0; i< list.size(); i++)
{
// if the record is the same as the input from user
// (Hint: use contains() in String class to check whether
// search word is found in the records
String temp = new String(uline);
if(list.get(i)== uline.contains(temp))
{
//print out the information of the vehicle that match user input
System.out.println(list.get(i));
}
}
}
catch(IOException e)
{
System.out.println(e);
}
catch (Exception e)
{
System.out.println("Input error!" + e);
}
}
}//main
Vehical Class
package lab6;
public class Vehicle {
// Declare all the variables to contain the fields of a record
String group;
String brand;
String model;
double rate;
// Creates a constructor to store all the fields into the variables
public Vehicle(String group, String brand, String model, double rate)
{
this.group=group; this.brand=brand; this.model=model; this.rate=rate;
}
// Create a toString() method to return string in the same delimited
// format as the input record
public String toString()
{
return(group+","+brand+","+model+","+rate);
}
}
Your code is not inside a method , so you are facing a problem.
I assume since your looking through vehicle objects trying to find a match of one its four variables. Your approach is wrong since you're comparing an object with a String.
Instead you could use a Comparable interface inside the Vehicle class where you would simply compare multiple strings.
Edit:
public class Vehicle implements Comparable<String>{
/* This method returns 0 if the search matches
* Else it return a negative or a positive number*/
#Override
public int compareTo(String o) {
int cmp = this.getBrand().compareToIgnoreCase(o);
if(cmp == 0) return cmp;
cmp = this.getGroup().compareToIgnoreCase(o);
if(cmp == 0) return cmp;
cmp = this.getModel().compareToIgnoreCase(o);
if(cmp == 0) return cmp;
/* Edited this part to work with doubles */
try{
cmp = (int)(this.getRate() - Double.parseDouble(o));
}
catch(NumberFormatException e){
return cmp;
}
return cmp;
}
}
And here is how you would loop through it:
for(int i = 0; i< list.size(); i++){
if(list.get(i).compareTo(uline) == 0)
{
System.out.println(list.get(i));
}
}
Hope it help.
PS. I'm also new to this :)
AAAAAAAND I FINALLY FIGURED IT OUT TOGETHER WITH MY OTHER FRIEND
Still, I'd love to thank all of you for extending a hand to help me :')
Shall post the solution to my problem here
//-etc-
// Create readers to read from user input
//FileReader ufr = new FileReader(INPUT_PROMPT);
BufferedReader ubr = new BufferedReader(new InputStreamReader (System.in));
// Read one line from user input
String uline=ubr.readLine();
// Loop through all the records in the LinkedList
for(int i = 0; i< list.size(); i++)
{
// if the record is the same as the input from user
// (Hint: use contains() in String class to check whether
// search word is found in the records
Vehicle vehicle = list.get(i);
if(vehicle.group.contains(uline) ||
vehicle.brand.contains(uline) ||
vehicle.model.contains(uline))
{
//print out the information of the vehicle that match user input
System.out.println(list.get(i));
}

program that uses input file and creates a new one

I'm writing a code that uses an input file called InvetoryReport.txt in a program I am supposed to create that is supposed to take this file, and then multiply two pieces of data within the file and then create a new file with this data. Also at the beginning of the program it is supposed to ask you for the name of the input file. You get three chances then it is to inform you that it cannot find it and will now exit, then stop executing.
My input file is this
Bill 40.95 10
Hammer 1.99 6
Screw 2.88 2
Milk .03 988
(The program is supposed to multiply the two numbers in the column and create a new column with the sum, and then under print another line like this
" Inventory Report
Bill 40.95 10 409.5
Hammer 1.99 6 11.94
Screw 2.88 2 5.76
Milk .03 988 29.64
Total INVENTORY value $ 456.84"
and my program I have so far is this
package textfiles;
import java.util.Scanner;
import java.io.PrintWriter;
import java.io.IOException;
public class LookOut{
double total = 0.0;
String getFileName(){
System.out.printIn("Type in file name here.");
try {
int count =1;
FileReader fr = new FileReader("InventoryReport.txt");
BufferedReader br = new BufferedReader(fr);
String str;
while ((str = br.readLine()) != null) {
out.println(str + "\n");
}
br.close();
} catch (IOException e) {
if(count == 3) {
System.out.printIn("The program will now stop executing.");
System.exit(0);
count++;
}
}
return str;
}
void updateTotal(double d){
total = total + d;
}
double getLineNumber(int String_line){
String [] invRep = line.split(" ");
Double x = double.parseDouble(invRep[1]);
Double y = double.parseDouble(invRep[2]);
return x * y;
}
void printNewData(String = newData) {
PrintWriter pW = new PrintWriter ("newData");
pw.print(newData);
pw.close;
}
public static void main(String[] args){
String str = ("Get file name");
String str = NewData("InventoryReport/n");
File file = new File(str);
Scanner s = new Scanner(file);
while(s.hasNextLine()) {
String line = s.nextLine();
double data = getLineNumber(line);
update total(data);
NewData += line + " " + data + "/n";
Print NewData(NewData);
}
}
}
I'm getting multiple error codes that I just cant seem to figure out.
try {
int count =1;
FileReader fr = new FileReader("InventoryReport.txt");
BufferedReader br = new BufferedReader(fr);
String str;
while ((str = br.readLine()) != null) {
br.close();
} catch (IOException e) {
if(count == 3) {
System.out.printIn("The program will now stop executing.");
System.exit(0);
count++;
}
}
Despite your best intentions you are in fact missing a '}'. Note that you haven't escaped the Try block before the catch. I imagine this is because you confused the closing } for the while statement as the closing } for the try block. Do this instead:
try {
int count =1;
FileReader fr = new FileReader("InventoryReport.txt");
BufferedReader br = new BufferedReader(fr);
String str;
while ((str = br.readLine()) != null) {
br.close();
}
}
catch (IOException e) {
if(count == 3) {
System.out.printIn("The program will now stop executing.");
System.exit(0);
count++;
}
}
Also, your indentation is ALL OVER THE PLACE. This should be a lesson to you in why you should format your code properly! It is so easy to miss simple syntax errors like that if you're not formatting properly. It's also hard for others to read your code and figure out what's wrong with it.

How can I fix my code so it can input letters [duplicate]

This question already has answers here:
How to insist that a users input is an int?
(7 answers)
Closed 9 years ago.
So i'm just learning java and I know this issue is very stupid, this is from the book Head Frist Java. When I try to put a letter instead of a number it crashes, how do I fix that? If I want it to say "pleasse try again with a number" when letter is entered.
public class Game {
public static void main(String[] args)
{
int numOfGuesses = 0;
GameHelper helper = new GameHelper();
SimpleDotCom theDotCom = new SimpleDotCom();
int randomNum = (int) (Math.random() * 5);
int[] locations = {randomNum, randomNum+1, randomNum+2};
theDotCom.setLocationCells(locations);
boolean isAlive = true;
while (isAlive == true)
{
String guess = helper.getUserInput("enter a number");
String result = theDotCom.checkYourself(guess);
numOfGuesses++;
if (result.equals("kill")) {
isAlive = false;
System.out.println("You took " + numOfGuesses + " guesses");
}
}
}
}
public class GameHelper {
private static final String alphabet = "abcdefg";
private int gridLength = 7;
private int gridSize = 49;
private int [] grid = new int[gridSize];
private int comCount = 0;
public String getUserInput(String prompt) {
String inputLine = null;
System.out.print(prompt + " ");
try {
BufferedReader is = new BufferedReader(
new InputStreamReader(System.in));
inputLine = is.readLine();
if (inputLine.length() == 0 ) return null;
} catch (IOException e) {
System.out.println("IOException: " + e);
}
return inputLine.toLowerCase();
}
public class SimpleDotCom {
int[] locationCells;
int numOfHits = 0;
public void setLocationCells(int[] locs)
{
locationCells = locs;
}
public String checkYourself(String stringGuess) {
int guess = Integer.parseInt(stringGuess);
String result = "miss";
for (int cell: locationCells)
{
if (guess == cell) {
result = "hit";
numOfHits++;
break;
}
}
if (numOfHits == locationCells.length)
{
result = "kill";
}
System.out.println(result);
return result;
}
In the following -
int guess = Integer.parseInt(stringGuess);
the parsing succeeds only if stringGuess contains some integer (within the range of [-2147483648 - 2147483647]. Otherwise, it fails with an exception.
To avoid that you have to make sure that stringGuess contains the right value.
Following is where the value comes from -
String guess = helper.getUserInput("enter a number");
String result = theDotCom.checkYourself(guess);
It's the getUserInput() method -
public String getUserInput(String prompt) {
String inputLine = null;
System.out.print(prompt + " ");
try {
BufferedReader is = new BufferedReader(new InputStreamReader(System.in));
inputLine = is.readLine();
if (inputLine.length() == 0)
return null; // this cannot be parsed
} catch (IOException e) {
System.out.println("IOException: " + e);
}
return inputLine.toLowerCase(); //this might not be an integer
}
And that's the part that you need to fix.
Following should do the job -
//...
BufferedReader is = new BufferedReader(new InputStreamReader(System.in));
while (true) { //keep reading
try {
inputLine = is.readLine();
int num = Integer.parseInt(inputLine); //make sure it's an integer
if(num > -1 && num < 10) { // if it is, and within [0-9]
break; // stop reading
}
} catch (Exception e) { // if not prompt again
System.out.println("pleasse try again with a number within [0-9]");
}
}
return inputLine; // no to lower case, it's a number
You can still better it up, by say just returning an int form this method, instead of String.
If you don't know if stringGuess is an integer or not, you can put Integer.parseInt(stringGuess) in a try { } catch construct. parseInt throws an exception if its input cannot be turned into an integer, so catch it. In the catch block, we know that it was not an integer. Otherwise it was an integer. Now do the logic you want to do (displaying a message, choosing to loop or not, etc)
(If you have not yet done exception handling, look up try and catch in Java)
as suggested by #patashu you can use try{ } catch() { }
as Integer.parseInt(argument) throws NumberFormatException if the argument is not a number(number in the form of string).
and about calling your input function again if user enters letter then you can simply do it by giving that particular input method a call inside catch block like:
try{
int guess = Integer.parseInt(stringGuess);
-----
-----
}
catch(NumberFormatException e){
System.out.println("Oooppps letter entered - try again with number ");
/**
now here make call to your method that takes input i.e getUserInput() in your case
**/
}

Reading a text file in Java and printing backwards with recursion

Write a Java program that recursively reads ten names from a file, and then outputs the total number of characters in the names, the list of names, and the list of names in reverse order. All looping must be performed recursively.
Jay Walker
Erol Flintstone
C. Erol Madre
Billy Pilgrim
Mickey Angels
José Francisco de San Martín
Squarebob Sponge Pants
Mischa Ternoff
Chester Peak
Al Italia
Ben Dover
Pat Pending
I am 100% lost. I would like advice on where would be the first place to start. Thinking about the program, I wanted to build a main that would call a scanner that would read the file first. When reading the file, it would count the characters in the text (quick question, would a scanner count the spaces between the characters?).
Next I was thinking of just a simple print function that would display the entire names.txt file.
Finally, the part the I'm 110% lost...how the heck would I go about listing the names in reverse order? What would I use? How does recursion fit in all this?
Something like this:
Reader(Stream strm)
{
string line;
if(!strm.eof())
{
line = strm.ReadLine();
Reader(strm);
}
// Info - char counte etc
string parseResult = Parse(line);
Print(parseResult);
}
Recursion will stop at the end of file and will start to unroll. The last message will be printed first.
Pseudocode for the recursion part:
function printLines(lines):
if lines not empty:
print first line from lines // this prints lines in order
call printLines(remaining lines)
print first line again // this prints lines in reverse order
Example output for lines ["line1", "line2", "line3"]
line1 // 1st output for printLines(["line1", "line2", "line3"])
line2 // 1st output for printLines(["line2", "line3"])
line3 // 1st output for printLines(["line3"])
// no output for printLines([])
line3 // 2nd output for printLines(["line3"])
line2 // 2nd output for printLines(["line2", "line3"])
line1 // 2nd output for printines(["line1", "line2", "line3"])
You can read file with scanner.nextLine(). It would read an entire line includiing spaces.
For how to print a string backwards using recursion, imagine that as a way containing houses on sides. You want to visit houses backwards (although you entered the way forwards). So you decided to go ahead until the way's end, and then back step by step and print neighbour house names.
function print( i )
if i == wayEnd
return
print(i + 1) // go ahead
// after you return, print:
output house at i
ADD
The code of method should be then:
private static Scanner scanner;
private static void readFile() {
if (!scanner.hasNext()) return;
String line = scanner.nextLine();
readFile();
System.out.println(line);
}
Just you have to call readFile() from main:
public static void main(String[] args) {
scanner = new Scanner(new File("myText.txt"));
readFile();
}
Am not good at scanning but using Desolator's scanner you can do the rest of the part as follows,
private Scanner scanner;
static Map<String, Integer> counts = new HashMap<String, Integer>();
public static void main(String[] args) {
scanner = new Scanner(new File("myText.txt"));
readFile();
System.out.println(counts);
}
private void readFile() {
if (!scanner.hasNext()) return;
String line = scanner.nextLine();
String[] names = line.split("([\\W\\s]+)");
for(int i=0;i<names.length;i++) {
populateMap(names[i]);
}
readFile();
}
static void populateMap(String str) {
counts.put(reverse(str), str.length());
}
static String reverse(String s) {
if(s.length() == 0)
return "";
return s.charAt(s.length() - 1) + reverse(s.substring(0,s.length()-1));
}
To train my Java skills I wrote you the following code:
import java.util.*;
import java.io.*;
public class RecursiveReadNames{
public static final int MAXLINES = 10;
public static void main(String[] args) throws FileNotFoundException {
Scanner scan = new Scanner(new File("listOfNames.txt"));
String[] names = new String[MAXLINES];
readNames(names, scan, 0);
printNames(names,0);
System.out.println();
printNamesReverse(names,0);
System.out.println(totalNumberOfCharsInNames(names, 0,0));
}
static String[] readNames(String[] names, Scanner scan, int curLine) {
if(curLine >= MAXLINES)
return names;
names[curLine] = scan.nextLine();
return readNames(names, scan, curLine+1);
}
static void printNames(String[] names, int cur) {
if(cur >= names.length)
return;
System.out.println(names[cur]);
printNames(names, cur+1);
}
static void printNamesReverse(String[] names, int cur) {
if(cur >= names.length)
return;
printNamesReverse(names, cur+1);
System.out.println(names[cur]);
}
static int totalNumberOfCharsInNames(String[] names, int cur, int sum) {
if(cur >= names.length)
return sum;
return totalNumberOfCharsInNames(names, cur+1, sum+names[cur].length());
}
}
do something like this
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class Test {
public static void printname(String name,BufferedReader br)
{
if(name!=null && br!=null)
{
try {
Test.printname(br.readLine(), br);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(name);
}
}
static Scanner scanner1 = new Scanner(System.in);
public static void main(String[] args)
{
//print the names and total character in each name
try {
FileInputStream fin=new FileInputStream("d:\\file.txt");
BufferedReader br=new BufferedReader(new InputStreamReader(fin));
String n;
while((n=br.readLine())!=null)
{
System.out.println(n+" length:"+n.length());
}
fin.close();
br.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//print names in reverse order
try {
FileInputStream f=new FileInputStream("d:\\file.txt");
BufferedReader br=new BufferedReader(new InputStreamReader(f));
try {
Test.printname(br.readLine(),br);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
f.close();
br.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
notice that I'm passing br object
import java.util.Scanner;
import java.io.*;
class Listnames{
public static void recursiveRead(Scanner scanner) {
String name;
if(scanner.hasNext())
{name=scanner.next();
recursiveRead(scanner);
System.out.println(name.length() +" "+ name);
}
}
public static void main(String[] args)
{
try{
Scanner scanner=new Scanner(new File("name.txt"));
scanner.useDelimiter(System.getProperty("line.separator"));
recursiveRead(scanner);
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}

Categories

Resources