Current method "evaluatePostfix" running but printing out false results (java) - java

I have written my code that is a linked list using stacks. The program, that takes an infix form and converts it to postfix, is currently outputting (with the use of my input and output files) the correct conversions. However, I don't understand how to get the evaluatePostFix method to work properly. My problem is printing out false results and I don't know why. Any help is appreciated!
My current evaluatePostfix method:
public static int evaluatePostfix(String postfix) {
Stack<Integer> stack = new Stack<>();
Stack<Character> operatorStack = new Stack<>();
int count = 0;
int operandTwo = '0';
int operandOne = '0';
while (count < postfix.length() && count >= 0) {
char nextCharacter = postfix.charAt(count);
switch(nextCharacter) {
case '^':
operatorStack.push (nextCharacter);
break;
case '+':
stack.push(operandTwo + operandOne);
case '-':
stack.push(operandTwo - operandOne);
case '*':
stack.push(operandTwo * operandOne);
case '/':
stack.push(operandTwo / operandOne);
int result1 = nextCharacter;
stack.push(result1);
break;
default: break;
} //End switch
count = count + 1;
} //End while
//return stack.pop();
return stack.peek();
} //End evaluatePostfix

case '+':
stack.push(operandTwo + operandOne);
case '-':
stack.push(operandTwo - operandOne);
You will want to have a break statement in there to avoid falling into the next case block.
You will want to pop these two operands off your stack first, otherwise you don't get to access their values (and they remain on the stack, too).
In general, to debug this kind of code, useful tools are stepping through with a debugger, inserting println statements, writing unit tests and reasoning about the flow and variable state on a piece of paper.

Related

How to create a program that converts binary to decimal

I'm trying to convert binary to decimal, how do I change my code to be able to do that? Where did I mess up?
i tried looking at other examples, looking at java api and watching videos but i still can't figure out what mistake i have made.
package Calculator;
import java.util.Scanner;
public class Calculator {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("(2) Convert binary to decimal");
System.out.println("\n\n Please enter your choice: ");
int choice = scan.nextInt();
if(choice == 2){
scan.nextLine();
//prompt for user input
System.out.println("Please enter a binary number: ");
String binary = scan.nextLine();
char[] binaryArray = binary.toCharArray();
int i=1;
int integer=0;
//potential problem somewhere around here?
while(i<8){
if(binaryArray[i]==0) {
++i;
}else if(binaryArray[i]==1) {
switch(i) {
case 1:
integer+=128;
++i;
break;
case 2:
integer+=64;
++i;
break;
case 3:
integer+=32;
++i;
break;
case 4:
integer+=16;
++i;
break;
case 5:
integer+=8;
++i;
break;
case 6:
integer+=4;
++i;
break;
case 7:
integer+=2;
++i;
break;
case 8:
integer+=1;
++i;
break;
}
}
}
System.out.println("The decimal value of the binary number is: "+ integer);
scan.close();
}
}
}
The input is always 0. I've tried 11010110, 11111111,and 01010111. Always 0. I know the problem lies somewhere with my integer value not changing but I can't figure out what it specifically is.
This is happening because you are reading the input, and converting into an array of char.
Anywhere where you are making your comparisons to an int, you should instead be doing a comparison to a char, by wrapping your values in single quotations.
while(i<8){
if(binaryArray[i]=='0') {
++i;
}else if(binaryArray[i]=='1') {
switch(i) {
case 1:
integer+=128;
++i;
break;
case 2:
integer+=64;
++i;
break;
case 3:
integer+=32;
++i;
break;
case 4:
integer+=16;
++i;
break;
case 5:
integer+=8;
++i;
break;
case 6:
integer+=4;
++i;
break;
case 7:
integer+=2;
++i;
break;
case 8:
integer+=1;
++i;
break;
}
}
Others have already pointed out that you have got confused between 0 and 1, and '0' and'1'`.
Other problems:
Your i starts at 1, so you miss the most significant bit;
You will never actually hit case 8: in the switch because of the while (i < 8) loop guard.
This doesn't work unless you enter exactly 8 bits.
You can write the entire while loop in a much more concise way:
for (int i = 0; i < binaryArray.length; i++) {
integer *= 2; // shift the digits along by 1 place
if (binaryArray[i] == '1') {
integer += 1; // set the least significant bit.
}
}
You should get away from all those switch statements.
Say you have "10101101" as input.
set val = 0;
Then either multiply by val by 2 or shift left 1 bit. They're the same. It is important
you do this before adding the next bit.
Start from the left and if it's a '1', add a 1 to val. Otherwise, add 0.
Then repeat starting at multiply until you've gone thru the string.
val should then have the decimal version when you print it.

java - switch statement with range of int

I want to use a switch statement to check a range of numbers I have found a few places saying something like
case 1...5 or case (score >= 120) && (score <=125) would work but I just somehow keep on getting errors.
What I want is if the number is between 1600-1699 then do something.
I can do if statements but figured it's time to start using switch if possible.
On the JVM level switch statement is fundamentally different from if statements.
Switch is about compile time constants that have to be all specified at compile time, so that javac compiler produces efficient bytecode.
In Java switch statement does not support ranges. You have to specify all the values (you might take advantage of falling through the cases) and default case. Anything else has to be handled by if statements.
If you really want to use switch statements — here is a way to create pseudo-ranges with enums, so you can switch over the enums.
First, we'll need to create the ranges:
public enum Range {
TWO_HUNDRED(200, 299),
SIXTEEN_HUNDRED(1600, 1699),
OTHER(0, -1); // This range can never exist, but it is necessary
// in order to prevent a NullPointerException from
// being thrown while we switch
private final int minValue;
private final int maxValue;
private Range(int min, int max) {
this.minValue = min;
this.maxValue = max;
}
public static Range from(int score) {
return Arrays.stream(Range.values())
.filter(range -> score >= range.minValue && score <= range.maxValue)
.findAny()
.orElse(OTHER);
}
}
And then your switch:
int num = 1630;
switch (Range.from(num)) {
case TWO_HUNDRED:
// Do something
break;
case SIXTEEN_HUNDRED:
// Do another thing
break;
case OTHER:
default:
// Do a whole different thing
break;
}
You can use ternary operator, ? :
int num = (score >= 120) && (score <=125) ? 1 : -1;
num = (score >= 1600) && (score <=1699 ) ? 2 : num;
switch (num) {
case 1 :
break;
case 2 :
break;
default :
//for -1
}
As far as I know, ranges aren't possible for switch cases in Java. You can do something like
switch (num) {
case 1: case 2: case 3:
//stuff
break;
case 4: case 5: case 6:
//more stuff
break;
default:
}
But at that point, you might as well stick with the if statement.

Why do I get this "unreachable statement" error?

I am converting a roman numeral input to it's integer value. In my convertChar method, I keep getting an error that it is an unreachable statement whenever I add a break statement in to the code. I don't know why this is. I'm a new student and I must have done something wrong and I was hoping maybe someone can show me what I did wrong and how to fix it. It must have something to do with the way I set the methods up right? I still get confused on what variables to input so maybe I messed up there but I'm not experienced enough to know exactly what I did wrong. Here is everything I have:
public class RomanNumeralConverter {
public int romanInput() {
return convert(getUserInput());
}
public String getUserInput() {
Scanner numberInput = new Scanner (System.in);
System.out.print("Enter a roman numeral in uppercase: ");
String userInput = numberInput.next();
numberInput.close();
return userInput;
}
public int convert (String userInput) {
int result = 0;
int subtractamount = 0;
int x = userInput.length();
while(x != 0) {
char romanConvert = userInput.charAt(x);
if(x >= 1) {
if(convertChar(romanConvert) >= convertChar(userInput.charAt(x - 1))) {
subtractamount += convertChar(userInput.charAt(x - 1));
}
}
result += convertChar(romanConvert);
x--;
}
result -= subtractamount;
return result;
}
public static char convertChar(char value) {
switch (value) {
case 'I':
return 1;
break;
case 'V':
return 5;
break;
case 'X':
return 10;
break;
case 'L':
return 50;
break;
case 'C':
return 100;
break;
case 'D':
return 500;
break;
case 'M':
return 1000;
break;
default:
System.out.println("Invalid character!");
return 0;
break;
}
return value;
}
public void printValue() {
System.out.println(romanInput());
}
public static void main(String[] args) {
new RomanNumeralConverter().printValue();
}
}
Your problem lies in your switch statement. You can minimize this occurring elsewhere by attempting to have methods return only once (which i think is best practice)
public static char convertChar(char value) {
char result;
switch (value) {
case 'I':
result = 1;
break;
case 'V':
result = 5;
break;
case 'X':
result = = 10;
break;
case 'L':
result = 50;
break;
case 'C':
result = 100;
break;
case 'D':
result = 500;
break;
case 'M':
result = 1000;
break;
default:
System.out.println("Invalid character!");
result = 0;
break;
}
return result
}
In Java, it is a compile error to have statements that will never be reached while execution. In your case, the break statement will never be reached as there is a return statement above it. Also that last return statement will never be reached as you already would have returned in any case by the end of the switch block.
The problem is in your switch statement.
A default case can be thought of like the else in an if-else statement; it will always execute if no other condition in the switch is satisfied. If you are performing a return (or throw) inside of a default case, any code that follows after that will not be reachable.
You have two options:
Change the return statements to only assign a value to result instead, meaning that there's only one point of return from your code, or
Remove the return result from after your switch.

Figure out Odd Even or Zero by entering the value

My teacher asked me a question and I was really confused how to write it out as a code. I understood what I had to do, but just couldn't write in Java. So the question was that: Design and implement an application that determines and prints the number of odd even and zero digits. Input could be anything from the user/keyboard. I just don't know how to start. So can someone help me here with an answer and an explanation with that?(without using string)
Thank you so much for your time.
Application? It's three lines:
int odds = str.replaceAll("[^13579]", "").length();
int evens = str.replaceAll("[^2468]", "").length();
int zeroes = str.replaceAll("[^0]", "").length();
If the input is not a string, make it one:
long number;
String str = number + "";
I would use a for loop to traverse the input string. Within the for loop would be a switch statement that increments either the 'odd' variable, the 'even' variable,' the 'zero' variable, or does nothing.
This way the string is only traversed once instead of three times.
The code would look something like:
int numOdds = 0;
int numEvens = 0;
int numZeroes = 0;
for(int i = 0; i < inputString.length(); i++) {
switch(inputString.charAt(i)) {
case '1':
case '3':
case '5':
case '7':
case '9': numOdds++;
break;
case '2':
case '4':
case '6':
case '8': numEvens++;
break;
case '0': numZeroes++;
default: break;
}
}
Looks like you have a couple answers. Here is another you may like more because you probably can understand it:
int odds, evens, zeroes;
public void setOddsEvensZereos(String str) {
for(char c:str) {
try {
int i = Integer.parseInt(c + "");
if(i == 0)
zereos++;
else if(i % 2 == 0)
evens++;
else
odds++;
} catch (Exception e){/*the character isn't a number*/}
}
}

Switch statement for some reason does not like case 8. Compiler is acting real weird

Here is the code:
public static void main(String args[])
{
int i=0;
int m=0;
double scale;
boolean exit;
Shape[] s = new Shape[10];
while(exit !=true)
{
System.out.print("\nChoose an option:\n"+
"1-Add a new circle\n"+
"2-Add a new rectangle\n"+
"3-Delete all shapes\n"+
"4-Scale all shapes\n"+
"5-Display perimeter of all shapes\n"+
"6-Display the area of all shapes\n"+
"7-Enter scale factor\n"+
"8-Exit program\n");
Scanner input = new Scanner(System.in);
m=input.nextInt();
if(i<=9)
{
switch (m)
{
case 1: Circle c = new Circle(0);
s[i]=c;
i++;
break;
case 2: Rectangle r = new Rectangle(1,1);
s[i]=r;
i++;
break;
case 3: s=null;
i=0;
break;
case 4: for(i=0; i<s.length; i++)
{
s[i].scaleShape();
}
break;
case 5: for(i=0; i<s.length; i++)
{
if(s[i] != null)
{
System.out.println(s[i].getPerimeter());
}
}
break;
case 6: for(i=0; i<s.length; i++)
{
if(s[i] != null)
{
System.out.println(s[i].getArea());
}
}
break;
case 7: do
{
System.out.println("\nEnter scale factor");
scale=input.nextDouble();
}
while(scale<0);
Shape.setScaleFactor(scale);
}
break;
case 8: System.out.println("Do you want to quit?");
break; //Nothing here since loop should terminate it.
//default: System.out.println("Number must be 1-8");
// break;
}
}
}
}
Oddly the compiler is giving me an error on case 8 saying:
Type mismatch can't convert from int to boolean.
But Im not converting anything to boolean
-syntax error on token "case" assert expected
-syntax error on token :, ; expected
But all the commands there have semi-colons
expression must return a value
Why is the compiler acting so funny? Normally errors like that are easy to find. What is going on?
Your problem is in the case for 7:
case 7: do
{
System.out.println("\nEnter scale factor");
scale=input.nextDouble();
}
while(scale<0);
Shape.setScaleFactor(scale);
}
Notice the extra close brace: that's closing your switch statement, orphaning your case 8.
} // <-- Why is this here?
break;
case 8: System.out.println("Do you want to quit?");
You're ending the switch statement with an extra }. Remove it and things may work.
Every one has pointed out that you have an extra parenthesis in your code, what we've failed to point out is where it's coming from...
while(scale<0); // <-- This isn't going to work....
Shape.setScaleFactor(scale);
}
It should be...
while(scale<0) {
Shape.setScaleFactor(scale);
}
The next question is, how is scale decremented? Cause this could cause an infinite loop if you're not careful.
while(scale<0);
Shape.setScaleFactor(scale);
} // Remove this parenthesis.
break;

Categories

Resources