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+
Related
this is my last resort. Will someone help me with my program?
The program is to convert infix to postfix, the issue is it won't give me an answer with decimal. I know i need to use double, but i don't know where to insert it.
here is my code
import java.util.*;
class Stack
{
int capacity = 10;
char arr []=new char[capacity];
int top = -1;
boolean isEmpty()
{
if(top==-1){
return true;
}
else {
return false;
}
}
void push(char c)
{
top++;
if (top <= capacity-1)
{
arr[top]= c;
}
else if (top > capacity-1)
{
System.out.println("Overflow"); //Stack is ful
System.exit(0);
}
}
char pop ()
{
if (isEmpty()==true){
System.out.print("Underflow");
System.exit(0);
}
return arr[top--];
}
char peek()
{
return arr[top];
}
}
public class Operations
{
static Stack s = new Stack ();
static int precedence(char c){
switch (c){
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '^':
return 3;
}
return -1;
}
public static String Conversion(String val){
String result = "";
for (int i = 0; i <val.length() ; i++) {
char c = val.charAt(i);
if(precedence(c)>0){
while(s.isEmpty()==false && precedence(s.peek())>=precedence(c)){
result += s.pop();
}
s.push(c);
}else if(c==')'){
char x = s.pop();
while(x!='('){
result += x;
x = s.pop();
}
}else if(c=='('){
s.push(c);
}else{
result += c;
}
if (i+1 >= val.length() || !Character.isDigit(val.charAt(i+1)))
result += ' ';
}
while (!s.isEmpty())
result = result + s.pop();
return result;
}
public static double Result(String Postfix)
{
for(int i=0; i < Postfix.length(); i++)
{
char ch = Postfix.charAt(i);
//check if it is a space (separator)
if(ch==' ')
continue;
if (Character.isDigit(ch)){
double num = 0;
while(Character.isDigit(ch)) {
num = num*10 + (ch-'0');
i++;
ch = Postfix.charAt(i);
}
i--;
s.push((char)(num));
}
else
{
double value1 = s.pop();
double value2 = s.pop();
switch(ch) //evaluating the expression
{
case '+':
s.push((char)(value2 + value1));
break;
case '-':
s.push((char)(value2 - value1));
break;
case '*':
s.push((char)(value2*value1));
break;
case '/':
if(value1==0){
System.out.print("Cannot divide by zero");
System.exit(0);
}
else
s.push((char)(value2/value1));
break;
}
}
}
return s.pop();
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter an infix expression: ");
String val = sc.next();
String Postfix = Conversion(val);
System.out.println("Postfix expression is: "+(Postfix.replaceAll("\\s+","")));
System.out.println("Result of the evaluation is: " + Result(Postfix));
}
}
i am not confident with the codes if it's correct. but any enlighten is welcome.
and perhaps can u help me with the loop? so i won't start to re-run the program everytime i input from the keyboard, big thanks seniors
If a user enters a string: hello there
it should output
Hello has 2 vowels
There has 3 consonants.
I know this is a fairly simple code but I am getting too many ideas and getting confused.
I need a to make sure I have 2 methods for numberofVowels and capitalizeWord and both returns a result
I am getting an error and I am still trying to figure out to capitalize after I got counting vowels work
import java.util.Scanner;
public class Hwk9
{
public static void main (String args[])
{
Scanner stdin = new Scanner(System.in);
String string1;
System.out.println("Enter a string");
string1 = stdin.nextLine();
string1 = string1.toLowerCase();
}
public static int numberVowels(String string1)
{
int count = 0;
int vowels = 0;
int consonants = 0;
for (int i = 0; i < string1.length(); i++)
{
char ch = string1.charAt(i);
if (ch == 'a' || ch == 'e' || ch == 'i' ||
ch == 'o' || ch == 'u')
{
vowels++;
}
else
{
consonants++;
}
}
}
}
Here is a simpler way of doing this, hope this helps:
public static void checkVowels(String s){
System.out.println("Vowel Count: " + (s.length() - s.toLowerCase().replaceAll("a|e|i|o|u|", "").length()));
//Also eliminating spaces, if any for the consonant count
System.out.println("Consonant Count: " + (s.toLowerCase().replaceAll("a|e|i|o| |u", "").length()));
}
Made something like this hope this helps, this will give vowels,consonants of each word
public static void main (String args[])
{
Scanner stdin = new Scanner(System.in);
String string1;
System.out.println("Enter a string");
string1 = stdin.nextLine();
string1 = string1.toLowerCase();
int count = 0;
int vowels = 0;
int consonants = 0;
for (String retval: string1.split(" ")){
for (int i = 0; i < retval.length(); i++)
{
char ch = retval.charAt(i);
if (ch == 'a' || ch == 'e' || ch == 'i' ||
ch == 'o' || ch == 'u')
{
vowels++;
}
else
{
consonants++;
}
}
System.out.println(retval.substring(0, 1).toUpperCase() + retval.substring(1)+" has "+vowels+" vowels and "+consonants+" cosonants");
vowels=0;
consonants=0;
}
}
My code without scanner and maybe not very simple, but:
public class Main{
public static void main(String[] args) {
String test = "qwertyYVTA";
test = test.trim();
int vowels = 0;
int consonants = 0;
Pattern patternVow = Pattern.compile("[eyuioa]", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
Matcher matcherVow = patternVow.matcher(test);
while (matcherVow.find()) {
vowels++;
}
Pattern patternCons = Pattern.compile("[wrtpsdfghjklzxcvbnm]", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
Matcher matcherCons = patternCons.matcher(test);
while (matcherCons.find()) {
consonants++;
}
System.out.println("Vowels in test String is " + vowels);
System.out.println("Consonants in test String is " + consonants);
}
}
following code will give you vowel and Constonent count
static String VOWEL_GROUP = "AEIOUaeiou";
static String testString = "AAAASHMAIOUAXCCDIOUGGGGA"; // say this is your text
public static void main(String[] args) {
int vovelCount = 0;
int consonantCount = 0;
for (int j = testString.length() - 1; j >= 0; j--) {//outer loop
for (int i = 0; i < VOWEL_GROUP.length(); i++) { //inner loop
if (VOWEL_GROUP.charAt(i) == testString.charAt(j)) {
vovelCount++; //vowel count in text
break;
}else{
consonantCount ++;
}
}
}
System.out.println(vovelCount+" "+ consonantCount);
}
I suggest you;
to create a final vowels array,
define a bool isVowel(char c) function and use it in your if condition.
Here is the simple code for counting the number of vowels using recursion
public static int vowels(String s){
int count =0;
char c;
if(s.length()==0){
return 0;
}
else{
c =s.charAt(0);
if(c=='a'||c=='e'||c=='i'||c=='o'||c=='u'){
count++;
}
return count+vowels(s.substring(1));
}
}
This looks way simple than above answers. It gets the input, converts it to lowercase then to an array of characters. A simple for loop will do the trick onwards.
import java.util.*;
public class FindVowelsConsonents {
public static void main(String[] args) {
int vowels_count = 0;
int consonents_count = 0;
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
String str2 = str.toLowerCase();
char[] chr = str2.toCharArray();
for(int i=0;i<chr.length;i++){
if(chr[i] == 'a' || chr[i]== 'e' || chr[i] == 'i' ||
chr[i] == 'o' || chr[i] == 'u')
vowels_count++;
else
consonents_count++;
}
System.out.println(vowels_count+ " "+consonents_count);
sc.close();
}
}
As far as I am concerned you can use StringTokenizer:
String text = "dupalo twoja mama";
StringTokenizer tokenizer = new StringTokenizer(text,"aeiuo",false);
int vowels = tokenizer.countTokens();
System.out.println(vowels);
In this case of "text" it will print out 7.
import java.util.Scanner;
//don't use space in between the input string;
class StrRev {
static String Vowels ="aeiouAEIOU";
public static void main(String[] args){
#SuppressWarnings("resource")
Scanner name = new Scanner(System.in);
String nm = name.nextLine();
System.out.println();
int vowel=0;
int consonant=0;
for(int i=0;i<nm.length();i++){
for(int j=0;j<Vowels.length();j++){
if(Vowels.charAt(j)==nm.charAt(i)){
vowel++;
break;
}
}
}
consonant = nm.length()-vowel;
System.out.println("no of Vowels :"+vowel+"\nno of consonant :"+consonant);
}
}
import java.util.Scanner;
public class Tester {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
char c = 'x';
Queue q1 = new Queue();
Stack s1 = new Stack();
s1.push('#');
Queue q2 = new Queue();
q1.enqueue('#');
while (c != '#') {
System.out.println("Enter a character: ");
c = input.next().charAt(0);
q1.enqueue(c);
}
while (c != '#') {
c = (char) q1.dequeue();
if (!operator(c)) {
q2.enqueue(c);
}
}
q1.print(q1);
System.out.println();
q2.print(q2);
}
public static boolean operator(char c) {
char op = 'x';
boolean isOperator;
switch (op) {
case '*':
case '/':
case '^':
case '+':
case '-':
isOperator = true;
break;
default:
isOperator = false;
break;
}
return isOperator;
}
}
The goal for this is for me to enter some characters into queue q1, then while the character isn't a #, it should dequeue from q1 as long as the character isn't an operator and enqueue it into q2.
However, none of my operators from q1 are getting dequeued and enqueued into q2 which should be happening from lines 20-23.
Your problem is in the variable c that is not resetted before doing the second while.
If you go out the first 'while' loop, c will be setted to '#' and you will not go in the second loop.
Try this:
while (c != '#') {
System.out.println("Enter a character: ");
c = input.next().charAt(0);
q1.enqueue(c);
}
c = 'a'
while (c != '#') {
c = (char) q1.dequeue();
if (!operator(c)) {
q2.enqueue(c);
}
}
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.
If a user enters a string: hello there
it should output
Hello has 2 vowels
There has 3 consonants.
I know this is a fairly simple code but I am getting too many ideas and getting confused.
I need a to make sure I have 2 methods for numberofVowels and capitalizeWord and both returns a result
I am getting an error and I am still trying to figure out to capitalize after I got counting vowels work
import java.util.Scanner;
public class Hwk9
{
public static void main (String args[])
{
Scanner stdin = new Scanner(System.in);
String string1;
System.out.println("Enter a string");
string1 = stdin.nextLine();
string1 = string1.toLowerCase();
}
public static int numberVowels(String string1)
{
int count = 0;
int vowels = 0;
int consonants = 0;
for (int i = 0; i < string1.length(); i++)
{
char ch = string1.charAt(i);
if (ch == 'a' || ch == 'e' || ch == 'i' ||
ch == 'o' || ch == 'u')
{
vowels++;
}
else
{
consonants++;
}
}
}
}
Here is a simpler way of doing this, hope this helps:
public static void checkVowels(String s){
System.out.println("Vowel Count: " + (s.length() - s.toLowerCase().replaceAll("a|e|i|o|u|", "").length()));
//Also eliminating spaces, if any for the consonant count
System.out.println("Consonant Count: " + (s.toLowerCase().replaceAll("a|e|i|o| |u", "").length()));
}
Made something like this hope this helps, this will give vowels,consonants of each word
public static void main (String args[])
{
Scanner stdin = new Scanner(System.in);
String string1;
System.out.println("Enter a string");
string1 = stdin.nextLine();
string1 = string1.toLowerCase();
int count = 0;
int vowels = 0;
int consonants = 0;
for (String retval: string1.split(" ")){
for (int i = 0; i < retval.length(); i++)
{
char ch = retval.charAt(i);
if (ch == 'a' || ch == 'e' || ch == 'i' ||
ch == 'o' || ch == 'u')
{
vowels++;
}
else
{
consonants++;
}
}
System.out.println(retval.substring(0, 1).toUpperCase() + retval.substring(1)+" has "+vowels+" vowels and "+consonants+" cosonants");
vowels=0;
consonants=0;
}
}
My code without scanner and maybe not very simple, but:
public class Main{
public static void main(String[] args) {
String test = "qwertyYVTA";
test = test.trim();
int vowels = 0;
int consonants = 0;
Pattern patternVow = Pattern.compile("[eyuioa]", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
Matcher matcherVow = patternVow.matcher(test);
while (matcherVow.find()) {
vowels++;
}
Pattern patternCons = Pattern.compile("[wrtpsdfghjklzxcvbnm]", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
Matcher matcherCons = patternCons.matcher(test);
while (matcherCons.find()) {
consonants++;
}
System.out.println("Vowels in test String is " + vowels);
System.out.println("Consonants in test String is " + consonants);
}
}
following code will give you vowel and Constonent count
static String VOWEL_GROUP = "AEIOUaeiou";
static String testString = "AAAASHMAIOUAXCCDIOUGGGGA"; // say this is your text
public static void main(String[] args) {
int vovelCount = 0;
int consonantCount = 0;
for (int j = testString.length() - 1; j >= 0; j--) {//outer loop
for (int i = 0; i < VOWEL_GROUP.length(); i++) { //inner loop
if (VOWEL_GROUP.charAt(i) == testString.charAt(j)) {
vovelCount++; //vowel count in text
break;
}else{
consonantCount ++;
}
}
}
System.out.println(vovelCount+" "+ consonantCount);
}
I suggest you;
to create a final vowels array,
define a bool isVowel(char c) function and use it in your if condition.
Here is the simple code for counting the number of vowels using recursion
public static int vowels(String s){
int count =0;
char c;
if(s.length()==0){
return 0;
}
else{
c =s.charAt(0);
if(c=='a'||c=='e'||c=='i'||c=='o'||c=='u'){
count++;
}
return count+vowels(s.substring(1));
}
}
This looks way simple than above answers. It gets the input, converts it to lowercase then to an array of characters. A simple for loop will do the trick onwards.
import java.util.*;
public class FindVowelsConsonents {
public static void main(String[] args) {
int vowels_count = 0;
int consonents_count = 0;
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
String str2 = str.toLowerCase();
char[] chr = str2.toCharArray();
for(int i=0;i<chr.length;i++){
if(chr[i] == 'a' || chr[i]== 'e' || chr[i] == 'i' ||
chr[i] == 'o' || chr[i] == 'u')
vowels_count++;
else
consonents_count++;
}
System.out.println(vowels_count+ " "+consonents_count);
sc.close();
}
}
As far as I am concerned you can use StringTokenizer:
String text = "dupalo twoja mama";
StringTokenizer tokenizer = new StringTokenizer(text,"aeiuo",false);
int vowels = tokenizer.countTokens();
System.out.println(vowels);
In this case of "text" it will print out 7.
import java.util.Scanner;
//don't use space in between the input string;
class StrRev {
static String Vowels ="aeiouAEIOU";
public static void main(String[] args){
#SuppressWarnings("resource")
Scanner name = new Scanner(System.in);
String nm = name.nextLine();
System.out.println();
int vowel=0;
int consonant=0;
for(int i=0;i<nm.length();i++){
for(int j=0;j<Vowels.length();j++){
if(Vowels.charAt(j)==nm.charAt(i)){
vowel++;
break;
}
}
}
consonant = nm.length()-vowel;
System.out.println("no of Vowels :"+vowel+"\nno of consonant :"+consonant);
}
}