CircularQueue Test errors, indent - java

Here's my code below. I'm new to java. The line in my test is getting an error. The line
x = Response.char At(0); is expecting an identifier?
import java.util.Scanner;
public class CircularQueue {
private int head, tail;
private String [ ] q = new String [ 10 ];
private String name;
int Size;
Scanner input = new Scanner (System.in);
public CircularQueue () {
head = -1;
tail = -1;
}
public void insertQueue () {
if (isQueueFull () )
System.out.println ("Overflow");
else {
name = getName ();
if (isQueueEmpty () )
head = +1;
if (tail==Size-1)
tail=-1;
q [++ tail] = name;
}
}
public void deleteQueue() {
String x;
if ( isQueueEmpty () )
System.out.println("Underflow");
else {
x=q[head];
System.out.println ("Servicing " + x);
if (head==tail) {
head=-1;
tail=-1;
}
else {
head ++;
if (head==Size)
head=0;
}
}
}
public void setSize(int i)
{
Size=i;
}
private String getName () {
System.out.println("Enter name");
return input.nextLine ();
}
public boolean isQueueEmpty () {
return (head==-1);
}
public boolean isQueueFull () {
return ((tail-head+1==0) || (tail-head+1==Size));
}
public void printQueueLogical () {
int next;
if (isQueueEmpty())
System.out.println ("Empty");
else {
next=head;
System.out.println (" q [" + next + "] = " +q[next]);
while (next != tail) {
next ++;
if (next==Size)
next=0;
System.out.println (" q [" + next + "] = " +q[next]);
}
}
}
public void printQueuePhysical () {
for (int J=0; J<Size; J++)
System.out.println (" q [" + J + "]= " + q [J]);
}
}
class TestCircularQueue2 {
public static void main ( String [] args) {
CircularQueue n = new CircularQueue ();
Scanner in = new Scanner (System.in);
String Response;
char x;
System.out.println("Enter command - i/d/l/p/q");
Response = in.next ();
x = Response.char At(0);
x = character.toLowerCase (x);
while (x != 'q' && x != 'Q') {
switch (x) {
case 'i':
n.insertQueue ();
break;
case 'd':
n.deleteQueue();
break;
case 'l':
n.printQueueLogical();
break;
case 'y':
n.printQueuePhysical();
break;
default:
System.out.println ("Illegal Response");
break;
}
System.out.println ("enter command - i/d/l/p/q");
Response = in.next ();
x = Response.char At(0);
x = character.toLowerCase (x);
}
}
}

The method is charAt() not char At(), so you should change the lines
x = Response.char At(0);
to
x = Response.charAt(0);
Also, note that the class is Character not character, so you should use:
Character.toLowerCase(x)
Note: Try to follow Java naming conventions. Use names like someVar for variables/methods and use names like SomeClass for classes.

Related

My program just stated acting up and now no matter what I do it always rains insert

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].

illegal start of expression in Java Error

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 ;

Error: 'void' type not allowed here, within while loop (Java)

I keep getting the following error message in my method:
"Error: 'void' type not allowed here" on the line outEquation = outEquation + opSt.pop() + " ";.
The code I'm working on currently is a stacked linked list which takes in user input (in infix notation) and converts it to postfix. Any help would be appreciated.
import java.util.Scanner;
public class StackDemo
{
public static void main(String[] args)
{
final int right = 0;
final int left = 1;
final int ADD = 0;
final int MULT = 1;
final int EXP = 2;
final int PAR = -1;
}
public void UserPrompt()
{
Scanner keyboard = new Scanner(System.in);
String input = keyboard.nextLine();
System.out.println("Please select what type of conversion you would like to do: ");
System.out.println();
System.out.println("1) Infix to postfix \n2) Postfix to infix \n3) Print Equations \n4) Exit");
if(input == "1")
{
infix();
}
else if(input == "2")
{
postfix();
}
else if(input == "3")
{
print();
}
else if(input == "4")
{
System.exit(0);
}
else
{
System.out.println("That is not a correct input, please re-enter.");
UserPrompt();
}
}
public String infix()
{
String outEquation = "";
LinkedStackClass<String> opSt = new LinkedStackClass<String>();
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the infix equation: ");
while(keyboard.hasNext())
{
String str = keyboard.next();
if(!isOperator(str))
{
outEquation = outEquation + str + " ";
}
else if(str.equals("("))
{
opSt.push(str);
}
else if(str.equals(")"))
{
while(!opSt.peek().equals("("))
{
outEquation = outEquation + opSt.pop() + " ";
}
opSt.pop();
}
else
{
while(opSt.size() > 0 && precede(opSt.peek(), str))
{
if(!opSt.peek().equals("("))
{
outEquation = outEquation + opSt.pop() + " ";
}
else
{
opSt.pop();
}
}
if(!str.equals(")"))
{
opSt.push(str);
}
}
while(opSt.size() > 0)
{
outEquation = outEquation + opSt.pop() + " ";
}
}
}
private static int getExpOrder(String op)
{
switch(op)
{
case "+":
case "-":
case "*":
case "/":
return left;
case "^":
return right;
//default
}
}
private boolean precede(String l, String r)
{
return (getPrec(l) > getPrec(r) || (getPrec(l) == getPrec(r) && getExpOrder(l) == left));
}
private int getPrec(String op)
{
switch(op)
{
case "+":
case "-":
return ADD;
case "*":
case "/":
return MULT;
case "^":
return EXP;
case "(":
case ")":
return PAR;
}
}
public static boolean isOperator(String op)
{
return (op.length() == 1 && "+-*/()".indexOf(op.charAt(0)) != -1);
}
public String toString()
{
return outEquation;
}
public void postfix()
{
System.out.println("Postfix");
}
public void print()
{
System.out.println("Print");
}
}
public class LinkedStackClass<T> extends UnorderedLinkedList<T>
{
public LinkedStackClass()
{
super();
}
public void initializeStack()
{
initializeList();
}
public boolean isEmptyStack()
{
return isEmptyList();
}
public boolean isFullStack()
{
return false;
}
public void push(T newElement)
{
insertFirst(newElement);
} //end push
public T peek() throws StackUnderflowException
{
if (first == null)
throw new StackUnderflowException();
return front();
} //end peek
public void pop()throws StackUnderflowException
{
if (first == null)
throw new StackUnderflowException();
first = first.link;
count--;
if (first == null)
last = null;
}//end pop
}
Ok, so the reason are you getting that error message is because your pop() function has a void return. Typically, in a stack implementation, the pop operation will remove the top item of the stack and return it. Your function only removes the element.
So change your pop() function to look as follows (I apologize in advanced, as Java is not my forté, and this may not even be correct, so you may need to tweak this):
public T pop() throws StackUnderflowException
{
if (first == null)
throw new StackUnderflowException();
// Get the top-most element
T top = peek();
first = first.link;
count--;
if (first == null)
last = null;
return top;
} //end pop
However as user Ashley Frieze stated, better to use an existing implementation if possible, rather than roll your own.

Value being read incorrectly during for loop

For some reason, my program seems to keep crashing because it's reading a token wrong.On line 362 and 363, where it reads token[i], no matter what happens it seems to read it as a '(' character, even though it's clearly not. If I input something like a 100*(5+5) , it will call recursion after i = 2 on 0*(5+5) instead of correctly going to i=4 and calling it on (5+5). Any help debugging would be great!
package apps;
import java.io.IOException;
import java.util.ArrayList;
import java.util.NoSuchElementException;
import java.util.Scanner;
import java.util.StringTokenizer;
import structures.Stack;
public class Expression {
/**
* Expression to be evaluated
*/
String expr;
/**
* Scalar symbols in the expression
*/
ArrayList<ScalarSymbol> scalars;
/**
* Array symbols in the expression
*/
ArrayList<ArraySymbol> arrays;
/**
* Positions of opening brackets
*/
ArrayList<Integer> openingBracketIndex;
/**
* Positions of closing brackets
*/
ArrayList<Integer> closingBracketIndex;
/**
* String containing all delimiters (characters other than variables and constants),
* to be used with StringTokenizer
*/
public static final String delims = " \t*+-/()[]";
/**
* Initializes this Expression object with an input expression. Sets all other
* fields to null.
*
* #param expr Expression
*/
public Expression(String expr) {
this.expr = expr;
scalars = null;
arrays = null;
openingBracketIndex = null;
closingBracketIndex = null;
}
/**
* Matches parentheses and square brackets. Populates the openingBracketIndex and
* closingBracketIndex array lists in such a way that closingBracketIndex[i] is
* the position of the bracket in the expression that closes an opening bracket
* at position openingBracketIndex[i]. For example, if the expression is:
* <pre>
* (a+(b-c))*(d+A[4])
* </pre>
* then the method would return true, and the array lists would be set to:
* <pre>
* openingBracketIndex: [0 3 10 14]
* closingBracketIndex: [8 7 17 16]
* </pe>
*
* See the FAQ in project description for more details.
*
* #return True if brackets are matched correctly, false if not
*/
public boolean isLegallyMatched()
{
Stack<Character> brack = new Stack<Character>();
Stack<Integer> opens = new Stack<Integer>();
openingBracketIndex = new ArrayList<Integer>();
closingBracketIndex = new ArrayList<Integer>();
char x;
char y;
String expr = this.expr;
for(int i=0; i<expr.length(); i++)
{
x = expr.charAt(i);
if(x!='(' && x!= '[' && x!=')' && x!=']')
{
continue;
}
if(x=='(' || x== '[')
{
opens.push(i);
brack.push(x);
}
else if(x==')' || x==']')
{
closingBracketIndex.add(i);
if(opens.isEmpty())
{
return false;
}
openingBracketIndex.add(opens.pop());
if(brack.isEmpty())
{
return false;
}
y = brack.pop();
if(y=='(' && x==')')
{
continue;
}
else if(y=='[' && x==']')
{
continue;
}
else if(y=='{' && x=='}')
{
continue;
}
else
{
return false;
}
}
}
if(!brack.isEmpty())
{
return false;
}
selectionSort(openingBracketIndex);
if(openingBracketIndex.isEmpty()!= true)
{
System.out.print("Opening Bracket Index: [ ");
for(int i=0;i<openingBracketIndex.size(); i++)
{
System.out.print(openingBracketIndex.get(i) + " ");
}
System.out.print("]");
System.out.println();
System.out.print("Closing bracket Index: [ ");
for(int i=0;i<openingBracketIndex.size(); i++)
{
System.out.print(closingBracketIndex.get(i) + " ");
}
System.out.println("]");
}
return true;
}
/**
* Populates the scalars and arrays lists with symbols for scalar and array
* variables in the expression. For every variable, a SINGLE symbol is created and stored,
* even if it appears more than once in the expression.
* At this time, values for all variables are set to
* zero - they will be loaded from a file in the loadSymbolValues method.
*/
public void buildSymbols()
{
scalars = new ArrayList<ScalarSymbol>();
arrays = new ArrayList<ArraySymbol>();
for(int i=0;i<expr.length();i++)
{
String symb = "";
while(i<expr.length() && Character.isLetter(expr.charAt(i)))
{
symb = symb + expr.charAt(i);
i++;
}
if(i==expr.length())
{
i--;
}
if(expr.charAt(i) == '[')
{
ArraySymbol arr = new ArraySymbol(symb);
boolean dupe = checkArrDupes(arr, arrays);
if(symb!="" && dupe == true)
{
arrays.add(arr);
}
}
else
{
ScalarSymbol scal = new ScalarSymbol(symb);
boolean dupe = checkScalDupes(scal,scalars);
if(symb!="" && dupe==true)
{
scalars.add(scal);
}
}
}
// COMPLETE THIS METHOD
}
/**
* Loads values for symbols in the expression
*
* #param sc Scanner for values input
* #throws IOException If there is a problem with the input
*/
public void loadSymbolValues(Scanner sc)
throws IOException {
while (sc.hasNextLine()) {
StringTokenizer st = new StringTokenizer(sc.nextLine().trim());
int numTokens = st.countTokens();
String sym = st.nextToken();
ScalarSymbol ssymbol = new ScalarSymbol(sym);
ArraySymbol asymbol = new ArraySymbol(sym);
int ssi = scalars.indexOf(ssymbol);
int asi = arrays.indexOf(asymbol);
if (ssi == -1 && asi == -1) {
continue;
}
int num = Integer.parseInt(st.nextToken());
if (numTokens == 2) { // scalar symbol
scalars.get(ssi).value = num;
} else { // array symbol
asymbol = arrays.get(asi);
asymbol.values = new int[num];
// following are (index,val) pairs
while (st.hasMoreTokens()) {
String tok = st.nextToken();
StringTokenizer stt = new StringTokenizer(tok," (,)");
int index = Integer.parseInt(stt.nextToken());
int val = Integer.parseInt(stt.nextToken());
asymbol.values[index] = val;
}
}
}
}
/**
* Evaluates the expression, using RECURSION to evaluate subexpressions and to evaluate array
* subscript expressions.
*
* #return Result of evaluation
*/
public float evaluate()
{
printScalars();
printArrays();
String expr = this.expr;
System.out.println("Hello");
float result = evaluate(expr, 0);
return result;
}
public float evaluate(String base, int brackIndex)
{
System.out.println("Method Start");
Stack<Float> numStack = new Stack<Float>();
Stack<String> opStack = new Stack<String>();
Stack<String> op2Stack = new Stack<String>();
Stack<Float> num2Stack = new Stack<Float>();
float x;
float y;
float result;
int swag = findParenIndexes(base);
Stack<Integer> open = new Stack<Integer>();
Stack<Integer> close= new Stack<Integer>();
for(int i=0;i<base.length();i++)
{
if(open.size()==1 && close.size()==1)
{
System.out.println(open.pop() + " " + close.pop());
break;
}
if(base.charAt(i)=='(' || base.charAt(i)=='[')
{
open.push(i);
}
if(base.charAt(i)==')'|| base.charAt(i)==']')
{
open.pop();
close.push(i);
}
}
String expr = base;
String orig = this.expr;
for(int i=0;i<scalars.size();i++)
{
expr = expr.replaceAll(scalars.get(i).name, scalars.get(i).value + "");
}
System.out.println(expr);
StringTokenizer st = new StringTokenizer(expr,delims,true);
String[] tokens = new String[st.countTokens()];
int z=0;
while(st.hasMoreTokens())
{
tokens[z] = st.nextToken();
z++;
}
for(int i=0;i<tokens.length;i++)
{
System.out.println(tokens[i]);
}
for(int i=0;i<tokens.length;i++)
{
String currToken = tokens[i];
if(isNumeric(currToken))
{
numStack.push(Float.parseFloat(currToken));
System.out.println("Number pushed to stack.");
}
if(currToken.charAt(0)=='+')
{
opStack.push(currToken);
System.out.println("+ pushed to stack.");
}
else if(currToken.charAt(0)=='-')
{
opStack.push(currToken);
System.out.println("- pushed to stack.");
}
else if(currToken.charAt(0)=='*')
{
System.out.println("Multiplying...");
System.out.println("Current bracket index is "+ brackIndex);
x = numStack.pop();
i++;
String next = tokens[i];
if(next.charAt(0)=='(')
{
try{
System.out.println("Evaluating " + expr.substring(i+1, swag));
}
catch(Exception e)
{
swag = findParenIndexes(expr.substring(swag,expr.length()));
}
System.out.println("i: " + i + " swag: ") ;
y=evaluate(expr.substring(i+1, swag), brackIndex+1);
result = x*y;
System.out.println("Multiplication worked - evaluate() returned " + result + " and jumped to the "+closingBracketIndex.get(brackIndex)+" index");
i = swag;
System.out.println("i: " + i);
numStack.push(result);
}
if(isNumeric(next))
{
y = Float.parseFloat(next);
result = x*y;
System.out.println(result + " pushed to stack");
numStack.push(result);
}
}
else if(currToken.charAt(0)=='/')
{
System.out.println("Dividing...");
x = numStack.pop();
i++;
String next = tokens[i];
if(next.charAt(0)== '(')
{
y=evaluate(expr.substring(i+1, swag), brackIndex+1);
i = swag;
}
else
{
y = Float.parseFloat(next);
}
if(y==0)
{
System.out.println("Divide by Zero encountered! Please check your input");
throw new IllegalArgumentException();
}
result = x/y;
System.out.println(result + " pushed to stack");
numStack.push(result);
}
else if(currToken.charAt(0)=='(')
{
System.out.println("Evaluating parentheses and adding the term to the stack.");
numStack.push(evaluate(expr.substring(i+1,swag), brackIndex+1));
System.out.println("Jumping to " + swag);
i = swag;
System.out.println("i: " + i);
}
if(arrays.contains(currToken))
{
System.out.println("array variable detected. looking up" + currToken);
int k = arrays.indexOf(currToken);
int cool = arrays.get(k).values[10];
}
// 5+(5*6+(5*3)-4)-9
}
// (a+(b-c))*(d+4)
while(!opStack.isEmpty())
{
op2Stack.push(opStack.pop());
}
while(!numStack.isEmpty())
{
num2Stack.push(numStack.pop());
}
while(op2Stack.isEmpty() == false)
{
String currOp = op2Stack.pop();
if(currOp.charAt(0) == '+')
{
x = num2Stack.pop();
y = num2Stack.pop();
System.out.println("adding "+ x +" and "+ y);
result = x+y;
System.out.println(result + " pushed to stack");
num2Stack.push(result);
if(!opStack.isEmpty())
System.out.println("next op... " + op2Stack.peek());
}
if(currOp.charAt(0) == '-')
{
System.out.println("subtracting...");
x = num2Stack.pop();
y = num2Stack.pop();
result = x-y;
System.out.println(result + " pushed to stack");
num2Stack.push(result);
if(!opStack.isEmpty())
System.out.println("next op... " + op2Stack.peek());
}
}
Float end = num2Stack.pop();
System.out.println("pls work - " + end);
return end;
}
private int findParenIndexes(String expr)
{
Stack<Integer> open = new Stack<Integer>();
Stack<Integer> close = new Stack<Integer>();
for(int i = 0;i<expr.length();i++)
{
if(expr.charAt(i)=='(' || expr.charAt(i)==']')
{
open.push(i);
}
if(expr.charAt(i)==')' || expr.charAt(i)==']')
{
close.push(i);
if(open.size()==1)
{
return close.pop();
}
open.pop();
}
}
return 0;
// COMPLETE THIS METHOD
}
private static boolean isNumeric(String str)
{
try
{
float f = Float.parseFloat(str);
}
catch(Exception e)
{
return false;
}
return true;
}
// test 5*(2+6-(5*3)-6)
/**
* Utility method, prints the symbols in the scalars list
*/
public void printScalars() {
for (ScalarSymbol ss: scalars) {
System.out.println(ss);
}
}
/**
* Utility method, prints the symbols in the arrays list
*/
public void printArrays()
{
for (ArraySymbol as: arrays)
{
System.out.println(as);
}
}
private boolean checkArrDupes(ArraySymbol sym, ArrayList<ArraySymbol> list)
{
if(list.size()!=0)
{
for(int i=0;i<list.size();i++)
{
if(sym==list.get(i))
{
return false;
}
}
}
return true;
}
private boolean checkScalDupes(ScalarSymbol sym, ArrayList<ScalarSymbol> list)
{
if(list.size()!=0)
{
for(int i=0;i<list.size();i++)
{
if(sym==list.get(i))
{
return false;
}
}
}
return true;
}
private void selectionSort(ArrayList<Integer> data)
{
if (data == null)
return;
if (data.size() == 0 || data.size() == 1)
return;
int smallestIndex;
int smallest;
for (int i = 0; i < data.size(); i++)
{
smallest = data.get(i);
smallestIndex = i;
for (int z = i + 1; z < data.size(); z++)
{
if (smallest > data.get(z))
{
// update smallest
smallest = data.get(z);
smallestIndex = z;
}
}
if (smallestIndex != i)
{
int temp = data.get(i);
data.set(i, data.get(smallestIndex));
data.set(smallestIndex, temp);
temp = closingBracketIndex.get(i);
closingBracketIndex.set(i,closingBracketIndex.get(smallestIndex));
closingBracketIndex.set(smallestIndex,temp);
}
}
}
}

need quick help in Java Program Lab

i have a lab for my java class. I have everything except cannot get the average method to work properly. Whenever i run the program, the average is calculated from the random values and not the one updated.
package ArrayKeyAccess;
/**
* Class Definition for Data Element
* Minimal Definition -- No Error Checking
* Instructional Model -- Conceptual Emphasis
*/
public class Data
{
private int studentID;
private int test1;
private int test2;
private int test3;
private int average;
private String letterGrade;
private static int nextSID = 99; //cheap sequence number approach
private static int getNextSID()
{
return ++nextSID;
}//getNextKey
public Data(int n) //no error checking
{
this.setStudentID(getNextSID());
this.setTest1(n);
this.setTest2(n);
this.setTest3(n);
}//Data constructor
public Data(int k, int n) //no uniqueness checking
{
this.setStudentID(k);
this.setTest1(n);
this.setTest2(n);
this.setTest3(n);
}//Data constructor
public Data( Data d ) //Copy Constructor
{ //required for Composition
this.setStudentID(d.getStudentID());
this.setTest1(d.getTest1());
this.setTest2(d.getTest2());
this.setTest3(d.getTest3());
this.calculateAverage(getTest1(), getTest2(), getTest3());
this.determineLetterGrade(letterGrade);
}//copy constructor
public Data copy() //Copy Object
{ //required for Compostion
return new Data(this);
}//copy object
public String toString()
{
return "Student ID: " + this.getStudentID() + '\n' +
"Test 1: " + this.getTest1() + '\n' +
"Test 2: " + this.getTest2() + '\n' +
"Test 3: " + this.getTest3() + '\n' +
"Average: " + this.getAverage() + '\n' +
"Letter Grade: " + this.getLetterGrade() + '\n';
}//toString
public void setStudentID (int n) //no error checking
{
studentID = n;
}
public int getStudentID()
{
return studentID;
}
//----------------------Test1---------------------------------------
public void setTest1(int n) //no validity checking
{
test1 = n;
}
public int getTest1()
{
return test1;
}
//----------------------Test2---------------------------------------
public void setTest2(int n) //no validity checking
{
test2 = n;
}
public int getTest2()
{
return test2;
}
//----------------------Test3---------------------------------------
public void setTest3(int n) //no validity checking
{
test3 = n;
}
public int getTest3()
{
return test3;
}
//---------------calculate average score-----------------------------
public void calculateAverage(int test1, int test2, int test3) //set
{
this.test1 = getTest1();
average = (getTest1() + getTest1() + getTest3()) / 3;
}
//----------------determine letter grade------------------------------
public void determineLetterGrade(String letterGrade)
{
if(average >= 90)
letterGrade = "A";
else if(average >= 80)
letterGrade = "B";
else if(average >= 70)
letterGrade = "C";
else if(average >= 60)
letterGrade = "D";
else
letterGrade = "F";
this.letterGrade = letterGrade;
}
//getAverageScore
public int getAverage() //get
{
return average;
}
//getLetterGrade
public String getLetterGrade()
{
return letterGrade;
}
}//class Data
ProgramTest
UnsortedArray s = new UnsortedArray(10);
int score;
//add 10 data elements
for( int i=1; i<=10; i++ )
{
score = 50 + (int)(Math.random()*50)+1;
s.insert( new Data(score) );
}
System.out.println("------------------TEST 1----------------------");
//update test 1
s.updateTest1(100,44);
s.updateTest1(101,89);
s.updateTest1(102,80);
s.updateTest1(103,95);
s.updateTest1(104,65);
s.updateTest1(105,74);
s.updateTest1(106,69);
s.updateTest1(107,56);
s.updateTest1(108,88);
s.updateTest1(109,99);
s.showList();
The Unsorted Array Class ( i forgot to attach before)
package ArrayKeyAccess;
/**
* Class Definition for Unsorted Array
* Minimal Basic Methods
* Implements Insert, Fetch, Update, Delete
* Conceptual Instructional Model
*/
public class UnsortedArray
{
private int next; //next insert position
private int size; //array capacity
private Data[] a; //reference for container of
//data elements
public UnsortedArray(int n) //no error checking
{
next = 0;
size = n;
a = new Data[size];
}//constructor
public boolean insert( Data newNode )
{
if( next >= size ) //array is full
return false;
//insert copy in next position
a[next] = new Data( newNode );
++next;
return true;
}//insert
public Data fetch( int targetKey )
{
int i=0;
while( i!=next && a[i].getStudentID()!=targetKey ) ++i;
if( i==next ) //node not found
return null;
else //node was found
return a[i].copy(); //return a copy
}//fetch
//Update data element field in the container
public boolean updateTest1( int targetKey, int val )
{
int i=0;
while( i!=next && a[i].getStudentID()!=targetKey ) ++i;
if( i==next ) //node not found
return false;
else //node was found
{
a[i].setTest1( val );
return true;
}
}//updateTest1
public boolean updateTest2( int targetKey, int val )
{
int i=0;
while( i!=next && a[i].getStudentID()!=targetKey ) ++i;
if( i==next ) //node not found
return false;
else //node was found
{
a[i].setTest2( val );
return true;
}
}//updateTest2
public boolean updateTest3( int targetKey, int val )
{
int i=0;
while( i!=next && a[i].getStudentID()!=targetKey ) ++i;
if( i==next ) //node not found
return false;
else //node was found
{
a[i].setTest3( val );
return true;
}
}//updateTest1
//overload update method
//assumes record was fetched and
//value was modified and now is
//to be "reinserted".
public boolean update( int targetKey, Data updNode )
{
int i=0;
while( i!=next && a[i].getStudentID()!=targetKey ) ++i;
if( i==next ) //node not found
return false;
else //node was found
{
a[i] = updNode.copy(); //assign copy
return true; //preserve Composition
}
}//update
public boolean delete( int targetKey )
{
int i=0;
while( i!=next && a[i].getStudentID()!=targetKey ) ++i;
if( i==next ) //node not found
return false;
else //node was found
{
a[i] = a[next-1]; //move last node to deleted position
//"deleted" node has no reference
a[next-1] = null; //new next available position
--next; //reset insert position
return true;
}
}//delete
public void showList() //List the nodes
{
for(int i=0; i<next; i++)
System.out.println( a[i] );
}//showList
}//class UnsortedArray
Well, there's two problems.
First, you're adding getTest1() twice. That's worth fixing in its own right.
The second problem is that you're going to run into integer division - simply because all four of your values are going to be ints, you won't get any floating-point values (or a "true" average).
What you want to do is change the type of average to double, then change your divdend into a floating point number, as such:
average = (getTest1() + getTest2() + getTest3()) / 3.0;
It may be because you add test1 twice.
average = (getTest1() + getTest1() + getTest3()) / 3;
i figured it out, these are my changes, no getters for calculateAverage or letterGrade
public int calculateAverage() //set
{
average = (this.getTest1() + this.getTest2() + this.getTest3()) / 3;
return average;
}
public String letterGrade()
{
if(this.average >= 90)
letterGrade = "A";
else if(this.average >= 80)
letterGrade = "B";
else if(this.average >= 70)
letterGrade = "C";
else if(this.average >= 60)
letterGrade = "D";
else
letterGrade = "F";
return letterGrade;
}
public String toString()
{
return "Student ID: " + this.getStudentID() + '\n' +
"Test 1: " + this.getTest1() + '\n' +
"Test 2: " + this.getTest2() + '\n' +
"Test 3: " + this.getTest3() + '\n' +
"Average: " + calculateAverage() + '\n' +
"Letter Grade: " + this.letterGrade() + '\n';
}//toString

Categories

Resources