I'm a bit new to java, I'm having one error with my Java program that I can't seem to fix, very easy solution I just can't see it haha. How can I fix this? I tried a few things but it adds more errors on top of each other. Thank you all!
import java.io.*;
import java.util.*;
class Node {
public char ch;
public Node leftChild;
public Node rightChild;
Node(char c) {
ch = c;
}
public void displayNode() {
System.out.print(ch);
}
}
class Tree {
public Node root;
public Tree(Node nd) {
root = nd;
}
public void traverse(int traverseType) {
switch (traverseType) {
case 1:
System.out.print(" \n Preorder traversal : ");
preOrder(root);
break;
case 2:
System.out.print(" \n Inorder traversal : ");
inOrder(root);
break;
case 3:
System.out.print(" \n Postorder traversal : ");
postOrder(root);
break;
}
System.out.println();
}
private void preOrder(Node localRoot) {
if (localRoot != null) {
localRoot.displayNode();
preOrder(localRoot.leftChild);
preOrder(localRoot.rightChild);
}
}
private void inOrder(Node localRoot) {
if (localRoot != null) {
inOrder(localRoot.leftChild);
localRoot.displayNode();
inOrder(localRoot.rightChild);
}
}
private void postOrder(Node localRoot) {
if (localRoot != null) {
postOrder(localRoot.leftChild);
postOrder(localRoot.rightChild);
localRoot.displayNode();
}
}
public void displayTree() {
Stack globalStack = new Stack();
globalStack.push(root);
int nBlanks = 32;
boolean isRowEmpty = false;
System.out.println(" ...................................................... ");
while (isRowEmpty == false) {
Stack localStack = new Stack();
isRowEmpty = true;
for (int j = 0; j < nBlanks; j++)
System.out.print(' ');
while (globalStack.isEmpty() == false) {
Node temp = (Node) globalStack.pop();
if (temp != null) {
temp.displayNode();
localStack.push(temp.leftChild);
localStack.push(temp.rightChild);
if (temp.leftChild != null || temp.rightChild != null)
isRowEmpty = false;
} else {
System.out.print("-");
localStack.push(null);
localStack.push(null);
}
for (int j = 0; j < nBlanks * 2 - 1; j++)
System.out.print(' ');
}
System.out.println();
nBlanks / = 2;
while (localStack.isEmpty() == false)
globalStack.push(localStack.pop());
}
System.out.println(" ...................................................... ");
}
}
class BottomUp {
private String inString;
private int strlen;
private Tree[] treeArray;
private Tree aTree;
private int numNodes;
BottomUp(String s) {
inString = s;
strlen = inString.length();
treeArray = new Tree[100];
for (int j = 0; j < strlen; j++) {
char ch = inString.charAt(j);
Node aNode = new Node(ch);
treeArray[j] = new Tree(aNode);
}
}
public Tree getTree() {
return aTree;
}
public void balanced() {
numNodes = strlen;
while (numNodes > 1) {
int i = 0;
int j = 0;
Tree[] tempArray = new Tree[100];
for (j = 0; j < strlen - 1; j++) {
Tree tree1 = treeArray[j];
Tree tree2 = treeArray[j + 1];
Node aNode = new Node('+');
aTree = new Tree(aNode);
aTree.root.leftChild = tree1.root;
aTree.root.rightChild = tree2.root;
tempArray[i++] = aTree;
numNodes--;
j++;
}
if (strlen % 2 == 1) {
Tree tree1 = treeArray[j];
Node aNode = new Node('+');
aTree = new Tree(aNode);
aTree.root.leftChild = tree1.root;
tempArray[i++] = aTree;
}
treeArray = tempArray;
strlen = numNodes;
}
aTree = treeArray[0];
}
}
class BottomUpApp {
public static void main(String[] args) throws IOException {
BottomUp bup;
Tree theTree = null;
int value;
String str;
while (true) {
System.out.print(" Enter first letter of ");
System.out.print(" balanced , show , or traverse : ");
int choice = getChar();
switch (choice) {
case 'b':
System.out.print(" Enter string : ");
str = getString();
bup = new BottomUp(str);
bup.balanced();
theTree = bup.getTree();
break;
case 's':
theTree.displayTree();
break;
case 't':
System.out.print(" Enter type 1, 2 or 3 : ");
value = getInt();
theTree.traverse(value);
break;
default:
System.out.print(" Invalid entry \n ");
}
}
}
public static String getString() throws IOException {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String s = br.readLine();
return s;
}
public static char getChar() throws IOException {
String s = getString();
return s.charAt(0);
}
public static int getInt() throws IOException {
String s = getString();
return Integer.parseInt(s);
}
}
ERROR CODE
Node.java:112: error: illegal start of expression
nBlanks / = 2 ;
^
1 error
The Java operator /= must be typed without spaces in between, or else it will be parsed as 2 separate operators, / and =, which is a syntax error. Try
nBlanks /= 2 ;
Related
So i have this function EDIT:Whole program as requested
//This is a java program to construct Expression Tree using Infix Expression
import java.io.*;
public class Infix_Expression_Tree
{
public static void main(String args[]) throws IOException
{
String result="";
File vhod = new File(args[0]);
try{
BufferedReader reader = new BufferedReader(new FileReader(vhod));
Tree t1 = new Tree();
String a = reader.readLine();
t1.insert(a);
t1.traverse(1,result);
System.out.println("rez "+ result);
ch = reader.readLine();
}catch(IOException e){
e.printStackTrace();
}
}
}
class Node
{
public char data;
public Node leftChild;
public Node rightChild;
public Node(char x)
{
data = x;
}
public void displayNode()
{
System.out.print(data);
}
}
class Stack1
{
private Node[] a;
private int top, m;
public Stack1(int max)
{
m = max;
a = new Node[m];
top = -1;
}
public void push(Node key)
{
a[++top] = key;
}
public Node pop()
{
return (a[top--]);
}
public boolean isEmpty()
{
return (top == -1);
}
}
class Stack2
{
private char[] a;
private int top, m;
public Stack2(int max)
{
m = max;
a = new char[m];
top = -1;
}
public void push(char key)
{
a[++top] = key;
}
public char pop()
{
return (a[top--]);
}
public boolean isEmpty()
{
return (top == -1);
}
}
class Conversion
{
private Stack2 s;
private String input;
private String output = "";
public Conversion(String str)
{
input = str;
s = new Stack2(str.length());
}
public String inToPost()
{
for (int i = 0; i < input.length(); i++)
{
char ch = input.charAt(i);
switch (ch)
{
case '+':
gotOperator(ch, 2);
break;
case '*':
gotOperator(ch,1);
break;
case '/':
gotOperator(ch, 3);
break;
case '(':
s.push(ch);
break;
case ')':
gotParenthesis();
//s.pop();
break;
default:
//gotOperator(ch, 0);
//break;
output = output + ch;
}
}
while (!s.isEmpty())
output = output + s.pop();
//System.out.println("to je output iz inToPost " +output);
return output;
}
private void gotOperator(char opThis, int prec1)
{
while (!s.isEmpty())
{
char opTop = s.pop();
if (opTop == '(')
{
s.push(opTop);
break;
} else
{
int prec2;
if (opTop == '+')
prec2 = 2;
else if(opTop=='*')
prec2=1;
else
prec2 = 3;
if (prec2 <= prec1)
{
s.push(opTop);
break;
} else
output = output + opTop;
}
}
s.push(opThis);
}
private void gotParenthesis()
{
while (!s.isEmpty())
{
char ch = s.pop();
if (ch == '(')
break;
else
output = output + ch;
}
}
}
class Tree
{
private Node root;
public Tree()
{
root = null;
}
public void insert(String s)
{
Conversion c = new Conversion(s);
s = c.inToPost();
Stack1 stk = new Stack1(s.length());
s = s + "#";
int i = 0;
char symbol = s.charAt(i);
Node newNode;
while (symbol != '#')
{
if (symbol >= '0' && symbol <= '9' || symbol >= 'A'
&& symbol <= 'Z' || symbol >= 'a' && symbol <= 'z')
{
newNode = new Node(symbol);
stk.push(newNode);
} else if (symbol == '+' || symbol == '/'
|| symbol == '*')
{
Node ptr1=null;
Node ptr2=null;
//if(!stk.isEmpty()){
ptr1 = stk.pop();
if(!stk.isEmpty()){
ptr2 = stk.pop();
}
//}
newNode = new Node(symbol);
newNode.leftChild = ptr2;
newNode.rightChild = ptr1;
stk.push(newNode);
}
/*else if(symbol=='/'){
Node ptr = stk.pop();
newNode = new Node(symbol);
newNode.leftChild = ptr;
newNode.rightChild=null;
stk.push(newNode);
}*/
symbol = s.charAt(++i);
}
root = stk.pop();
}
public void traverse(int type,String result)
{
System.out.println("Preorder Traversal:- ");
preOrder(root,result);
}
private void preOrder(Node localRoot, String result)
{
if(root==null){
return;
}
if (localRoot != null)
{
if(localRoot.data == '/'){
preOrder(localRoot.leftChild,result);
result=result + localRoot.data;
//StringBuilder stringBuilder1 = new StringBuilder();
//stringBuilder1.append(result).append(localRoot.data);
System.out.println(result);
//localRoot.displayNode();
preOrder(localRoot.rightChild,result);
return;
}else{
//System.out.println("trenutni root je" );
//localRoot.displayNode();
result=result + localRoot.data;
// StringBuilder stringBuilder1 = new StringBuilder();
//stringBuilder1.append(result).append(localRoot.data);
System.out.println(result);
preOrder(localRoot.leftChild,result);
//result=result + localRoot.data;
//System.out.print(root.data);
preOrder(localRoot.rightChild,result);
//System.out.print(root.data);
//preOrder(localRoot.rightChild);
return;
}
}
}
}
my problem with it is that with localRoot.DisplayNode() i get the result i want. But when i add the same thing to the String result it adds data, until i get to leaf of the tree(leaf doesnt have left/right child) so it returns to previous recursive call, and goes to right child, here somewhere the leaf(from which we came back) isnt in String anymore. How do i fix this?
String is defined in main method
To shrink a string "abbcccbfgh" by removing consecutive k characters till no removal can be done.
e.g. for k=3 output for the above string will be "afgh".
Please note that K and string both are dynamic i.e provided by the user.
I wrote the below program but I couldn't complete it. Please help.
public class Test {
public static void main(String[] args) {
String str = "abbcccbfgh";
int k = 3;
String result = removeConsecutive(str, k);
System.out.print("result is " + result);
}
private static String removeConsecutive(String str, int k) {
String str1 = str + "";
String res = "";
int len = str.length();
char c1 = 0, c2 = 0;
int count = 0;
for (int i = 0; i < len - 1; i++) {
c1 = str.charAt(i);
c2 = str.charAt(i + 1);
if (c1 == c2) {
count++;
} else {
res = res + String.valueOf(c1);
count = 0;
}
if (count == k-1) {
//remove String
}
}
return res;
}
I suggest to do it with regex:
int l = 0;
do {
l = str.length();
str = str.replaceAll("(.)\\1{" + n + "}", "");
} while (l != str.length());
n = k - 1
(.)\1{2} means any character followed by n same characters. \1 means the same character as in group #1
Is it okey to have recursion ?
public class Test {
public static void main(String[] args) {
String str = "abbcccbfgh";
int k = 3;
String result = removeConsecutive(str, k);
System.out.print("result is " + result);
}
private static String removeConsecutive(String str, int k) {
String ret = str;
int len = str.length();
int count = 0;
char c1 = 0 ;
char c2 = 0;
char last = 0 ;
for (int i = 0; i < ret.length()-1; i++) {
last = c1 ;
c1 = str.charAt(i);
c2 = str.charAt(i + 1);
if (c1 == c2 ) {
if( count > 0 ) {
if( last == c1 ) {
count ++ ;
}
else {
count = 0;
}
}
else {
count++;
}
} else {
count = 0;
}
if (count == k-1) {
int start = ((i+1) - k) + 1 ;
String one = str.substring(0, start) ;
String two = str.substring(start+k);
String new1 = one + two ;
//recursion
ret = removeConsecutive(new1, k) ;
count = 0;
}
}
return ret;
}
}
You can do it with a stack. For each character ch in the string, push it to the stack, if there's 3 consecutive same characters, pop them all. In the end, convert the stack to a string. You can improve the program a little by using a special stack that remembers the number of occurrences of each element.
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
public class Reduce implements Function<String, String> {
private final int k;
public Reduce(final int k) {
if (k <= 0) {
throw new IllegalArgumentException();
}
this.k = k;
}
#Override
public String apply(final String s) {
Stack<Character> stack = new Stack<>();
for (Character ch : s.toCharArray()) {
stack.push(ch);
if (stack.topCount() == k) {
stack.pop();
}
}
return stack.toString();
}
public static void main(String[] args) {
Reduce reduce = new Reduce(3);
System.out.println(reduce.apply("abbcccbfgh"));
}
private static class Stack<T> {
private class Node {
private T value;
private int count;
Node(T value) {
this.value = value;
this.count = 1;
}
}
private List<Node> nodes = new ArrayList<>();
public void push(T value) {
if (nodes.isEmpty() || !top().value.equals(value)) {
nodes.add(new Node(value));
} else {
top().count++;
}
}
public int topCount() {
return top().count;
}
public void pop() {
nodes.remove(nodes.size()-1);
}
private Node top() {
return nodes.get(nodes.size()-1);
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
nodes.forEach(n->{
for (int i = 0; i < n.count; i++) {
sb.append(n.value);
}
});
return sb.toString();
}
}
}
I can't figure out what is wrong with my if else statements telling it which statement to run and what is wrong with the insert statement. It keeps going straight back to insert no matter what i type.
import java.util.*;
import java.io.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.*;
import javax.lang.model.element.*;
public class Node {
public static Node head;
static String data;
static Node next;
static Node q = new Node("", null);
static String inputline;
static int y = 0;
static int count = 0;
static Node current = new Node(q.data, q);
static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
public static void main(String[] args) {
BuildList();
}
public Node() {
data = "";
next = null;
}
public Node(String x, Node n) {
data = x;
next = n;
}
public static void BuildList() {
try { //match
System.out.println("Please Choose A Command To Execute From The Following List:");
System.out.println("-----------------------------------------------------------");
System.out.println("$insert");
System.out.println("$delete m n");
System.out.println("$print m n");
System.out.println("$line m");
System.out.println("$search String");
System.out.println("$done");
System.out.println(
"Please NOTE: m and n are line number parameters for editing and String is a word");
System.out.println("-----------------------------------------------------------");
inputline = in.readLine();
String[] array = inputline.split(" "); //breaks the command into an array 0,1,2
while (!array[0].equals("$done")) //each statement tells it which method to run
{
if (array[0].equals("$insert")) {
Insert();
} else if (array[0].equals("$delete")) {
Delete();
} else if (array[0].equals("$print")) {
Print();
} else if (array[0].equals("$line")) {
Line();
} else if (array[0].equals("$search")) {
Search();
} else {
System.out.println("You have entered an incorrect command");
}
System.out.println("Please enter a command");
inputline = in.readLine();
}
System.out.println("The program is done");
} catch (Exception e) {
System.out.println("Error --" + e.toString());
}
}
public static void Insert() throws IOException {
System.out.println(
"Please Enter The Desired Text (Note: enter $$ when you wish to terminate insert command)");
while (!inputline.equals("$$")) {
inputline = in.readLine();
Node p = new Node(inputline, null);
q.next = p;
q = p;
y++;
}
}
public static void Delete() {
String[] array = inputline.split(" "); //breaks the command into an array 0,1,2
q = head.next;
int lower = Integer.parseInt(array[1]);
int upper = Integer.parseInt(array[2]);
lower--;
if (lower > upper) {
System.out.println("Wrong, first number must be the smaller line number");
} else
for (count = 1; count < y; count++) {
if (lower <= count) {
while (lower <= upper) {
q.next = q.next;
current = q;
lower++;
}
current = q;
break;
} else {
q = q.next;
}
}
}
public static void Print() {
String[] array = inputline.split(" "); //breaks the command into an array 0,1,2
q = head;
if (array.length > 1) {
int lower = Integer.parseInt(array[1]);
int upper = Integer.parseInt(array[2]);
if (lower > upper) {
System.out.println("Wrong, first number must be the smaller line number");
} else {
for (count = 1; count <= y; count++) {
if (lower <= count) {
while (lower <= upper) {
System.out.println(q.data);
q = q.next;
lower++;
}
break;
} else {
q = q.next;
}
}
}
} else {
while (q != null) {
System.out.println(q.data);
q = q.next;
}
}
}
public static void Line() {
String[] array = inputline.split(" "); //breaks the command into an array 0,1,2
q = head.next;
int line_number = Integer.parseInt(array[1]);
for (count = 1; count <= y; count++) {
if (line_number == count) {
System.out.println(q.data);
current = q;
break;
} else {
q = q.next;
}
}
}
public static void Search() {
String[] array = inputline.split(" "); //breaks the command into an array 0,1,2
if (data.contains(array[1])) {
System.out.println(q.data);
} else if (!data.contains(array[1])) {
System.out.println("Word Not Found");
}
}
}
After
System.out.println("Please enter a command");
inputline = in.readLine();
in the while loop, you need to split it into the array again:
array = inputline.split(" ");
otherwise you never change the value of array[0].
Java won't stop reading from input.
I understand that maybe this while loop might have something to do with it:
while(input.hasMoreTokens());
{
array1[counter] = input.nextToken();
counter++;
}
But I don't see why the loop should be a problem because I am already calling .nextToken() which should advance the token.
Here's the full source code:
import java.io.*;
import java.util.*;
class HelloWorld
{
static String ReadLn (int maxLg) // utility function to read from stdin
{
byte lin[] = new byte [maxLg];
int lg = 0, car = -1;
String line = "";
try
{
while (lg < maxLg)
{
car = System.in.read();
if ((car < 0) || (car == '\n')) break;
lin [lg++] += car;
}
}
catch (IOException e)
{
return (null);
}
if ((car < 0) && (lg == 0)) return (null); // eof
return (new String (lin, 0, lg));
}
public static void main (String args[]) // entry point from OS
{
HelloWorld myWork = new HelloWorld(); // create a dinamic instance
myWork.Begin(); // the true entry point
}
void Begin()
{
String idata;
StringTokenizer input;
while ((idata = HelloWorld.ReadLn (255)) != null)
{
input = new StringTokenizer (idata);
String[] array1 = {};
int counter = 0;
while(input.hasMoreTokens());
{
array1[counter] = input.nextToken();
counter++;
}
int[] array2 = {};
for(int a = 0; a < array1.length; a++)
{
array2[a] = Integer.parseInt(array1[a]);
}
int[] array3 = {};
for(int b = 0; b < array2.length; b++)
{
if ( array2[b] != 42)
{
array3[b] = array2[b];
}
else
{
break;
}
}
String string = "";
for( int c = 0; c < array3.length; c++)
{
if( c < array3.length - 1)
{
string += array3[c] + "\n";
}
else
{
string += array3[c];
}
}
System.out.println(string);
}
}
}
You have a stray semicolon at the end of the while:
while(input.hasMoreTokens());
^ REMOVE THIS
I am trying to complete an assignment where I need to write a Java program to take a string from the command line, and implement it as a Binary Tree in a specific order, then get the depth of the binary tree.
For example: "((3(4))7((5)9))"
would be entered as a tree with 7 as the root, 3 and 9 as the children, and 4 as a right child of 3, and 5 as a left child of 9.
My code is below.. The problem I am having is that, because I am basing my checks off of finding a right bracket, I am unsure how to get the elements correctly when they are not directly preceding the brackets, such as the 3 in the above string. Any direction would be greatly appreciated..
class Node {
int value;
Node left, right;
}
class BST {
public Node root;
// Add Node to Tree
public void add(int n) {
if (root == null) {
root = new Node( );
root.value = n;
}
else {
Node marker = root;
while (true) {
if (n < marker.value) {
if (marker.left == null) {
marker.left = new Node( );
marker.left.value = n;
break;
} else {
marker = marker.left;
}
} else {
if (marker.right == null) {
marker.right = new Node( );
marker.right.value = n;
break;
} else {
marker = marker.right;
}
}
}
}
} // End ADD
//Find Height of Tree
public int height(Node t) {
if (t.left == null && t.right == null) return 0;
if (t.left == null) return 1 + height(t.right);
if (t.right == null) return 1 + height(t.left);
return 1 + Math.max(height(t.left), height(t.right));
} // End HEIGHT
// Check if string contains an integer
public static boolean isInt(String s) {
try {
Integer.parseInt(s);
}
catch(NumberFormatException e) {
return false;
}
return true;
} // End ISINT
public int elementCount(String[] a) {
int count = 0;
for (int i = 0; i < a.length; i++) {
if (isInt(a[i])) count++;
}
return count;
}
} // End BST Class
public class Depth {
public static void main(String[] args) {
String[] a = args[0].split(" ");
BST tree = new BST();
int[] bcount = new int[10];
int[] elements = new int[10];
int x = 0, bracketcount = 0;
// Display entered string
System.out.print("Entered Format: ");
for (int j=0; j < a.length; j++) {
System.out.print(a[j]);
}
for (int i=0; i < a.length; i++) {
char c = a[i].charAt(0);
switch (c)
{
case '(':
bracketcount++;
break;
case ')':
if (isInt(a[i-1])) {
bcount[x] = bracketcount--;
elements[x++] = Integer.parseInt(a[i-1]);
}
break;
case '1':
case '7':
default : // Illegal character
if ( (a[i-1].charAt(0) == ')') && (a[i+1].charAt(0) == '(') ) {
bcount[x] = bracketcount;
elements[x++] = Integer.parseInt(a[i]);
}
break;
}
}
System.out.println("\nTotal elements: " + tree.elementCount(a));
// Display BracketCounts
for (int w = 0; w < x; w++) {
System.out.print(bcount[w] + " ");
}
System.out.println(" ");
// Display Elements Array
for (int w = 0; w < x; w++) {
System.out.print(elements[w] + " ");
}
System.out.println("\nDepth: " + tree.height(tree.root));
// Build the tree
for (int y = 0; y < x-1; y++) {
for (int z = 1; z < tree.height(tree.root); z++) {
if (bcount[y] == z) {
tree.add(elements[y]);
}
}
}
} // End Main Function
public static boolean isInt(String s) {
try {
Integer.parseInt(s);
}
catch(NumberFormatException e) {
return false;
}
return true;
}
} // End Depth Class
I would do a couple of statements to get access to a tree with that kind of shape:
For input string : input= "((3(4))7((5)9))"
You could do :
public class Trial {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String input = "((3(4))7((5)9))";
String easier = input.replaceAll("\\(\\(", "");
String evenEasier = easier.replaceAll("\\)\\)", "");
System.out.println(evenEasier);
int firstVal = Integer.parseInt(evenEasier.substring(0, 1));
int firstBracketVal = Integer.parseInt(evenEasier.substring(2, 3));
int middleVal = Integer.parseInt(evenEasier.substring(3, 4));
int secondBracketVal = Integer.parseInt(evenEasier.substring(4,5));
int lastVal = Integer.parseInt(evenEasier.substring(6));
System.out.println("First Val:"+firstVal);
System.out.println("First bracket Val:"+firstBracketVal);
System.out.println("Middle Val:"+middleVal);
System.out.println("Second Bracket Val:"+secondBracketVal);
System.out.println("Last Val:"+lastVal);
}
}
This however would only ever work for entries in that specific format, if that were to change, or the length of the input goes up - this would work a bit or break.....If you need to be able to handle more complicated trees as input in this format a bit more thought would be needed on how to best handle and convert into your internal format for processing.
pseudocode:
function getNode(Node)
get one char;
if (the char is "(")
getNode(Node.left);
get one char;
end if;
Node.value = Integer(the char);
get one char;
if (the char is "(")
getNode(Node.right);
get one char;
end if;
//Now the char is ")" and useless.
end function
Before calling this function, you should get a "(" first.
In this method, the framwork of a Node in string is "[leftchild or NULL] value [rightchild or NULL])".
"("is not belong to the Node, but ")" is.