Use existing Method instead of new Parameter - java

I'm trying to finish this project and I can't figure how to use my existing method in my other method. I want to get rid of VOWELS, which is defined as a field the class, and I just want to use the method isVowel which returns a boolean after you type in a Char.
This is what I have:
public class StringAndIO {
private static Scanner v;
static final String VOWELS = "AaEeIiOoUuÄäÖöÜü";
public static boolean isVowel(char c) {
if (c == 'a' || c == 'A' || c == 'e' || c == 'E' || c == 'i' || c == 'I' || c == 'o' || c == 'O' || c == 'u'
|| c == 'U' || c == 'ä' || c == 'Ä' || c == 'ö' || c == 'Ö' || c == 'ü' || c == 'Ü') {
return true;
} else {
return false;
}
}
public static String toPigLatin(String text) {
String ret = "";
String vowelbuf = "";
for (int i = 0; i < text.length(); ++i) {
char x = text.charAt(i);
if (VOWELS.indexOf(x) != -1) {
vowelbuf += x;
} else {
if (vowelbuf.length() > 0) {
ret += vowelbuf + "b" + vowelbuf + x;
vowelbuf = "";
} else {
ret += x;
}
}
}
if (vowelbuf.length() > 0) {
ret += vowelbuf + "b" + vowelbuf;
}
return ret;
}
/**
* only there for testing purpose
*/
public static void main(String[] args) {
v = new Scanner(System.in);
System.out.println("Enter a Char!");
char c = v.next().charAt(0);
System.out.println(isVowel(c));
String s = "Meine Mutter ißt gerne Fisch";
System.out.println(s);
System.out.println(toPigLatin(s));
System.out.println();
}
}

THis is how to use your isVowel(x) method inside the other method
public static String toPigLatin(String text) {
String ret = "";
String vowelbuf = "";
for (int i = 0; i < text.length(); ++i) {
char x = text.charAt(i);
if (isVowel(x)) {
vowelbuf += x;
} else {
if (vowelbuf.length() > 0) {
ret += vowelbuf + "b" + vowelbuf + x;
vowelbuf = "";
} else {
ret += x;
}
}
}
if (vowelbuf.length() > 0) {
ret += vowelbuf + "b" + vowelbuf;
}
return ret;
}

Related

String Index Exception

I was trying to convert an expression from infix form to postfix form.I used String a, p , s for stack, postfix result expression, input expression respectively.
Every time I am getting this error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: -1 at
java.lang.String.charAt(String.java:658) at
javaapplication4.A.conversion(A.java:50) at
javaapplication4.A.main(A.java:83)
Please help me how can I solve it.
Here is my code:
import java.util.Scanner;
public class A {
String a="(", s = "", p = "";
int i, n = 1, top = 0, pp = 0;
void push(char ch) {
a = a + ch;
top = n;
n++;
}
void pop() {
n--;
top--;
}
int prio(char ch) {
int f = -1;
if (ch == '(') {
f = 0;
} else if (ch == '+' || ch == '-') {
f = 1;
} else if (ch == '*' || ch == '/' || ch == '%') {
f = 2;
} else if (ch == '^') {
f = 3;
}
return f;
}
void conversion() {
System.out.print("Enter infix form: ");
Scanner sd = new Scanner(System.in);
s = sd.nextLine();
//System.out.println(s);
int t, j, sz;
sz = s.length();
for (i = 0; i < sz; i++) {
if (s.charAt(i) >= '0' && s.charAt(i) <= '9') {
p = p + s.charAt(i);
pp++;
} else if (s.charAt(i) == '(') {
push('(');
} else if (s.charAt(i) == '-' || s.charAt(i) == '+' || s.charAt(i) == '*' || s.charAt(i) == '/' || s.charAt(i) == '%' || s.charAt(i) == '^') {
j = prio(s.charAt(i));
t = prio(a.charAt(top));
//System.out.println(t+" "+j);
while (j <= t) {
p = p + a.charAt(top);
pp++;
pop();
t = prio(a.charAt(top));
}
push(s.charAt(i));
} else if (s.charAt(i) == ')') {
while (a.charAt(top) != '(') {
p = p + a.charAt(top);
pp++;
pop();
}
pop();
}
}
while (a.charAt(top) != '(') {
p = p + a.charAt(top);
pp++;
pop();
}
pop();
}
void postfix() {
System.out.print("postfix form is: ");
System.out.println(p);
}
public static void main(String args[]) {
A h = new A();
h.conversion();
h.postfix();
//System.out.println(h.a);
//System.out.println(h.s);
}
}
Can you confirm if the error is here?
while (a.charAt(top) != '(')
Inside the loop you continuously pop(), which decrements from top, which has the risk of going negative if a match is never found. Even if the error is not here, it should check for that condition.
You may have made an extra pop() definition. Can you check this?

I need to create a program that will read a text file, figure out in the parentheses are valid, and solve the equation

This is my assignment on number 6:
And this is what I have so far. It's not working properly and I am not sure why. Any help would be greatly appreciated. I showed what error I get at the bottom of the code. I'm not sure how to fix it and where to go from here.
import java.util.Arrays;
public class st {
public static void main(String[] args) {
String aa = "8 + (2+2)";
Init init = new Init(aa);
}
}
public final class Init {
public int top = 1;
Integer[] stack = new Integer[10];
String[] queue = new String[10];
int number, x, y, z, op, front, rear;
int finalValue;
int CurrValue;
String queueOperand;
Character s;
public Init(String s) {
ValidateEquation(s);
int finalVal = postFix(s);
System.out.printf("The answer is " + finalVal + "\n");
}
void ValidateEquation(String s) {
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '(') {
push(c);
} else if (c == ')') {
if (isStackEmpty()) {
System.out.printf("Error: Too many ')'");
System.exit(0);
} else {
int closeParen = pop();
}
}
}
}
public int postFix(String s) {
int CurrentCalculation;
int i = 0;
while (i < s.length()) {
char c = s.charAt(i);
if ((int) c > 47 && (int) c < 58) {
int numVal = Character.getNumericValue(c);
push(numVal);
} else if ((int) c > 41 && (int) c < 48) {
String StrVal = Character.toString(c);
pushQ(StrVal);
}
if (c == '(' || c == ')' || i == s.length()-1) {
String newString = "";
for (Integer stack1 : stack) {
/* iterate through the stack */
if (stack1 != null) {
newString = newString + stack1 + " ";
}
}
for (String queue1 : queue) {
/* iterate through the queue */
if (queue1 != null) {
newString = newString + queue1 + " ";
queueOperand = queue1;
}
}
if (newString.length() > 2) {
int CurrValue = calculateEquation(newString);
if ("+".equals(queueOperand)) {
finalValue = finalValue + CurrValue;
} else if ("-".equals(queueOperand)) {
finalValue = finalValue - CurrValue;
} else if ("*".equals(queueOperand)) {
finalValue = finalValue * CurrValue;
} else if ("/".equals(queueOperand)) {
finalValue = finalValue / CurrValue;
}
popAll();
}
}
i++;
}
return finalValue;
}
int calculateEquation(String s) {
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if ((int) c > 47 && (int) c < 58) {
int numVal = Character.getNumericValue(c);
push(numVal);
}
if ((int)c > 41 && (int)c < 48) {
if (s.length() <= 4) {
x = pop();
if (c == '*' || c == '/') {
y = 1;
} else {
y = 0;
}
} else {
x = pop();
y = pop();
}
System.out.println("\n" + x + " " + y + " " + c);
if (c == '+') {
z = x + y;
} else if (c == '-') {
z = x - y;
} else if (c == '*') {
z = x * y;
} else if (c == '/') {
z = x / y;
}
}
}
return z;
}
void push(int x) {
top = top + 1;
/* Increment stack pointer. */
stack[top] = x;
/* Place x on top of stack. */
}
void pushQ(String x) {
rear = rear + 1;
/* Increment stack pointer. */
queue[rear] = x;
/* Place x on top of stack. */
}
int pop() {
int x;
x = stack[top];
/* Retrieve item from top of stack. */
top = top - 1;
/* Decrement stack. */
return x;
}
void popAll() {
Arrays.fill(stack, null);
Arrays.fill(queue, null);
}
boolean isStackEmpty() {
boolean empty;
empty = false;
if (top == -1) {
/* If top = -1, that indicates an empty stack. */
empty = true;
}
return empty;
}
}
This is the error I get:
"/st.java:12: error: class Init is public, should be declared in a file named Init.java
public final class Init {"
You should put each public class in separate file and file name must be class name.

Can someone explain how this code works? (StringBuffer & StringTokenizer)

I'm searching for ways on how to compute mathematical expressions that can compute inputs with string such as sin(90) and 10E8, until I saw these codes which I can't fully understand how these works. I want to make these as a basis because I want to improve my MDAS calculator.
I am having difficulty on understanding these codes. I'm not familiar with StringBuffer, StringTokenizer, Math.ceil, ans += mul(); , ( b.toString(), "\t" ); , but I have idea on how the trigonometric function & MDAS operation works.
Update: I've understand what is StringTokenizer but what is its relation with StringBuffer?
import java.util.*;
public class Expression {
String s, x;
double term() {
double ans = 0;
StringBuffer temp = new StringBuffer();
while (s.length() > 0 && Character.isDigit(s.charAt(0))) {
temp.append(Integer.parseInt("" + s.charAt(0)));
s = s.substring(1);
}
if (s.length() > 0 && s.charAt(0) == '.') {
temp.append('.');
s = s.substring(1);
while (s.length() > 0 && Character.isDigit(s.charAt(0))) {
temp.append(Integer.parseInt("" + s.charAt(0)));
s = s.substring(1);
}
}
if (s.length() > 0 && (s.charAt(0) == 'e' || s.charAt(0) == 'E')) {
temp.append('e');
s = s.substring(1);
temp.append(s.charAt(0));
s = s.substring(1);
while (s.length() > 0 && Character.isDigit(s.charAt(0))) {
temp.append(Integer.parseInt("" + s.charAt(0)));
s = s.substring(1);
}
}
ans = Double.valueOf(temp.toString()).doubleValue();
return ans;
}
double paren() {
double ans;
if (s.charAt(0) == '(') {
s = s.substring(1);
ans = add();
s = s.substring(1);
} else {
ans = term();
}
return ans;
}
double exp() {
boolean neg = false;
if (s.charAt(0) == '-') {
neg = true;
s = s.substring(1);
}
double ans = paren();
while (s.length() > 0) {
if (s.charAt(0) == '^') {
s = s.substring(1);
boolean expNeg = false;
if (s.charAt(0) == '-') {
expNeg = true;
s = s.substring(1);
}
double e = paren();
if (ans < 0) {
double x = 1;
if (Math.ceil(e) == e) {
if (expNeg)
e *= -1;
if (e == 0)
ans = 1;
else if (e > 0)
for (int i = 0; i < e; i++)
x *= ans;
else
for (int i = 0; i < -e; i++)
x /= ans;
ans = x;
} else {
ans = Math.log(-1);
}
} else if (expNeg)
ans = Math.exp(-e * Math.log(ans));
else
ans = Math.exp(e * Math.log(ans));
} else
break;
}
if (neg)
ans *= -1;
return ans;
}
double trig() {
double ans = 0;
boolean found = false;
if (s.indexOf("sin") == 0) {
s = s.substring(3);
ans = Math.sin((trig() * Math.PI) / 180);
found = true;
} else if (s.indexOf("cos") == 0) {
s = s.substring(3);
ans = Math.cos((trig() * Math.PI) / 180);
found = true;
} else if (s.indexOf("tan") == 0) {
s = s.substring(3);
ans = Math.tan((trig() * Math.PI) / 180);
found = true;
}
if (!found) {
ans = exp();
}
return ans;
}
double mul() {
double ans = trig();
if (s.length() > 0) {
while (s.length() > 0) {
if (s.charAt(0) == '*') {
s = s.substring(1);
ans *= trig();
} else if (s.charAt(0) == '/') {
s = s.substring(1);
ans /= trig();
} else
break;
}
}
return ans;
}
double add() {
double ans = mul();
while (s.length() > 0) {
if (s.charAt(0) == '+') {
s = s.substring(1);
ans += mul();
} else if (s.charAt(0) == '-') {
s = s.substring(1);
ans -= mul();
} else {
break;
}
}
return ans;
}
public double evaluate() {
s = x.intern();
double last = add();
return last;
}
public Expression(String s) {
StringBuffer b = new StringBuffer();
StringTokenizer t = new StringTokenizer(s, " ");
while (t.hasMoreElements())
b.append(t.nextToken());
t = new StringTokenizer(b.toString(), "\t");
b = new StringBuffer();
while (t.hasMoreElements())
b.append(t.nextToken());
x = b.toString();
}
public String toString() {
return x.intern();
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter expression: ");
Expression e = new Expression(sc.nextLine());
System.out.println("\n" + e + " = " + e.evaluate() + "\n");
}
}
This program is generally reading in a string representation of a mathematical expression, and interpreting and executing that expression. As for the Java elements you're curious about:
StringBuffer is a more efficient interface to manipulating String objects.
StringTokenizer(String, String) is a class to break a string into tokens. In this constructor, the first argument is a string to break into tokens, the second argument is the delimiter used to create those tokens.
Math.ceil() returns the smallest (closest to negative infinity) double value that is greater than or equal to the argument and is equal to a mathematical integer.
StringBuffer.toString() writes out a String representing the data in the buffer
\t is a tab
+= and -= are the {add/ subtract} assignment operators, which {add / subtract} right operand to the left operand and assign the result to left operand. E.g.
int x = 0;
x += 2; // x is now 2
See javadoc for StringBuffer at http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuffer.html
See javadoc for StringTokenizerat http://docs.oracle.com/javase/7/docs/api/java/util/StringTokenizer.html
I will try to comment all but the obvious lines
import java.util.*;
public class Expression {
String s, x;
double term() {
double ans = 0;
StringBuffer temp = new StringBuffer(); //Efficient than simple String
while (s.length() > 0 && Character.isDigit(s.charAt(0))) { //Check if the first character is a digit
temp.append(Integer.parseInt("" + s.charAt(0))); //If true, add to temp String
s = s.substring(1);
}
if (s.length() > 0 && s.charAt(0) == '.') {
temp.append('.');
s = s.substring(1);
while (s.length() > 0 && Character.isDigit(s.charAt(0))) {
temp.append(Integer.parseInt("" + s.charAt(0)));
s = s.substring(1);
}
}
if (s.length() > 0 && (s.charAt(0) == 'e' || s.charAt(0) == 'E')) {
temp.append('e');
s = s.substring(1);
temp.append(s.charAt(0));
s = s.substring(1);
while (s.length() > 0 && Character.isDigit(s.charAt(0))) {
temp.append(Integer.parseInt("" + s.charAt(0)));
s = s.substring(1);
}
}
ans = Double.valueOf(temp.toString()).doubleValue();
return ans;
}
double paren() {
double ans;
if (s.charAt(0) == '(') {
s = s.substring(1);
ans = add();
s = s.substring(1);
} else {
ans = term();
}
return ans;
}
double exp() {
boolean neg = false;
if (s.charAt(0) == '-') {
neg = true;
s = s.substring(1);
}
double ans = paren();
while (s.length() > 0) {
if (s.charAt(0) == '^') {
s = s.substring(1);
boolean expNeg = false;
if (s.charAt(0) == '-') {
expNeg = true;
s = s.substring(1);
}
double e = paren();
if (ans < 0) {
double x = 1;
if (Math.ceil(e) == e) { //Check Math.ceil documentation at http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#ceil(double)
if (expNeg)
e *= -1;
if (e == 0)
ans = 1;
else if (e > 0)
for (int i = 0; i < e; i++)
x *= ans;
else
for (int i = 0; i < -e; i++)
x /= ans;
ans = x;
} else {
ans = Math.log(-1); //http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#log(double)
}
} else if (expNeg)
ans = Math.exp(-e * Math.log(ans));
else
ans = Math.exp(e * Math.log(ans)); //http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#exp(double)
} else
break;
}
if (neg)
ans *= -1;
return ans;
}
double trig() {
double ans = 0;
boolean found = false;
if (s.indexOf("sin") == 0) {
s = s.substring(3);
ans = Math.sin((trig() * Math.PI) / 180);
found = true;
} else if (s.indexOf("cos") == 0) {
s = s.substring(3);
ans = Math.cos((trig() * Math.PI) / 180);
found = true;
} else if (s.indexOf("tan") == 0) {
s = s.substring(3);
ans = Math.tan((trig() * Math.PI) / 180);
found = true;
}
if (!found) {
ans = exp();
}
return ans;
}
double mul() {
double ans = trig();
if (s.length() > 0) {
while (s.length() > 0) {
if (s.charAt(0) == '*') {
s = s.substring(1);
ans *= trig();
} else if (s.charAt(0) == '/') {
s = s.substring(1);
ans /= trig();
} else
break;
}
}
return ans;
}
double add() {
double ans = mul();
while (s.length() > 0) {
if (s.charAt(0) == '+') {
s = s.substring(1);
ans += mul();
} else if (s.charAt(0) == '-') {
s = s.substring(1);
ans -= mul();
} else {
break;
}
}
return ans;
}
public double evaluate() {
s = x.intern();
double last = add();
return last;
}
public Expression(String s) {
StringBuffer b = new StringBuffer();
StringTokenizer t = new StringTokenizer(s, " "); //Creates a iterable t object so you can iterate over each "word" separate by space
while (t.hasMoreElements())
b.append(t.nextToken());
t = new StringTokenizer(b.toString(), "\t");
b = new StringBuffer();
while (t.hasMoreElements())
b.append(t.nextToken());
x = b.toString();
}
public String toString() {
return x.intern();
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter expression: ");
Expression e = new Expression(sc.nextLine());
System.out.println("\n" + e + " = " + e.evaluate() + "\n");
}
}

Why subsequence(a,b).toString() is faster than substring(a,b)?

Why subsequence(a,b).toString() is faster than substring(a,b)?
when i convert my all subsequences to substring it slows up to %7 all the time. why does it happen?
Below is my code;
private static String filterStr(String s)
{
for(int a = 0; a < s.length(); a++)
{
int c = s.charAt(a);
if(((c < 65) || ((c >90) &&(c < 97)) || (c > 122)))
{
if(c!=34 && c!=96 && c!=39)// tırnak değillerse
{
String temp = s.substring(0,a);
temp+= s.subSequence(a+1,s.length());
s = temp;
a--;
}
else
{
if(a !=0) // if not at the beginning
{
if(a == s.length()-1)
s = s.subSequence(0,s.length()-1).toString();
else
s = s.subSequence(0,s.length()-2).toString();
}
else
s = s.subSequence(1,s.length()).toString();
}
}
if(c >= 65 && c <= 90) // convert to lower case first character.
{
String temp = s.substring(1,s.length());
c+=32;
s = (char)c + temp;
}
}
return s;
}
CharSequence subSequence(int beginIndex, int endIndex) {
return this.substring(beginIndex, endIndex);
}
this is the implementation of subSequence method, It can not be faster/slower.

String errors in convertor

so my code works for some words but not others it sprints out String index out of range: -1
im suppose to print out ub before every vowel and vowel cluster
ex dubious would be dubububious or cat loveo would be lubovudeo
String sentance, set;
sentance = "toster iooppp";
set= translate(sentance);
System.out.println(set);
}
public static String translate (String sentence){
String set = " ";
sentence= sentence.toLowerCase();
scan = new Scanner (sentence);
while (scan.hasNext()) {
set+= toUbbi (scan.next());
set += " ";
}
return set;
}
private static String toUbbi(String word ) {
String str= word;
String new_str="";
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (isVowel(c) && isVowel(str.charAt(i -1)) )
{ // If is a vowel
new_str += "ub" ;
}
new_str += c;
}
return new_str;
}
private static boolean isVowel(char c)
{
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' ){
return true;}
return false;
in first iteration it gives error..
if (isVowel(c) && isVowel(str.charAt(i -1)) )
{ // If is a vowel
new_str += "ub" ;
}
so change like this..
if (isVowel(c))
{ // If is a vowel
new_str += "ub" ;
}
or change your loop..
for (int i = 1; i < str.length(); i++) {
// yur remain code...
}

Categories