I am trying to make a fraction calculator that quits when you type quit regardless of the casing. However these two errors have been coming up. Any suggestion?? Thanks a lot.
FractionCalculator.java:70: error: '(' expected
else if kb.next().equalsIgnoreCase("quit"){
^
FractionCalculator.java:70: error: ')' expected
else if kb.next().equalsIgnoreCase("quit"){
^
FractionCalculator.java:70: error: 'else' without 'if'
else if kb.next().equalsIgnoreCase("quit"){
^
import java.util.*;
public class FractionCalculator {
// useDelimiter or split method in string class
public static void main(String[] args) {
Greeting();
produceAnswer();
}
static String value1Str = "";
static String value2Str = "";
static char operator = ' ';
public static void Greeting() {
Scanner kb = new Scanner (System.in);
String userName;
System.out.print("Hello Person, What is your first name: ");
userName = kb.next();
System.out.println("Hi " +userName +", welcome to the great mystical fraction calculator.");
}
public static void produceAnswer() {
Scanner kb = new Scanner (System.in);
System.out.println("What is your input or type quit to leave?");
String input = kb.nextLine();
boolean value1Done = false;
boolean operatorDone = false;
boolean value2Done = false;
boolean correctFormat = false;
for (int i = 0; i < input.length(); i++) {
System.out.println("The input of given string is: " +input.charAt(i));
if (input.charAt(i) != ' ' && value1Done == false) {
value1Str += input.charAt(i);
}
else {
value1Done = true;
}
if (input.charAt(i) == '+' || input.charAt(i) == '-' || input.charAt(i) == '*' || input.charAt(i) == '/' && operatorDone == false && value1Done == true) {
operator = input.charAt(i);
operatorDone = true;
i=i+1;
}
if (input.charAt(i) != ' ' && value1Done == true && value2Done == false) {
value2Str += input.charAt(i);
}
else {
value2Done = false;
}
else if kb.next().equalsIgnoreCase("quit"){
System.out.println("Why are you leaving? Comeback soon bby");
break;
// quit = true;
//correctFormat = true;
}
}
System.out.println("value1Str is: " +value1Str);
System.out.println("Operator is: " +operator);
System.out.println("Value2Str is: " +value2Str);
}
}
You have errors in using if condition .
Updating your code with proper use of if , if else conditions.
import java.util.*;
public class FractionCalculator {
// useDelimiter or split method in string class
public static void main(String[] args) {
Greeting();
produceAnswer();
}
static String value1Str = "";
static String value2Str = "";
static char operator = ' ';
public static void Greeting() {
Scanner kb = new Scanner(System.in);
String userName;
System.out.print("Hello Person, What is your first name: ");
userName = kb.next();
System.out.println("Hi " + userName
+ ", welcome to the great mystical fraction calculator.");
}
public static void produceAnswer() {
Scanner kb = new Scanner(System.in);
System.out.println("What is your input or type quit to leave?");
String input = kb.nextLine();
boolean value1Done = false;
boolean operatorDone = false;
boolean value2Done = false;
boolean correctFormat = false;
for (int i = 0; i < input.length(); i++) {
System.out.println("The input of given string is: "
+ input.charAt(i));
if (input.charAt(i) != ' ' && value1Done == false) {
value1Str += input.charAt(i);
} else {
value1Done = true;
}
if (input.charAt(i) == '+' || input.charAt(i) == '-'
|| input.charAt(i) == '*' || input.charAt(i) == '/'
&& operatorDone == false && value1Done == true) {
operator = input.charAt(i);
operatorDone = true;
i = i + 1;
}
if (input.charAt(i) != ' ' && value1Done == true
&& value2Done == false) {
value2Str += input.charAt(i);
} else if (kb.next().equalsIgnoreCase("quit")) {
System.out.println("Why are you leaving? Comeback soon bby");
break;
// quit = true;
// correctFormat = true;
} else {
value2Done = false;
}
}
System.out.println("value1Str is: " + value1Str);
System.out.println("Operator is: " + operator);
System.out.println("Value2Str is: " + value2Str);
}
}
Check how to use if-then and if-then-else Statements at this link :
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/if.html
You have a malformed if statement:
if (...) { ....
}
else {
value2Done = false;
}
else // ERROR
An if statement cannot have two else clauses ... which you have here.
Indeed, the 3rd error message is saying that explicitly.
Related
I'm writing a program about musical chords. I want the user to input A-G or a-g, but it can also be # or - (flat), and also m (minor).
It's running, but if you put in a#m, you get
Enter a musical piano chord name:
A
I need it to keep reading the if statements so that if the input is 3 characters, I can delineate what that char should be.
I haven't added the section on sharps and flats yet.
import java.util.Scanner;
public class Hwk9 {
public static void main(String[] args) {
String chord;
Scanner stdin = new Scanner(System.in);
System.out.println("Enter a musical piano chord name: ");
chord = stdin.nextLine();
String finalChord = validChord(chord);
System.out.println(finalChord);
}
public static String validChord(String input) {
if (input.length() > 3 && input.length() < 1) {
input = "Invalid chord";
}
char note = input.charAt(0);
char capNote = chordCapitalize(note);
if (capNote == 'A') {
input = capNote + "";
}
else if (capNote == 'B') {
input = capNote + "";
}
else if (capNote == 'C') {
input = capNote + "";
}
else if (capNote == 'D') {
input = capNote + "";
}
else if (capNote == 'E') {
input = capNote + "";
}
else if (capNote == 'F') {
input = capNote + "";
}
else if (capNote == 'G') {
input = capNote + "";
}
else {
input = "Invalid chord";
}
if (input.length() == 3) { *<<<<<<This section is not going through*
char minor = input.charAt(2);
if (minor == 'm') {
input = capNote + "" + minor;
}
else {
input = "Invalid chord";
}
}
return input;
}
public static char chordCapitalize(char input) {
String note = input + "";
String caps = note.toUpperCase();
char capNote = caps.charAt(0);
return capNote;
}
}
The problem is you are assigning the capitalized chord back to input in the if blocks. You need to have a local variable for that and not re-assign it to input
If you assign input the value of capNote, length of input will always be one.
String result;
if (capNote == 'A') {
result = capNote + "";
}
else if (capNote == 'B') {
result = capNote + "";
}
//Rest of code
if (input.length() == 3) {
char minor = input.charAt(2);
if (minor == 'm') {
result = capNote + "" + minor;
}
else {
result = "Invalid chord";
}
}
return result;
I seem to be having some issues with my program. I was advised to use a do while loop by my instructor to keep the program running. However, it errors out when I type in an invalid password and restarts. When I input a valid password it only prints "Valid Password" and does not loop. Where have I gone wrong?
import java.util.Scanner;
public class CovenduniteProg5_FIX {
public static void main(String[] args) {
boolean passwordValid = false;
do {
boolean invalidLength = false;
boolean containsRestrictedWord = false;
boolean containsLowerCaseLetter = false;
boolean containsUpperCaseLetter = false;
boolean containsDigit = false;
boolean containsSpecialChar = false;
Scanner stdIn = new Scanner(System.in);
System.out.println("Password Verifier");
System.out.println("\nEnter a password that meets the following rules:\n" +
"\tIs at least 8 characters long\n" +
"\tContains at least 1 lower letter character\n" +
"\tContains at least 1 upper letter character\n" +
"\tContains at least 1 numberic digit\n" +
"\tContains at least 1 special character from the set: !##$%^&*\n" +
"\tDoes not contain the word \"and\" or the word \"the\"\n");
System.out.print("Enter your password: ");
String password = stdIn.nextLine();
for (int i = 0; i < password.length(); i++) {
char ch = password.charAt(i);
if (Character.isUpperCase(ch) && !containsUpperCaseLetter) {
containsUpperCaseLetter = true;
}
if (Character.isLowerCase(ch) && !containsLowerCaseLetter) {
containsLowerCaseLetter = true;
}
if (Character.isDigit(ch) && !containsDigit) {
containsDigit = true;
}
if ((ch == '!' || ch == '#' || ch == '#' || ch == '$' || ch == '%' || ch == '^' || ch == '&' || ch == '*') && !containsSpecialChar) {
containsSpecialChar = true;
}
}
if (password.length() < 8 ) {
invalidLength = true;
}
if (password.contains("and") || password.contains("the")) {
containsRestrictedWord = true;
}
if (invalidLength) {
System.out.println("Invalid: Invalid length");
}
if (containsRestrictedWord) {
System.out.println("Invalid: Contains either the word \"and\" or \"the\".");
}
if (!containsDigit) {
System.out.println("Invalid: Does not contain at least one digit.");
}
if (!containsLowerCaseLetter) {
System.out.println("Invalid: Does not contain at least one lowercase letter.");
}
if (!containsUpperCaseLetter) {
System.out.println("Invalid: Does not contain at least one uppercase letter.");
}
if(!containsSpecialChar) {
System.out.println("Invalid: Does not contain at least one special character.");
}
if (containsSpecialChar && containsUpperCaseLetter && containsLowerCaseLetter && containsDigit && !containsRestrictedWord && !invalidLength)
passwordValid = true;
if (passwordValid)
System.out.print("\nPassword is valid.");
} while (!passwordValid);
passwordValid = false;
while(!passwordValid) {
if (passwordValid)
System.out.print("\nPassword is valid.");
}
}
}
We don't need the second while loop, it's basically an infinite loop. Also, we need to move the "Password Verifier" statements outside the while loop as they needn't be printed multiple times. So, the method will look something like this:
public static void main(String[] args) {
boolean passwordValid = false;
System.out.println("Password Verifier");
System.out.println("\nEnter a password that meets the following rules:\n" + "\tIs at least 8 characters long\n"
+ "\tContains at least 1 lower letter character\n" + "\tContains at least 1 upper letter character\n"
+ "\tContains at least 1 numberic digit\n"
+ "\tContains at least 1 special character from the set: !##$%^&*\n"
+ "\tDoes not contain the word \"and\" or the word \"the\"\n");
do {
boolean invalidLength = false;
boolean containsRestrictedWord = false;
boolean containsLowerCaseLetter = false;
boolean containsUpperCaseLetter = false;
boolean containsDigit = false;
boolean containsSpecialChar = false;
Scanner stdIn = new Scanner(System.in);
System.out.print("Enter your password: ");
String password = stdIn.nextLine();
for (int i = 0; i < password.length(); i++) {
char ch = password.charAt(i);
if (Character.isUpperCase(ch) && !containsUpperCaseLetter) {
containsUpperCaseLetter = true;
}
if (Character.isLowerCase(ch) && !containsLowerCaseLetter) {
containsLowerCaseLetter = true;
}
if (Character.isDigit(ch) && !containsDigit) {
containsDigit = true;
}
if ((ch == '!' || ch == '#' || ch == '#' || ch == '$' || ch == '%' || ch == '^' || ch == '&'
|| ch == '*') && !containsSpecialChar) {
containsSpecialChar = true;
}
}
if (password.length() < 8) {
invalidLength = true;
}
if (password.contains("and") || password.contains("the")) {
containsRestrictedWord = true;
}
if (invalidLength) {
System.out.println("Invalid: Invalid length");
}
if (containsRestrictedWord) {
System.out.println("Invalid: Contains either the word \"and\" or \"the\".");
}
if (!containsDigit) {
System.out.println("Invalid: Does not contain at least one digit.");
}
if (!containsLowerCaseLetter) {
System.out.println("Invalid: Does not contain at least one lowercase letter.");
}
if (!containsUpperCaseLetter) {
System.out.println("Invalid: Does not contain at least one uppercase letter.");
}
if (!containsSpecialChar) {
System.out.println("Invalid: Does not contain at least one special character.");
}
if (containsSpecialChar && containsUpperCaseLetter && containsLowerCaseLetter && containsDigit
&& !containsRestrictedWord && !invalidLength)
passwordValid = true;
if (passwordValid)
System.out.print("\nPassword is valid.");
} while (!passwordValid);
}
You put the last passwordValid = false; outside the do-while when you should just have it once before the loop. And you also do not need the second while(!passwordValid) loop:
boolean passwordValid = false; //← only here
do {
boolean invalidLength = false;
boolean containsRestrictedWord = false;
boolean containsLowerCaseLetter = false;
boolean containsUpperCaseLetter = false;
boolean containsDigit = false;
boolean containsSpecialChar = false;
Scanner stdIn = new Scanner(System.in);
/*
...
*/
if (/*All sub-conditions met*/)
passwordValid = true;
if (passwordValid)
System.out.print("\nPassword is valid.");
}
while (!passwordValid);
//passwordValid = false; ← remove this
//no need for while or if statment, because you can only reach this code if passwordValid = true
System.out.print("\nPassword is valid.");
The following code will do what you ask. Some things to consider :
The second while loop is infinite.
Declare the scanner outside the do loops...creating one everytime could cause issues and you only need to declare and create it once.
Use two do loops, the outer loop has an infinite condition so it will continue forever...you can re-write to terminate in some fashion.
the outer loop displays your menu.
the inner loop does all you scanner/input and validation and determination.
Hope this helps
// CovenduniteProg5_FIX
public static void main(String[] args) {
boolean passwordValid = false;
Scanner stdIn = new Scanner(System.in);
do {
System.out.println("Password Verifier");
System.out.println("\nEnter a password that meets the following rules:\n"
+ "\tIs at least 8 characters long\n" + "\tContains at least 1 lower letter character\n"
+ "\tContains at least 1 upper letter character\n" + "\tContains at least 1 numberic digit\n"
+ "\tContains at least 1 special character from the set: !##$%^&*\n"
+ "\tDoes not contain the word \"and\" or the word \"the\"\n");
System.out.print("Enter your password: ");
do {
boolean invalidLength = false;
boolean containsRestrictedWord = false;
boolean containsLowerCaseLetter = false;
boolean containsUpperCaseLetter = false;
boolean containsDigit = false;
boolean containsSpecialChar = false;
try {
String password = stdIn.nextLine();
for (int i = 0; i < password.length(); i++) {
char ch = password.charAt(i);
if (Character.isUpperCase(ch) && !containsUpperCaseLetter) {
containsUpperCaseLetter = true;
}
if (Character.isLowerCase(ch) && !containsLowerCaseLetter) {
containsLowerCaseLetter = true;
}
if (Character.isDigit(ch) && !containsDigit) {
containsDigit = true;
}
if ((ch == '!' || ch == '#' || ch == '#' || ch == '$' || ch == '%' || ch == '^' || ch == '&'
|| ch == '*') && !containsSpecialChar) {
containsSpecialChar = true;
}
}
if (password.length() < 8) {
invalidLength = true;
}
if (password.contains("and") || password.contains("the")) {
containsRestrictedWord = true;
}
if (invalidLength) {
System.out.println("Invalid: Invalid length");
}
if (containsRestrictedWord) {
System.out.println("Invalid: Contains either the word \"and\" or \"the\".");
}
if (!containsDigit) {
System.out.println("Invalid: Does not contain at least one digit.");
}
if (!containsLowerCaseLetter) {
System.out.println("Invalid: Does not contain at least one lowercase letter.");
}
if (!containsUpperCaseLetter) {
System.out.println("Invalid: Does not contain at least one uppercase letter.");
}
if (!containsSpecialChar) {
System.out.println("Invalid: Does not contain at least one special character.");
}
if (containsSpecialChar && containsUpperCaseLetter && containsLowerCaseLetter && containsDigit
&& !containsRestrictedWord && !invalidLength)
passwordValid = true;
if (passwordValid)
System.out.print("\nPassword is valid.");
}
catch ( Exception ltheXcp ) {
ltheXcp.printStackTrace();
}
} while (!passwordValid);
passwordValid = false;
} while ( 1 != 2 );
// while (!passwordValid) {
// if (passwordValid)
// System.out.print("\nPassword is valid.");
// }
}
I am writing a program that is supposed to calculate the Flesch index of a passage or string and tell the minimum education level required to comprehend.
What is supposed to happen is a person types in a string that the want to be calculated and the program is supposed to count the number of words and count the number of sentences as well as go through each word and calculate how many syllables there are in the word and add that to the total syllable counter. The way to calculate syllables is to count the number of adjacent vowels in a word, so "Computer" for instance has the vowels o, u, and e so 3 syllables. But, if the word ends in the letter e, subtract 1 from the total syllable count so, "Passage" has a, a, and e, but since the e is at the end, the syllable count is 2.
Here is what I got so far:
// Import scanner to get input from the user
import java.util.Scanner;
public class Flesch
{
public static void main (String [] args)
{
public static final double BASE = 206.835;
public static final double WORD_LENGTH_PENALTY = 84.6;
public static final double SENTENCE_LENGTH_PENALTY = 1.015;
Scanner input = new Scanner (System.in);
// Declare variables for syllables and words
int totalWords = 0;
int totalSyllables = 0;
// Prompt user for a passage of text
System.out.println ("Please enter some text:");
String passage = input.nextLine();
// Words
for (int i = 0; i < passage.length(); i++)
{
if (passage.charAt(i) == ' ') {
totalWords++;
}
else if (passage.charAt(i) == '.') {
totalWords++;
}
else if (passage.charAt(i) == ':') {
totalWords++;
}
else if (passage.charAt(i) == ';') {
totalWords++;
}
else if (passage.charAt(i) == '?') {
totalWords++;
}
else if (passage.charAt(i) == '!') {
totalWords++;
}
}
System.out.println ("There are " + totalWords + " words.");
char syllableList [] = {'a', 'e', 'i', 'o', 'u', 'y'};
// Syllables
for (int k = 0; k < syllableList.length; k++)
{
for (int i = 0; i < passage.length(); i++)
{
if (passage.charAt(i) == syllableList[k]) {
totalSyllables = totalSyllables + 1;
}
if (lastChar(passage) == 'E' || lastChar(passage) == 'e') {
totalSyllables = totalSyllables - 1;
} else {
break;
}
}
}
System.out.println ("There are " + totalSyllables + " syllables.");
input.close();
public static char lastChar (String aWord)
{
char aChar = aWord.charAt(aWord.length() - 2);
System.out.print (aChar);
return aChar;
}
/** Return true if the last character in the parameter word is
* a period, question mark, or exclaimation point, and false
* otherwise
**/
public static boolean sentenceEnd (String word)
{
if (lastChar(passage) == '.') {
return true;
} else if (lastChar(passage) == '?') {
return true;
} else if (lastChar(passage) == '!') {
return true;
} else {
return false;
}
}
double fleschIndex = BASE - WORD_LENGTH_PENALTY * (totalSyllables / totalWords) - SENTENCE_LENGTH_PENALTY * (totalWords / totalSentences);
if (fleschIndex > 100) {
educationLevel = "4th grader";
} else if (fleschIndex <= 100) {
educationLevel = "5th grader";
} else if (fleschIndex <= 90) {
educationLevel = "6th grader";
} else if (fleschIndex <= 80) {
educationLevel = "7th grader";
} else if (fleschIndex <= 70) {
educationLevel = "8th grader";
} else if (fleschIndex <= 60) {
educationLevel = "9th grader";
} else if (fleschIndex <= 50) {
educationLevel = "high school graduate";
} else if (fleschIndex <= 30) {
educationLevel = "college graduate";
} else if (fleschIndex < 0) {
educationLevel = "law school graduate";
}
System.out.println ("The Flesch idex is " + fleschIndex + ".");
System.out.println ("The text can be understood by a " + educationLevel + ".");
}
}
I keep getting some weird error messages telling me to put semi-colons around the boolean declarations which makes no sense to me.
It looks to me like you mixed up your methods.
The methods sentenceEnd and lastChar are inside the main-method. This is not allowed.
They have to be outside of the main-method but inside the Flesch-Class.
Wondering how to exit if total phrase is guessed and why my vowels, spaces and consonants are not counting? Most of progam runs great just cant figure out how to exit without saying "n" to question. I am returning values for counters, don't understand?
import java.util.Scanner;
public class Prog09
{
public static void main(String[] args)
{
Scanner stdIn = new Scanner(System.in);
// Initializes all string variables
String sPhrase;
String answer;
// Initializes all int variables
int vowels = 0;
int consonants = 0;
int spaces = 0;
// Initializes all char variables
char cGuess = 0;
char vGuess = 0;
boolean valid = false;
// Asks user to enter if they want to play
System.out.print("Do you want to play a game? [y/n] ");
answer = stdIn.nextLine();
// Asks user to enter the phrase
System.out.print("Please enter the phrase to guess at : ");
sPhrase = stdIn.nextLine();
// Checks if user wants to play
while (answer.equalsIgnoreCase("y"))
{
char[] phrase = new char[sPhrase.length()];
char[] tmpArr = new char[sPhrase.length()];
for(int i = 0; i < sPhrase.length();i++)
{
tmpArr[i] = sPhrase.charAt(i);
phrase[i] = sPhrase.charAt(i);
}
// Runs methods and main body of program
initTemplateArray(sPhrase, tmpArr, spaces);
printHeader();
printTemplateArray(tmpArr);
System.out.println("");
System.out.println("");
while (answer.equalsIgnoreCase("y"))
{
//getConsonant(stdIn, cGuess);
cGuess = getConsonant(stdIn, cGuess);
vGuess = getVowel(stdIn, vGuess);
isVowel(vGuess, valid);
updateTemplateArray(tmpArr, sPhrase, cGuess, vGuess, consonants, vowels);
printHeader();
printTemplateArray(tmpArr);
System.out.println("");
System.out.println("");
stdIn.nextLine();
System.out.print("Do you want to try again? [y/n]: ");
answer = stdIn.next();
vGuess = 0;
cGuess = 0;
}
}
// Prints results
System.out.println("The common phrase contained: Spaces: " + spaces + " Consonants: " + consonants + " Vowels: " + vowels);
stdIn.close();
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Methods for program
public static int initTemplateArray(String sPhrase, char [] tmpArr, int spaces)
{
for (int i = 0; i < sPhrase.length(); i++)
{
if (sPhrase.charAt(i) == ' ')
{
spaces++;
tmpArr[i] = ' ';
}
if (!(sPhrase.charAt(i) == ' '))
{
tmpArr[i] = '?';
}
}
return spaces;
}
public static void printTemplateArray(char [] tmpArr)
{
for (int i = 0; i < tmpArr.length; i++)
{
System.out.print(tmpArr[i]);
}
System.out.println();
}
public static boolean isVowel(char c, boolean valid)
{
if(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
{
return valid = true;
}
else
{
return valid = false;
}
}
public static char getConsonant(Scanner stdIn, char cGuess)
{
while(cGuess == 'a' || cGuess == 'e' || cGuess == 'i' || cGuess == 'o' || cGuess == 'u'|| cGuess == 0)
{
System.out.print("Enter a lowercase consonant guess : ");
String myGuess = stdIn.next();
cGuess = myGuess.charAt(0);
}
return cGuess;
}
public static char getVowel(Scanner stdIn, char vGuess)
{
while(!(vGuess == 'a' || vGuess == 'e' || vGuess == 'i' || vGuess == 'o' || vGuess == 'u'))
{
System.out.print("Enter a lowercase vowel guess : ");
String newGuess = stdIn.next();
vGuess = newGuess.charAt(0);
}
return vGuess;
}
public static int updateTemplateArray(char [] tmpArr, String sPhrase, char cGuess, char vGuess, int consonants, int vowels)
{
vowels = 0;
consonants = 0;
for (int i = 0; i < tmpArr.length; i++)
{
if (cGuess == sPhrase.charAt(i))
{
tmpArr[i] = sPhrase.charAt(i);
consonants++;
}
if (vGuess == sPhrase.charAt(i))
{
tmpArr[i] = sPhrase.charAt(i);
vowels++;
}
}
return consonants & vowels;
}
public static void printHeader()
{
System.out.println("");
System.out.println(" Common Phrase");
System.out.println("---------------");
}
}
Java passes Ints by value instead of by reference, this means that updateTemplateArray doesn't modify the values of main's vowels, consonants or spaces. To fix this you could:
Make these variables global by definining them outside the scope of the main method. You would have to change the name of the parameters in the updateTemplateArray method to prevent shadowing.
Break updateTemplateArray into separate functions to count each of the vowels, consonants or spaces, and have them return the count of each. You would then call something like: vowels = countVowels(sPhrase); to populate the variables.
With the current setup, it will exit whenever answer stops being equal to 'y' Changing the value of answer at any time will exit the loop.
I'm trying to code an infix to postfix calculator. So far what I have got after inserting infix expression is either a prefix expression or the code keeps on running and does nothing. Here is what I've made:
import java.util.Scanner;
import java.util.Stack;
public class postFix {
public static StringBuilder postFixExp = new StringBuilder();
public static int priority(char ch){
if(ch == '^') return 3;
if(ch == '/' || ch == '*') return 2;
if(ch == '+' || ch == '-') return 1;
return 0;
}
public static String postfix(){
Stack<Character> st = new Stack<Character>();
Scanner scan = new Scanner(System.in);
System.out.println("Sisestage infiks: ");
String sone = scan.next();
scan.close();
for(int i = 0; i<sone.length(); i++){
char ch = sone.charAt(i);
switch(ch){
case'+':
case'-':
case'*':
case'/':
postFixExp.append(' ');
st.push(ch);
break;
// case' ':
case'(':
st.push(ch);
break;
case')':
while(st.peek() != '('){
postFixExp = postFixExp.append(st.pop());
}
st.pop();
break;
default:
while(!st.isEmpty() && st.peek() != '(' && priority(ch) <= priority(st.peek()))
{
postFixExp = postFixExp.append(st.pop());
}
st.push(ch);
break;
}
}
while(!st.isEmpty()){
postFixExp = postFixExp.append(st.pop());
}
return postFixExp.toString();
}
public static void main(String[] args) {
System.out.println(postfix());
}
}
I used this pseudocode.
What's wrong with my code?
If I input :
1+2
It returns
+12
I would like to see
1 2 + or 12+