How to simplify my methods with tons of if statements [duplicate] - java

This question already has answers here:
Read a text file and store every single character occurrence
(3 answers)
Closed 6 years ago.
My code is supposed to read an input file and count the uses of each character in the file then print them all out. The code works but I know that there has to be a way to cut down on all the if statements. Right now I'm making methods for reading and one for output so its not all written in my main method. Any and all suggestions are helpful, thanks.
import java.io.FileReader;
import java.io.IOException;
public class CharacterCounts {
static int nl = 0;
static int sp = 0;
static int ex = 0;
static int ap = 0;
static int cm = 0;
static int hy = 0;
static int pd = 0;
static int cn = 0;
static int sm = 0;
static int qu = 0;
static int a = 0;
static int b = 0;
static int c = 0;
static int d = 0;
static int e = 0;
static int f = 0;
static int g = 0;
static int h = 0;
static int ii = 0;
static int j = 0;
static int k = 0;
static int l = 0;
static int m = 0;
static int n = 0;
static int o = 0;
static int p = 0;
static int q = 0;
static int r = 0;
static int s = 0;
static int t = 0;
static int u = 0;
static int v = 0;
static int w = 0;
static int x = 0;
static int y = 0;
static int z = 0;
static int A = 0;
static int B = 0;
static int C = 0;
static int D = 0;
static int E = 0;
static int F = 0;
static int G = 0;
static int H = 0;
static int I = 0;
static int J = 0;
static int K = 0;
static int L = 0;
static int M = 0;
static int N = 0;
static int O = 0;
static int P = 0;
static int Q = 0;
static int R = 0;
static int S = 0;
static int T = 0;
static int U = 0;
static int V = 0;
static int W = 0;
static int X = 0;
static int Y = 0;
static int Z = 0;
public static void main(String args[]) throws IOException {
String file = args[0];
#SuppressWarnings("resource")
FileReader scanner = new FileReader(file);
int i;
while ((i = scanner.read()) != -1) {
if ((char) i == '\n') {
nl++;
} else if ((char) i == ' ') {
sp++;
} else if ((char) i == '!') {
ex++;
} else if ((char) i == '\'') {
ap++;
} else if ((char) i == ',') {
cm++;
} else if ((char) i == '-') {
hy++;
} else if ((char) i == '.') {
pd++;
} else if ((char) i == ':') {
cn++;
} else if ((char) i == ';') {
sm++;
} else if ((char) i == '?') {
qu++;
} else if ((char) i == 'a') {
a++;
} else if ((char) i == 'b') {
b++;
} else if ((char) i == 'c') {
c++;
} else if ((char) i == 'd') {
d++;
} else if ((char) i == 'e') {
e++;
} else if ((char) i == 'f') {
f++;
} else if ((char) i == 'g') {
g++;
} else if ((char) i == 'h') {
h++;
} else if ((char) i == 'i') {
ii++;
} else if ((char) i == 'j') {
j++;
} else if ((char) i == 'k') {
k++;
} else if ((char) i == 'l') {
l++;
} else if ((char) i == 'm') {
m++;
} else if ((char) i == 'n') {
n++;
} else if ((char) i == 'o') {
o++;
} else if ((char) i == 'p') {
p++;
} else if ((char) i == 'q') {
q++;
} else if ((char) i == 'r') {
r++;
} else if ((char) i == 's') {
s++;
} else if ((char) i == 't') {
t++;
} else if ((char) i == 'u') {
u++;
} else if ((char) i == 'v') {
v++;
} else if ((char) i == 'w') {
w++;
} else if ((char) i == 'x') {
x++;
} else if ((char) i == 'y') {
y++;
} else if ((char) i == 'z') {
z++;
} else if ((char) i == 'A') {
A++;
} else if ((char) i == 'B') {
B++;
} else if ((char) i == 'C') {
C++;
} else if ((char) i == 'D') {
D++;
} else if ((char) i == 'E') {
E++;
} else if ((char) i == 'F') {
F++;
} else if ((char) i == 'G') {
G++;
} else if ((char) i == 'H') {
H++;
} else if ((char) i == 'I') {
I++;
} else if ((char) i == 'J') {
J++;
} else if ((char) i == 'K') {
K++;
} else if ((char) i == 'L') {
L++;
} else if ((char) i == 'M') {
M++;
} else if ((char) i == 'N') {
N++;
} else if ((char) i == 'O') {
O++;
} else if ((char) i == 'P') {
P++;
} else if ((char) i == 'Q') {
Q++;
} else if ((char) i == 'R') {
R++;
} else if ((char) i == 'S') {
S++;
} else if ((char) i == 'T') {
T++;
} else if ((char) i == 'U') {
U++;
} else if ((char) i == 'V') {
V++;
} else if ((char) i == 'W') {
W++;
} else if ((char) i == 'X') {
X++;
} else if ((char) i == 'Y') {
Y++;
} else if ((char) i == 'Z') {
Z++;
}
}
if (nl != 0) {
System.out.printf("'/n' %d\n", nl);
}
if (sp != 0) {
System.out.printf("' ' %d\n", sp);
}
if (ex != 0) {
System.out.printf("'!' %d\n", ex);
}
if (ap != 0) {
System.out.printf("''' %d\n", ap);
}
if (cm != 0) {
System.out.printf("',' %d\n", cm);
}
if (hy != 0) {
System.out.printf("'-' %d\n", hy);
}
if (pd != 0) {
System.out.printf("'.' %d\n", pd);
}
if (cn != 0) {
System.out.printf("':' %d\n", cn);
}
if (sm != 0) {
System.out.printf("';' %d\n", sm);
}
if (qu != 0) {
System.out.printf("'?' %d\n", qu);
}
if (A != 0) {
System.out.printf("'A' %d\n", A);
}
if (B != 0) {
System.out.printf("'B' %d\n", B);
}
if (C != 0) {
System.out.printf("'C' %d\n", C);
}
if (D != 0) {
System.out.printf("'D' %d\n", D);
}
if (E != 0) {
System.out.printf("'E' %d\n", E);
}
if (F != 0) {
System.out.printf("'F' %d\n", F);
}
if (G != 0) {
System.out.printf("'G' %d\n", G);
}
if (H != 0) {
System.out.printf("'H' %d\n", H);
}
if (I != 0) {
System.out.printf("'I' %d\n", I);
}
if (J != 0) {
System.out.printf("'J' %d\n", J);
}
if (K != 0) {
System.out.printf("'K' %d\n", K);
}
if (L != 0) {
System.out.printf("'L' %d\n", L);
}
if (M != 0) {
System.out.printf("'M' %d\n", M);
}
if (N != 0) {
System.out.printf("'N' %d\n", N);
}
if (O != 0) {
System.out.printf("'O' %d\n", O);
}
if (P != 0) {
System.out.printf("'P' %d\n", P);
}
if (Q != 0) {
System.out.printf("'Q' %d\n", Q);
}
if (R != 0) {
System.out.printf("'R' %d\n", R);
}
if (S != 0) {
System.out.printf("'S' %d\n", S);
}
if (T != 0) {
System.out.printf("'T' %d\n", T);
}
if (U != 0) {
System.out.printf("'U' %d\n", U);
}
if (V != 0) {
System.out.printf("'V' %d\n", V);
}
if (W != 0) {
System.out.printf("'W' %d\n", W);
}
if (X != 0) {
System.out.printf("'X' %d\n", X);
}
if (Y != 0) {
System.out.printf("'Y' %d\n", Y);
}
if (Z != 0) {
System.out.printf("'Z' %d\n", Z);
}
if (a != 0) {
System.out.printf("'a' %d\n", a);
}
if (b != 0) {
System.out.printf("'b' %d\n", b);
}
if (c != 0) {
System.out.printf("'c' %d\n", c);
}
if (d != 0) {
System.out.printf("'d' %d\n", d);
}
if (e != 0) {
System.out.printf("'e' %d\n", e);
}
if (f != 0) {
System.out.printf("'f' %d\n", f);
}
if (g != 0) {
System.out.printf("'g' %d\n", g);
}
if (h != 0) {
System.out.printf("'h' %d\n", h);
}
if (ii != 0) {
System.out.printf("'i' %d\n", ii);
}
if (j != 0) {
System.out.printf("'j' %d\n", j);
}
if (k != 0) {
System.out.printf("'k' %d\n", k);
}
if (l != 0) {
System.out.printf("'l' %d\n", l);
}
if (m != 0) {
System.out.printf("'m' %d\n", m);
}
if (n != 0) {
System.out.printf("'n' %d\n", n);
}
if (o != 0) {
System.out.printf("'o' %d\n", o);
}
if (p != 0) {
System.out.printf("'p' %d\n", p);
}
if (q != 0) {
System.out.printf("'q' %d\n", q);
}
if (r != 0) {
System.out.printf("'r' %d\n", r);
}
if (s != 0) {
System.out.printf("'s' %d\n", s);
}
if (t != 0) {
System.out.printf("'t' %d\n", t);
}
if (u != 0) {
System.out.printf("'u' %d\n", u);
}
if (v != 0) {
System.out.printf("'v' %d\n", v);
}
if (w != 0) {
System.out.printf("'w' %d\n", w);
}
if (x != 0) {
System.out.printf("'x' %d\n", x);
}
if (y != 0) {
System.out.printf("'y' %d\n", y);
}
if (z != 0) {
System.out.printf("'z' %d\n", z);
}
}
}

This can be easily improved by using a Map<Character, Integer>. Change your declaration to this:
static final Map<Character, Integer> VALUES = new HashMap<>();
Then the body of your code can be changed to this:
Integer val = VALUES.get(i);
if(val == null) VALUES.put(i, 1);
else VALUES.put(i, val + 1);
Then simply iterate over it to display the values at the end.
Keeping the order, or restricting it to just those characters, could be done by using a LinkedHashMap and pre-populating all the desired values with zero.
Here's an example of what that would look like:
private static final Map<Character, Integer> VALUES = new LinkedHashMap<>();
static{
for(char c : "\n !\\,-.:;?".toCharArray()){
VALUES.put(c, 0);
}
for(char c = 'a'; c < 'z'; c++){
VALUES.put(c, 0);
}
for(char c = 'A'; c < 'Z'; c++){
VALUES.put(c, 0);
}
}
public static void main(String args[]){
try{
String file = args[0];
FileReader scanner = new FileReader(file);
int i;
while ((i = scanner.read()) != -1) {
Integer val = VALUES.get((char)i);
if(val != null) VALUES.put((char)i, val + 1);
}
for(Map.Entry<Character, Integer> entry : VALUES.entrySet()){
if(entry.getValue() > 0)
System.out.println(entry.getKey() + " " + entry.getValue());
}
} catch(IOException ioe){
ioe.printStackTrace();
}
}
^Untested, but should at least be close.
Now tested, and the numerous bugs have been fixed.
Same behavior, more maintainable, less likely to contain typos, and 10% of the typing.

Related

Is there a solution to prevent this recursion?

In this program, a randomly generated 2D array is populated with 1's or 0's and I attempt to find a path of 1's (no diagonal movement). I have got the program to work for smaller dimensions of the 2D array, but when the dimensions are too large, the error Exception in thread "main" java.lang.StackOverflowError occurs.
import java.util.Scanner;
import java.util.Random;
public class Daft {
private int counter = 0;
public static void main(String[] args) {
Daft punk = new Daft();
punk.run();
}
public void run() {
int ans;
int[][] array;
int[][] solvedPath;
do {
counter = 1;
array = populate(defineArray(firstDimension(),secondDimension()));
solvedPath = findPath(array);
System.out.println("Times before solvable: " + counter);
print(solvedPath);
ans = continuity();
}while(ans != 0);
}
public int[][] findPath(int[][] array) {
int r = 0, c = 0;
while(true) {
array[0][0] = 7;
if(c == 0 && r == array.length-1) { //reached the bottom left, checks right
if(array[r][c+1] == 1) {
array[r][c+1] = 7;
c+=1;
} else {
array[r][c] = 7;
break;
}
} else if(c == array[0].length-1 && r == array.length-1) { //reached the bottom right, checks left
if(array[r][c-1] == 1) {
array[r][c-1] = 7;
} else {
array[r][c] = 7;
break;
}
} else if(r == array.length-1) { //reached the bottom, checks left/right
if(array[r][c+1] == 1 && array[r][c-1] == 1) {
counter++;
newPath(array);
break;
} else if(array[r][c+1] == 1) { //checks right
array[r][c+1] = 7;
c+=1;
} else if(array[r][c-1] == 1) { //checks left
array[r][c-1] = 7;
c-=1;
} else { //end of path
array[r][c] = 7;
break;
}
} else if(c == 0) { //reached the left, checks right/bottom
if(array[r][c+1] == 1 && array[r+1][c] == 1) { //checks if path is unique
counter++;
newPath(array);
break;
} else if(array[r][c+1] == 1) {
array[r][c+1] = 7;
c+=1;
} else if(array[r+1][c] == 1) {
array[r+1][c] = 7;
r+=1;
} else {
counter++; //path has ended, not solvable
newPath(array);
break;
}
} else if(c == array[0].length-1) { //reached the right, checks left/bottom
if(array[r+1][c] == 1 && array[r][c-1] == 1) { //checks if path is unique
counter++;
newPath(array);
break;
} else if(array[r+1][c] == 1) {
array[r+1][c] = 7;
r+=1;
} else if(array[r][c-1] == 1) {
array[r][c-1] = 7;
c-=1;
} else {
counter++; //path has ended, not solvable
newPath(array);
break;
}
} else if(array[r][c+1] == 1 && array[r+1][c] == 1) { //checks if path is unique
counter++;
newPath(array);
break;
} else if(array[r][c-1] == 1 && array[r+1][c] == 1) { //checks if path is unique
counter++;
newPath(array);
break;
} else if(array[r][c+1] == 1) { //checks right
array[r][c+1] = 7;
c+=1;
} else if(array[r+1][c] == 1) { //checks bottom
array[r+1][c] = 7;
r+=1;
} else if(array[r][c-1] == 1) { //checks left
array[r][c-1] = 7;
c-=1;
} else {
counter++;
newPath(array);
break;
}
}
return array;
}
public int firstDimension() {
Scanner in = new Scanner(System.in);
System.out.println("Size of the first dimension:");
return in.nextInt();
}
public int secondDimension() {
Scanner in = new Scanner(System.in);
System.out.println("Size of the second dimension:");
return in.nextInt();
}
public int[][] defineArray(int firstDimension, int secondDimension) {
return new int[firstDimension][secondDimension];
}
public int[][] populate(int[][] array) {
Random rand = new Random();
for(int i = 0; i < array.length; i++) {
for(int j = 0; j < array[i].length; j++) {
array[i][j] = rand.nextInt(2);
}
}
return array;
}
public int continuity() {
Scanner in = new Scanner(System.in);
System.out.println("Enter a number to continue (0 to quit):");
return in.nextInt();
}
public void print(int[][] array) {
for(int[] ints : array) {
for(int anInt : ints) {
System.out.print(anInt + " ");
}
System.out.println();
}
System.out.println();
}
public void newPath(int[][] array) {
findPath(populate(array));
}
}

How to fix my merge sort?

When I compile my merge sort, it compiles fines but there is no output.
This needs to be done recursively. Also, I do run my printList() function in my main, so it isn't that I am forgetting to print the list. I've been staring at this for the past 30 minutes.
public void printList(){
for(int i = 0; i < fullNames.size(); i++){
System.out.println(fullNames.get(i));
}
}
public void sort(){
fullNames = mergeSort(fullNames);
}
public ArrayList<String> extract(ArrayList<String> ex, int low, int high){
ArrayList<String> answer = new ArrayList<String>();
for(int i = low; i <= high; i++){
answer.add(ex.get(i));
}
return answer;
}
public ArrayList<String> merge(ArrayList<String> first, ArrayList<String> second){
int f = 0;
int s = 0;
ArrayList<String> answer = new ArrayList<String>();
while(first.size() > 0 || second.size() > 0){
if(s != second.size() && f != first.size()){
if(first.get(f).compareTo(second.get(s)) > 0){
answer.add(second.get(s));
s++;
}
else if(first.get(f).compareTo(second.get(s)) < 0){
answer.add(first.get(f));
f++;
}
}
else if(f == first.size()){
while(s != second.size()){
answer.add(second.get(s));
s++;
}
}
else{
while(f != first.size()){
answer.add(first.get(f));
f++;
}
}
}
return answer;
}
public ArrayList<String> mergeSort(ArrayList<String> names){
int k = names.size()-1;
if(k > 1){
ArrayList<String> first = extract(names, 0, k / 2);
ArrayList<String> second = extract(names, (k / 2) + 1, k);
mergeSort(first);
mergeSort(second);
return merge(first, second);
}
else{
return names;
}
}
The while condition in your merge will never be false because the size of first and second is never adjusted within the loop:
while(first.size() > 0 || second.size() > 0){
if(s != second.size() && f != first.size()){
if(first.get(f).compareTo(second.get(s)) > 0){
answer.add(second.get(s));
s++;
}
else if(first.get(f).compareTo(second.get(s)) < 0){
answer.add(first.get(f));
f++;
}
}
else if(f == first.size()){
while(s != second.size()){
answer.add(second.get(s));
s++;
}
}
else{
while(f != first.size()){
answer.add(first.get(f));
f++;
}
}
}

How do I strip empty lines from an InputStream?

What is the best way to strip empty lines from an InputStream in java?
A custom FilterReader can be used, preferably one that copes with different line endings (\n, \r, and \r\n) as well.
Usage:
StripEmptyLinesReader reader = new StripEmptyLinesReader(new InputStreamReader(origStream));
ReaderInputStream newStream = new ReaderInputStream(reader, someCharset);
Here's the class:
public class StripEmptyLinesReader extends FilterReader {
private char[] prevChars = new char[3];
public StripEmptyLinesReader(Reader reader) {
super(reader);
}
#Override
public int read(char[] buffer, int fromIndex, int length) throws IOException {
int numChars = 0;
while (numChars == 0) {
numChars = in.read(buffer, fromIndex, length);
if (numChars == -1) {
return -1;
}
int lastIndex = fromIndex;
for (int i = fromIndex; i < fromIndex + numChars; i++) {
int charsToSkip = numberOfNewlineCharactersToSkip(buffer[i]);
switch (charsToSkip) {
case 0:
buffer[lastIndex++] = buffer[i];
break;
case 2:
lastIndex--;
break;
}
prevChars[0] = buffer[i];
prevChars[1] = (i > 0) ? buffer[i - 1] : '\0';
prevChars[2] = (i > 1) ? buffer[i - 2] : '\0';
}
numChars = lastIndex - fromIndex;
}
return numChars;
}
private int numberOfNewlineCharactersToSkip(char currentChar) {
if ((currentChar == '\n' && prevChars[0] == '\n') || (currentChar == '\r' && prevChars[0] == '\r')) {
return 1;
}
if ((currentChar == '\n' && prevChars[0] == '\r' && prevChars[1] == '\n' && prevChars[2] == '\r')) {
return 2;
}
return 0;
}
#Override
public int read() throws IOException {
char[] buffer = new char[1];
int result = read(buffer, 0, 1);
return (result == -1) ? -1 : (int) buffer[0];
}
}

Special characters in a string [JAVA]

folks, the method below would throw an Exception if other character than "01xX \t"(including whitespace and \t inside a passed String) is found. If I have this String "1 x \tX 00", the method should return [1,X,X,X,X,X,X,X,0,0] but Im getting only [1,X,X,0,0] in which the 'whitespace' and '\t' somehow are not getting included. 'Whitespace' and '\n' also should return 'X'. Please could smb help me?
//Here's the test case that I'm failing
#Test (timeout=3000) public void signal13(){
String inp = "1 x \tX 00";
List<Signal> expecteds = Signal.fromString(inp);
assertEquals(expecteds, Arrays.asList(new Signal[]{Signal.HI, Signal.X, Signal.X, Signal.LO, Signal.LO}));
}
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public enum Signal {
HI, LO, X;
public Signal invert()
{
if(this == HI)
return LO;
else if(this == LO)
return HI;
else if(this == X)
return X;
return this;
}
public static Signal fromString(char c)
{
if(c == '1')
return HI;
else if(c == '0')
return LO;
else if(c == 'X')
return X;
else if(c == 'x')
return X;
else
throw new ExceptionLogicMalformedSignal(c, "Invalid character!");
}
public static List <Signal> fromString(String inps)
{
List<Signal> values = new ArrayList<Signal>();
for(int i = 0; i < inps.length(); i++)
{
if(inps.charAt(i) == '1')
values.add(HI);
else if(inps.charAt(i) == '0')
values.add(LO);
else if(inps.charAt(i) == 'X')
values.add(X);
else if(inps.charAt(i) == 'x')
values.add(X);
else if(inps.charAt(i) == ' ')
values.add(X);
else if(inps.charAt(i) == '\t')
{
values.add(X);
values.add(X);
}
else
throw new ExceptionLogicMalformedSignal(inps.charAt(0), "Invalid character!");
}
return values;
}
#Override
public String toString()
{
if(this == HI)
return "1";
else if(this == LO)
return "0";
else if(this == X)
return "X";
return "Error here!";
}
public static String toString(List<Signal> sig)
{
String result = "";
ArrayList<Signal> temp = new ArrayList<>();
for(Signal x: sig)
{
temp.add(x);
}
for(int i = 0; i < temp.size(); i++)
{
if(temp.get(i) == HI)
result += "1";
else if(temp.get(i) == LO)
result += "0";
else if(temp.get(i) == X)
result += "X";
}
return result;
}
}
Seem like the assertion is not correct, it's:
assertEquals(expecteds, Arrays.asList(new Signal[]{Signal.HI, Signal.X, Signal.X, Signal.LO, Signal.LO}));
while it should be :
List<Signal> actual = Signal.fromString(inp);
List<Signal> expected = Arrays.asList(new Signal[]{Signal.HI, Signal.X, Signal.X,Signal.X,Signal.X,Signal.X,Signal.X,Signal.X, Signal.LO, Signal.LO});
assertEquals(expected, actual);
Because the expected result is [1,X,X,X,X,X,X,X,0,0]
here is a modified version of your code that works as you need it...
private String fromString(String inps) throws Exception {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < inps.length(); i++) {
if (inps.charAt(i) == '1') {
sb.append("1");
} else if (inps.charAt(i) == '0') {
sb.append("0");
} else if (inps.charAt(i) == 'X') {
sb.append("x");
} else if (inps.charAt(i) == 'x') {
sb.append("x");
} else if (inps.charAt(i) == ' ') {
sb.append("x");
} else if (inps.charAt(i) == '\t') {
sb.append("x");
sb.append("x");
} else {
throw new Exception("invalid character");
}
}
return sb.toString();
}
When you output fromString("1 x \tX 00") you get the result 1xxxxxxx00 as expected.
Hope this helps

Infix to postfix digit or letter concatenation

working on a program that converts infix notation to postfix. I have it working for most instances except when character concatenation is required. For example, if I pass in a string of numbers (1002+304) it outputs 1, 0, 0, 2, 3, 0, 4, + instead of 1002, 304, +.
import java.util.*;
public class InfixToPostfix {
private Deque<String> postfix; // Used as a queue of String
private static boolean isOperator(char op)
{
if(op=='+'||op=='-'||op=='*'||op=='/'||op=='^'
||op=='('||op==')')
{
return true;
}
return false;
}
private static boolean lowerEqualPrec(char op1, char op2)
{
boolean flag = false;
if(op1=='+'|| op1=='-')
{
if(op2=='+'||op2=='-'||op2=='*'||op2=='/'||op2=='^')
{
flag= true;
}
}else if(op1=='*' || op1=='/')
{
if(op2=='*'||op2=='/'||op2=='^')
{
flag= true;
}
}else if(op1=='^')
{
flag= false;
}else if(op1=='(')
{
flag= false;
}
return flag;
}
public InfixToPostfix(String infix)
{
for(int i=0; i<infix.length(); i++)
{
if(infix.length() ==0 || infix.charAt(0)==')' ||
infix.charAt(i)=='&' || infix.charAt(infix.length()-1)=='(')
{
throw new IllegalArgumentException();
}
}
postfix = new LinkedList<String>();
Stack<Character> stack = new Stack<Character>();
Character ch;
String digits="";
String letters = "";
for(int i=0; i<infix.length(); i++)
{
ch=infix.charAt(i);
if(ch == ' ')
{
//do nothing
}
if(Character.isDigit(ch))
{
digits=""+ch;
if(i+1 >= infix.length() || !Character.isDigit(infix.charAt(i+1)))
{
digits=digits+"";
}
postfix.add(digits);
}
if(Character.isLetter(ch))
{
letters=ch+"";
postfix.add(letters);
}
if(isOperator(ch))
{
if(ch == ')')
{
if(!stack.isEmpty() && stack.peek() != '(')
{
postfix.add(""+stack.pop());
if(!stack.isEmpty())
{
stack.pop();
}
}
}
else
{
if(!stack.isEmpty() && !lowerEqualPrec(ch, stack.peek()))
{
stack.push(ch);
}
else
{
while(!stack.isEmpty() && lowerEqualPrec(ch, stack.peek()))
{
char pop = stack.pop();
if(ch!='(')
{
postfix.add(pop+"");
}
}
stack.push(ch);
}
}
}
}
while(!stack.isEmpty()&&stack.peek()!='(')
{
postfix.add(stack.pop()+"");
}
System.out.println(postfix);
}
public Iterator<String> iterator()
{
return new PostfixIterator(postfix) ;
}
public static void main(String[] args)
{
InfixToPostfix test = new InfixToPostfix("1002+304");
}
}
For postfixConversion
public static String postfixConversion(String input) {
int i;
String postfix = "";
Stack<Character> stack = new Stack<Character>();
for (i = 0; i < input.length(); i++) {
while (input.charAt(i) == ' ') {
++i;
}
if (Character.isDigit(input.charAt(i))) {
postfix += input.charAt(i);
//if (!Character.isDigit(input.charAt(i+1))) {
postfix += ' ';
//}
}
else if (precedenceLevel(input.charAt(i)) != 0) {
while ((!stack.isEmpty()) && (precedenceLevel(stack.peek()) >= precedenceLevel(input.charAt(i))) && (stack.peek() != '(')) {
postfix += stack.peek();
postfix += ' ';
stack.pop();
}
stack.push(input.charAt(i));
}
else if (input.charAt(i) == '(') {
stack.push(input.charAt(i));
}
else if (input.charAt(i) == ')') {
while (!stack.isEmpty() && stack.peek() != '(') {
postfix += stack.peek();
stack.pop();
}
stack.pop();
}
}
while (!stack.isEmpty()) {
postfix += stack.peek();
postfix += ' ';
}
return postfix;
}

Categories

Resources