infix to postfix in java using stack class - java

I'm trying to write infix to postfix program in java using stack. Here is my code:
import java.io.*;
import java.util.*;
public class ONP{
public static void main(String args[]) throws java.io.IOException, NumberFormatException ,EmptyStackException{
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
int n=Integer.parseInt(br.readLine());
StringBuilder out= new StringBuilder();
Stack st=new Stack();
for(int i=0;i<n;i++){
String input=br.readLine();
char in[]=input.toCharArray();
int len=input.length();
for (int j=0;j<len;j++){
if (in[j]>='a' && in[j]<='z'){
out.append(in[j]);
}
else if(in[j]=='('){
st.push(new Character(in[j]));
}
else if(in[j]=='+' || in[j]=='-' || in[j]=='*' || in[j]=='/' || in[j]=='^'){
st.push(new Character(in[j]));
}
else if(in[j]==')'){
int k=j;
while(in[k]!='(' && !st.empty() ){
char ch=st.pop().toString().charAt(0);
if(ch!='('&&ch!=')')
out.append(ch);
k--;
}
}
}
out.append("\n");
}
System.out.print(out);
}
}
Input:
((a+t)*((b+(a+c))^(c+d)))
Output:
at+bac++*cd+^
"*" should come after "+^" but it comes after "++". I can't find the bug.

It's just a small error.
In this code you look for '(' in the "in" array which makes no sense. You only want to look for it on the stack.
else if(in[j]==')'){
int k=j;
while(in[k]!='(' && !st.empty() ){
char ch=st.pop().toString().charAt(0);
if(ch!='('&&ch!=')')
out.append(ch);
k--;
}
}
Just change it to this
else if(in[j]==')'){
while(!st.empty() ){
char ch=st.pop().toString().charAt(0);
if(ch == '(') break;
out.append(ch);
}
}
That should fix the error. But there are a lot of other details you could improve. e.g. put part of the code into another method and make use of generics and autoboxing. Use Strings instead of chars to allow operators with more then one character and also implement operator precedence so you don't need so many parentheses.
Look at this.
import java.io.*;
import java.util.*;
import java.util.regex.*;
public class ONP {
private static int precedence(String operator) {
switch(operator) {
case "(": return 0;
case "+": case "-": return 1;
case "*": case "/": return 2;
case "^": return 3;
case "sin": case "cos": return 4;
default: return -1;
}
}
private static List<String> tokenize(String input) {
ArrayList<String> tokens = new ArrayList<>();
Pattern p = Pattern.compile("\\(|\\)|[A-Za-z]+|\\d*\\.\\d*|\\d+|\\S+?");
Matcher m = p.matcher(input);
while(m.find()) {
tokens.add(m.group());
}
return tokens;
}
private static List<String> toPostfix(List<String> infix) {
Stack<String> st = new Stack<>();
ArrayList<String> out = new ArrayList<>();
for(String s: infix) {
if(s.equals("(")){
st.push(s);
} else if(s.equals(")")){
while(!st.empty() ){
String s2 = st.pop();
if(s2.equals("(")) break;
out.add(s2);
}
} else if(precedence(s) > 0) {
int p = precedence(s);
while(!st.isEmpty() && precedence(st.peek()) >= p) out.add(st.pop());
st.push(s);
} else {
out.add(s);
}
}
while(!st.isEmpty()) out.add(st.pop());
return out;
}
public static void main(String args[]) throws java.io.IOException, NumberFormatException ,EmptyStackException{
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
int n=Integer.parseInt(br.readLine());
for(int i=0;i<n;i++){
String input=br.readLine();
List<String> tokens = tokenize(input);
System.out.println("tokens: " + tokens);
List<String> postfix = toPostfix(tokens);
System.out.print("postfix: ");
for(String s: postfix) System.out.print(s + " ");
System.out.println();
}
}
}

Well you need to implement operator precedence, and you haven't. You need to look up the Dijkstra Shunting-yard algorithm.

Related

How to read number as a String type and return an output in the equivalent Integer type

Input is a user string such as --> "ONE" and the output should be '1'
or,"NINE" output = '9'
public int check(String s)
{
int a=0;
switch(s)
{
case "ZERO": a= 0;
break;
case "ONE": a= 1;
break;
case "TWO": a= 2;
break;
case "THREE": a= 3;
break;
case "FOUR": a= 4;
break;
case "FIVE": a= 5;
break;
case "SIX": a= 6;
break;
case "SEVEN": a= 7;
break;
case "EIGHT": a= 8;
break;
case "NINE": a= 9;
}
return a;
}
main method
public static void main(String args[])throws IOException
{
int k=0,i;
String wrd="";
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();
String str="ONE,ZERO,TWO,THREE,FOUR,FIVE,SIX,SEVEN,EIGHT,NINE,";
int l = s.length();
for(i=0;i<l;i++)
{
while(str.charAt(k)!=s.charAt(i))k++;
if(str.charAt(k)==s.charAt(i))
{
while(!(str.charAt(k)==',') && (s.charAt(i)==(str.charAt(k))))
{
wrd=wrd+s.charAt(i++);
k++;
}
}
else
while(str.charAt(k)!=s.charAt(i))k++;
}
System.out.println(wrd);
Friend obj = new Friend();
int a = obj.check(wrd);
System.out.println(a);
}
the code i've written above converts the all other inputs to integer except for "FIVE" "SEVEN" "EIGHT" "NINE" for these inputs the output is '0'
THERE MAY BE SOME OTHER EASY WAY TO CONVERT I/P STRING TO INTEGER BUT
I NEED TO HAVE THIS METHOD FOR SOME OTHER PURPOSES.
I'd use enum like this:
public enum MyNumber {
ONE(1),
TWO(2),
THREE(3);
private final int value;
MyNumber(int value){
this.value = value;
}
int getValue(){
return this.value;
}
}
and use it...
public static void main(String[] args) {
//test
System.out.println(MyNumber.ONE.getValue());
System.out.println(MyNumber.valueOf("ONE"));
}
Please, notice that if you write
System.out.println(MyNumber.valueOf("ONES"));
you will get the run time exception. So, you'll have to check the strings before passing the parameter.
What is the purpose of the str variable? A simple way to achieve what you want can be:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();
System.out.println(s);
Friend friend = new Friend();
int a = friend.check(s);
System.out.println(a);
If performance is not an issue, use a Map<String, Integer>
i.E.
private static Map<String, Integer> map = new HashMap<>();
static {
map.put("zero", 0);
//do this for 1..9 here too
}
public static int check(String string) {
Integer number = map.get(string.toLowerCase());
return number == null ? -1 : number;
}
Is there a reason you are not using .split()? If it is allowed, you can try:
Friend friend = new Friend();
String[] numbers = str.split(",");
for(int i = 0; i < numbers.length; i++){
if(s.equals(numbers[i]){ //You could also do s.toUpperCase().equals(numbers[i])
System.out.println(s);
System.out.println(friend.check(s));
break;
}
}
However, if you cannot use .split(), the problem with your solution is multiple while loops nested inside for loops. You can solve this by using if statement instead. Try this:
for(i = 0; i < l; i++)
{
while(str.charAt(k)!=s.charAt(i)){
k++;
}
if((str.charAt(k) != ',') && (s.charAt(i)==(str.charAt(k))))
{
wrd=wrd+s.charAt(i); //You don't need to use while since
k++; //you are already in for loop. So i++ is already done
}
}
Also it will be optimal to use try catch blocks or exceptions if you do not want to run into errors.

Java regular expression prompt error character [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 6 years ago.
Improve this question
Usually, a regular expression can only indicate whether the statement and the rule match. I want to be able to indicate the wrong character when I'm not, what should I do。
Pattern compile = Pattern.compile("[a-zA-Z]*");
Matcher matcher = compile.matcher("abc1ac");
I want to make an error in the character 1.
I want to check a filter,like (name eq '1' or nickname ne '2') and code like '''' and user.name like 'jo%', the value using double '' translation
I write as follow,maybe better to use design pattern.
public class FilterExpressionException extends RuntimeException {
private String expression;
private int index;
public FilterExpressionException(String expression, int index) {
super(mark(expression, index));
this.expression = expression;
this.index = index;
}
public FilterExpressionException(String message, String expression, int index) {
super(message + "(" + mark(expression, index) + ")");
this.expression = expression;
this.index = index;
}
private static String mark(String expression, int index) {
return expression.substring(0, index) + '^' + expression.substring(index);
}
public String getExpression() {
return expression;
}
public int getIndex() {
return index;
}
}
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class FilterExpressionParserImpl {
private String[] relations = {"eq", "ne", "gt", "ge", "lt", "le", "like", "in", "bt"};
private String[] logices = {"and", "or"};
private char[][] relationChars = toCharArray(relations);
private char[][] logicChars = toCharArray(logices);
public static void main(String[] args) {
FilterExpressionParserImpl impl = new FilterExpressionParserImpl();
String expr = "(name eq '' or nickname ne '2' ) and (code like '''' or (user.A.name eq '''go''go''go'))";
List<String> parse = impl.parse(expr);
System.out.println(parse);
List<String> strings = impl.followUp(parse);
System.out.println(strings);
}
private class Variable {
Stack<String> words = new Stack<>();
Stack<Character> characters = new Stack<>();
Stack<Integer> brackets = new Stack<>();
int step = 0;
char character;
int commaTimes = 0;
char[][] relations;
char[][] logices;
public Variable(char[][] relations, char[][] logices) {
this.relations = relations;
this.logices = logices;
}
}
private List<String> followUp(List<String> middles) {
List<String> afters = new ArrayList<>(middles.size());
Stack<String> operators = new Stack<>();
String top;
for (String middle : middles) {
switch (middle) {
case "and":
case "or":
if (operators.size() > 0 && !operators.peek().equals("(")) afters.add(operators.pop());
operators.push(middle);
break;
case "(":
operators.push(middle);
break;
case ")":
while (!(top = operators.pop()).equals("(")) afters.add(top);
break;
default:
afters.add(middle);
}
}
while (!operators.isEmpty()) afters.add(operators.pop());
return afters;
}
private List<String> parse(String filter) {
filter = filter.trim();
Variable variable = new Variable(relationChars, logicChars);
for (int i = 0; i < filter.length(); i++) {
variable.character = filter.charAt(i);
switch (variable.character) {
case ' ':
if (variable.characters.isEmpty()) continue;
switch (variable.step) {
case 0:
dealPropertyPathEnd(filter, i, variable);
break;
case 1:
dealRelationEnd(variable);
break;
case 2:
dealValueEnd(filter, i, variable);
break;
case 3:
dealLogicEnd(variable);
break;
}
pushWord(variable);
break;
case '(':
if (variable.step != 0) throw new FilterExpressionException(filter, i);
variable.words.push(String.valueOf(variable.character));
variable.brackets.push(i);
break;
case ')':
if (variable.brackets.size() == 0) throw new FilterExpressionException(filter, i);
variable.brackets.pop();
if (variable.step == 2 && !variable.characters.isEmpty()) {
dealValueEnd(filter, i, variable);
pushWord(variable);
}
if (variable.step != 3) throw new FilterExpressionException(filter, i);
variable.words.push(String.valueOf(variable.character));
break;
default:
switch (variable.step) {
case 0:
if (!(isLetter(variable.character) || variable.character == '.')
|| ((variable.characters.size() == 0 || variable.characters.peek() == '.') && variable.character == '.'))
throw new FilterExpressionException(filter, i);
break;
case 1:
variable.relations = find(variable.relations, variable.characters.size(), variable.character);
if (variable.relations == null) throw new FilterExpressionException(filter, i);
break;
case 2:
if (variable.characters.size() == 0) {
if (variable.character != '\'') throw new FilterExpressionException(filter, i);
}
else {
if (variable.character == '\'') variable.commaTimes++;
else if (variable.commaTimes % 2 != 0) throw new FilterExpressionException(filter, i);
}
break;
case 3:
variable.logices = find(variable.logices, variable.characters.size(), variable.character);
if (variable.logices == null) throw new FilterExpressionException(filter, i);
break;
}
variable.characters.push(variable.character);
break;
}
}
if (!variable.characters.isEmpty()) {
if (variable.characters.peek() != '\'') throw new FilterExpressionException(filter, filter.length() - 1);
if (variable.commaTimes % 2 != 1) throw new FilterExpressionException(filter, filter.length() - 1 - variable.commaTimes);
pushWord(variable);
}
if (!variable.brackets.isEmpty()) throw new FilterExpressionException(filter, variable.brackets.firstElement());
return variable.words;
}
private void pushWord(Variable variable) {
String string = join(variable.characters);
if (variable.step == 3) {
if (string.equals("\'\'")) {
string = "";
} else {
string = string.replace("\'\'", "\'");
string = string.substring(1, string.length() - 1);
}
}
variable.words.push(string);
variable.characters.clear();
}
private String join(List<Character> characters) {
StringBuilder builder = new StringBuilder();
characters.forEach(builder::append);
return builder.toString();
}
private void dealPropertyPathEnd(String filter, int i, Variable variable) {
if (variable.characters.peek() == '.') throw new FilterExpressionException(filter, i);
variable.step = 1;
}
private void dealRelationEnd(Variable variable) {
variable.relations = relationChars;
variable.step = 2;
}
private void dealValueEnd(String filter, int i, Variable variable) {
if (variable.characters.peek() != '\'') throw new FilterExpressionException(filter, i);
if (variable.commaTimes % 2 != 1) throw new FilterExpressionException(filter, i);
variable.commaTimes = 0;
variable.step = 3;
}
private void dealLogicEnd(Variable variable) {
variable.logices = logicChars;
variable.step = 0;
}
private boolean isLetter(char character) {
return ('a' <= character && character <= 'z') || ('A' <= character && character <= 'Z');
}
private char[][] toCharArray(String[] strings) {
char[][] chars = new char[strings.length][];
for (int i = 0; i < strings.length; i++) {
chars[i] = strings[i].toCharArray();
}
return chars;
}
private char[][] find(char[][] sources, int column, char character) {
if (sources == null || sources.length == 0) return sources;
List<Integer> indexes = new ArrayList<>(sources.length);
for (int i = 0; i < sources.length; i++) {
if (sources[i].length > column && sources[i][column] == character) indexes.add(i);
}
if (indexes.isEmpty()) return null;
char[][] targets = new char[indexes.size()][];
for (int i = 0; i < indexes.size(); i++) {
targets[i] = sources[indexes.get(i)];
}
return targets;
}
}
Java's regular expression engine can do much more than just matching text. For more information, read the documentation.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class LookingAt {
public static String validate(String input, Pattern regex) {
Matcher m = regex.matcher(input);
if (m.matches())
return "OK";
if (m.lookingAt())
return "First error at index " + m.end();
if (m.hitEnd())
return "Too short";
return "Cannot match at all";
}
public static void main(String[] args) {
System.out.println(validate("abcac", Pattern.compile("[a-zA-Z]*")));
System.out.println(validate("abc1ac", Pattern.compile("[a-zA-Z]*")));
System.out.println(validate("abcac", Pattern.compile("[a-zA-Z]{10,}")));
System.out.println(validate("1abcac", Pattern.compile("[a-zA-Z]+")));
}
}

Clean string method for a recusrion palindrome java program?

This is a recursion program to test whether or not a sentence is a palindrome. It will run correctly if I write "bob" but not for "Madam I'm Adam" because of the caps and symbols. We are required to use a clean string method(?) to eliminate the spaces, symbols, and caps. This is what I have but I don't believe I've implemented it correctly. Could someone tell me how to improve/fix this? (Yes, I've looked all over the internet)
import java.util.Scanner;
public class Palindromes {
public static boolean isaPalindrome(String s) {
String cleanedString = clean(s);
if (s.length() == 0 || s.length() == 1)
return true;
if (s.charAt(0) == s.charAt(s.length() - 1))
return isaPalindrome(s.substring(1, s.length() - 1));
return false;
}
public static void main(String[] args) {
System.out.print("Enter a palindrome to test: ");
Scanner console = new Scanner(System.in);
String inStr = console.nextLine();
if (isaPalindrome(inStr)) {
System.out.printf("The input string, %s, is a palindrome.\n",
inStr);
reverseStr(inStr); // must be recursive!
System.out.println();
} else {
System.out.printf("The input string, %s, is not a palindrome.\n",
inStr);
}
}
private static String clean(String s) {
String cleaned = "";
return cleaned;
}
private static String reverseStr(String inStr) {
if ((null == inStr) || (inStr.length() <= 1)) {
return inStr;
}
return reverseStr(inStr.substring(1)) + inStr.charAt(0);
}
}
Your recursive method isaPalindrome is correct. If you want to further improve it, I would suggest you to avoid using subString to create parameters for your recursive call, this will create too many strings.
Instead, keep track of the positions of the characters in the original string that you are comparing:
public static boolean isaPalindrome(String s, int leftIndex, int rightIndex) {
if (leftIndex == rightIndex) return true;
if (s.charAt(leftIndex) == s.charAt(rightIndex))
return isaPalindrome(s, leftIndex + 1, rightIndex - 1);
return false;
}
You would invoke the method as: isaPalindrome(inStr, 0, inStr.length() - 1)
As for your clean method, you can use toLowerCase and Character.isLetter method to process the original string.
private static String clean(String s) {
String lowerCaseString = s.toLowerCase();
StringBuffer result = new StringBuffer();
for (int i = 0; i < lowerCaseString.length(); ++i) {
if (Character.isLetter(lowerCaseString.charAt(i))) {
result.append(lowerCaseString.charAt(i));
}
}
return result.toString();
}
Try this:
public static void main(final String[] args) {
final String unclean = "Madam I'm Adam";
final String clean = cleanString(unclean);
System.out.println("Clean string is: " + clean);
}
static private String cleanString(final String pTheString) {
final StringBuilder sb = new StringBuilder(pTheString.length());
for (final char c : pTheString.toCharArray()) {
switch (c) {
// ignore all those
case ' ':
case '\'':
case '.':
break;
// write the rest
default:
sb.append(c);
}
}
return sb.toString().toLowerCase();
}

Reverse Polish Notation Code Review

I've been trying to solve this question on SPOJ: http://www.spoj.com/problems/ONP/.
I've tried to implement a two Stack solution for the problem stated above. It works fine on my system, but I get a 'Wrong Answer' every time I try to submit the following code to the SPOJ Engine.
import java.io.*;
import java.util.Stack;
import java.util.Scanner;
public class InfixToPostfix {
public static String postfixString(String expression) {
Stack <Character> valueStack = new Stack <Character>();
Stack <Character> operatorStack = new Stack <Character>();
char[] tokens = expression.toCharArray();
for(char c : tokens) {
if(c == '('){
continue;
}
else if(c == '+' || c == '-' || c == '*' || c == '/' || c == '^') {
operatorStack.push(c);
continue;
}
else if(c == ')') {
valueStack.push(operatorStack.peek());
operatorStack.pop();
continue;
}
else {
valueStack.push(c);
continue;
}
}
return valueStack.toString();
}
public static void main (String [] args)throws java.lang.Exception {
String inputString = "";
int n1;
Scanner numberOfTestCases = new Scanner(System.in);
try
{
n1 = numberOfTestCases.nextInt();
StringBuilder[] sbuf = new StringBuilder[n1];
Scanner inputExpression = new Scanner(System.in);
for(int i = 0; i < n1; i++) {
sbuf[i] = new StringBuilder();
if(inputExpression.hasNextLine()) {
inputString = inputExpression.nextLine();
sbuf[i].append(postfixString(inputString).replaceAll("\\[", "").replaceAll("]", "").replaceAll(", ", ""));
}
else {
break;
}
}
for(int i = 0; i < n1; i++) {
System.out.println(sbuf[i].toString());
}
}
catch (Exception e) {
// System.out.println("");
System.out.println(e.getMessage());
// numberOfTestCases.next();
}
System.exit(0);
}
}
I can't figure out where I'm going wrong; I've tried all possible test cases.
P.S.: The problem assumes all inputs to be parenthesized; there's no need to include any code for resolving operator precedence.
return valueStack.toString();
This doesn't return the required format: it returns a comma-separated format bounded by [ and ], which isn't what is specified.
But I'm sure there are other problems.
I don't see anything in the problem statement that corresponds to your PS: on the contrary, it specifically mentions operator precedence.
Are you sure you've 'tried all possible test cases'? Try (1+2)/3 and 1+3/2.
You're peeking something you haven't pushed in the case of ')'.
I don't see why you need two stacks either.
Given the problem statement, what you need is either a recursive-descent expression parser or the Dijkstra Shunting-yard algorithm.

Unreported IOException? What is wrong with this code?

I am working on some code for homework and for the life of me can't figure out why this won't run. It ran until I added in the methods for file reading, which I know worked in another program. I took the code directly from some of my other work. So, can someone much better at Java than I tell me what I am doing wrong to have this problem? As this is homework please don't tell me how to fix any other problems, but I wouldn't discourage hints about them.
import java.io.*;
import java.util.Scanner;
import java.util.StringTokenizer;
public class vowels_r_us {
//for file reading
private static FileInputStream inFile;
private static InputStreamReader inReader;
private static BufferedReader reader;
//pasrsing input from file
private static StringTokenizer strTkn;
public static void main(String[] args)
{
initFile(); //prepare file for reading
while (reader.ready())//iterate as long as there is more avaliable data
{
String word, suffix, line;
line = getWordSuffix();
word = line.substring(0, line.indexOf(' '));
suffix = line.substring(line.indexOf(' '));
}
}
/*CONJUGATION METHODS*/
static String pluralize(String s)
{
String pluralForm;
switch (classifyEnding(s))
{
case 'c':
pluralForm = s.concat("GH");
break;
case 'v':
pluralForm = s.substring(0, s.length() - 1).concat("G");//drop last letter add G
break;
case 'd':
pluralForm = s + s.charAt(s.length() - 1) +"H";//double last letter, then add H
break;
default:
pluralForm = "If you are getting this something is broken, have fun debugging.";
break;
}
return pluralForm;
}
static String addSuffix(String word, String suffix)
{
String suffixAdded;
switch (classifyEnding(word))
{
case 'c':
suffixAdded = word + suffix;
break;
case 'v':
if(isVowel(suffix.charAt(0)))
{
suffixAdded = word + suffix.substring(1);//word + drop first letter of suffix then add suffix
}
else
{
suffixAdded = word + suffix.charAt(0) + suffix;//word + first letter of suffix + suffix
}
break;
case 'd':
if(isVowel(suffix.charAt(0)))
{
suffixAdded = word + suffix.charAt(0) + suffix;//word + first letter of suffix + suffix
}
else
{
suffixAdded = trimRepeatSequence(word) + suffix;
}
break;
default:
suffixAdded = "If you are getting this something is broken, have fun debugging.";
break;
}
return suffixAdded;
}
/*END CONJUGATION METHODS*/
/*STRING MODIFICATION AND TESTING METHODS*/
//removes lefmost vowel or consonant from sequence
static String trimRepeatSequence(String s)
{
String editedString = "";
boolean vBasedEnding = isVowel(s.charAt(s.length() - 1));
for (int i = s.length() - 1; i >= 0; i--)
{
if (isVowel(s.charAt(i)) != vBasedEnding)
{
editedString = s.substring(0, i+1) + s.substring(i+2, s.length());
break;
}
}
return editedString;
}
/* classify endings in to three grammatical categories, single vowel ending 'v', single consonant ending 'c', double type ending 'd'
*/
static char classifyEnding(String s)
{
char grammaticalClass;
if (isVowel(s.charAt(s.length()- 1)) == isVowel(s.charAt(s.length()- 2)))
{
grammaticalClass = 'd';
}
else
{
grammaticalClass = isVowel(s.charAt(s.length()- 1)) == true? 'v' : 'c';
}
return grammaticalClass;
}
static boolean isVowel(char c)
{
boolean b;//rename
switch (Character.toLowerCase(c))
{
case 'a': case 'c':
case 's': case 'l':
b = true;
break;
default:
b = false;
break;
}
return b;
}
/*END STRING MODIFICATION AND TESTING METHODS*/
/*FILE READER METHODS*/
//read file for input
public static void initFile() throws IOException
{
inFile = new FileInputStream ("C:\\Users\\Tom\\Dropbox\\!!VHSAPCSData\\VHSP35data.txt");
inReader = new InputStreamReader(inFile);
reader = new BufferedReader(inReader);
}
public static String getWordSuffix() throws IOException
{
String line;
line = reader.readLine();
return line;
}
}
You need to wrap your IO code in a try / catch:
import java.io.*;
import java.util.Scanner;
public class ScanXan {
public static void main(String[] args) throws IOException {
Scanner s = null;
try {
s = new Scanner(new BufferedReader(new FileReader("xanadu.txt")));
while (s.hasNext()) {
System.out.println(s.next());
}
} finally {
if (s != null) {
s.close();
}
}
}
}
taken from: http://docs.oracle.com/javase/tutorial/essential/io/scanning.html

Categories