pop()ing stacks doesn't seem to be erasing the values - java

This program is supposed to read the values of the string input and return a result.
However, when I use
System.out.println(Arrays.toString(stack.toArray()));
to check what the stack looks like at the end, or even during the program, I noticed that the pop() method foe the stack doesn't seem to be removing the elements it's returning.
I'm probably doing something horribly wrong, but I haven't been able to figure it out.
I'd really appreciate any insight !
// Test example : (((1+1)+1)+1)
import java.util.*;
public class Task2
{
public static void main(String[] args) //run Start() method
{
System.out.print("Enter an expression, or press Enter to quit: ");
Stack<String> stack = new Stack<String>();
Scanner scanner = new Scanner(System.in);
String n = scanner.nextLine();
if(!n.isEmpty())
{
for(int i = 0 ; i < n.length() ; i++)
{
if(!(n.charAt(i) == ')'))
{
stack.push(n.charAt(i) + "");
}
else
{
int two = Integer.parseInt(stack.pop());
char op = (stack.pop()).charAt(0);
int one = Integer.parseInt(stack.pop());
switch(op)
{
case '+':{stack.push((one + two) + "");}
case '-':{stack.push((one - two) + "");}
case '*':{stack.push((one * two) + "");}
case '/':{stack.push((one / two) + "");}
}
}
}
}
else
{
System.out.print("\ngoodbye");
System.exit(0);
}
}
}
Sorry for the lack of comments, and thanks !

This is my first solution here, so be gentle :D. The issue was not with pop(), as pop was doing what it was supposed to. You forgot to add break points in your switch statement. It did every operation and added it to the stack giving it the illusion that pop was not working. I will leave the printing part to you. Cheers.
switch(op)
{
case '+':
stack.push((one + two) + "");
break;
case '-':
stack.push((one - two) + "");
break;
case '*':
stack.push((one * two) + "");
break;
case '/':
stack.push((one / two) + "");
break;
}

Related

For each to find object in an array, and return that object

New here, got a small problem that is giving me a headache. I feel like its like one line of code to fix, but for the life of me I cant figure it out.
I'm supposed to have a for-each loop that locates an object within an array and returns that object if it exists, and returns null if it doesn't exist. Yet here's the odd thing for me, it can find the object just fine, and it will set it to something, not the object, just something. I can tell because other methods dependent on this work just fine, this one just isn't returning the object for whatever reason. Anyways, here's the code, I don't think you need anything else
public Icosahedron findIcosahedron(String labelIn) {
Icosahedron output;
output = null;
for (Icosahedron i : iList) {
if (i.getLabel().equalsIgnoreCase(labelIn)) {
output = i;
}
}
return output;
}
Requested:
case 'F':
System.out.print("\tLabel: ");
label = userInput.nextLine();
if (myIcosahedronList.findIcosahedron(label) != null) {
myIcosahedronList.findIcosahedron(label);
}
else {
System.out.println("\"" + label + "\" not found");
}
break;
Once you find object you should stop searching any further:
for (Icosahedron i : iList) {
if (i.getLabel().equalsIgnoreCase(labelIn)) {
output = i;
break;
}
}
Use break to leave the loop.
In the second part of your code store :
case 'F':
System.out.print("\tLabel: ");
label = userInput.nextLine();
Icosahedron icosahedron = myIcosahedronList.findIcosahedron(label);
if ( icosahedron == null) {
System.out.println("\"" + label + "\" not found");
}
else {
// Do something with icosahedron
}
break;
Your code doesn't include a System.out.print() function for when the object is found, you run the function and do nothing with what it returns:
case 'F':
System.out.print("\tLabel: ");
label = userInput.nextLine();
if (myIcosahedronList.findIcosahedron(label) != null) {
myIcosahedronList.findIcosahedron(label); // <- here
}
else {
System.out.println("\"" + label + "\" not found");
}
break;

Calling a method from a switch

My issue is that I can't seem to call the "RustySword" block from a "switch" in my main class. See below.
import java.util.Scanner;
public class Heart {
static int playerGold = 100;
static int oldHatPrice = 25;
static int canOfBeansPrice = 250;
static int rustySwordPrice = 125;
public static Scanner Economy = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Hi, Welcome to my store.\nWould you like to see my wares?");
String c = Economy.next();
switch (c) {
case "yes":
System.out.println("old hat: " + oldHatPrice +" gold\nRusty Sword: " + rustySwordPrice + " gold\nCan of beans: " + canOfBeansPrice + " gold");
String e =Economy.next();
switch (e) {
case "Rusty sword":
RustySword();
break;
default: System.out.println("I don't think you need that!");
}
}
}
public static void RustySword() {
System.out.println("Would you like to buy this rusty sword?\n Rusty sword: " + rustySwordPrice + "\n Your gold: " + playerGold);
String a = Economy.nextLine();
switch (a) {
case "yes":
if (playerGold >= rustySwordPrice) {
System.out.println("Here you go");
playerGold = playerGold - rustySwordPrice;
System.out.println("-Rusty Sword- added to inventory\n Gold remaining: " + playerGold);
}
else {
System.out.println("Sorry, you don't have enough gold!\ncome back when you have more.");}
break;
case "no":
System.out.println("Is there anything else I can do for you?");
String d = Economy.nextLine();
switch (d) {
case "no":
System.out.println("Thanks for shopping");
break;
}
break;
default: System.out.println("i'm not sure what your talking about!");
}
}
}
You are using next() to read the input that is reading only till space then the cursor is being placed in the same line after reading the input.
So the cursor will be at the end of the line \n if your input is only a single word e.g., yes in your case.
The end of the line will be consumed by following next() method. Hence your condition is not matching.
Use nextLine() to read the complete line and use it. You can look into this question
for more info.

Issue with resetting data with a do while loop (Java)

I'm working on a program for school where I need to sort how many vowels are in a string along with the # of non-vowels. My teacher wants us to ask the user if they want to continue so we can provide multiple test cases without running the program more than once. I successfully got the program to loop, but my problem is that the vowel and non-vowel numbers from the previous test case carry over to the next one. I've been searching around online for the solution but I've had no luck so far. Any help would be much appreciated. (I am a noob at programming btw, I still have much to learn.)
import java.util.*;
class VowelReader
{
public static void main(String[] args)
{
String line;
int vi= 0, a = 0, e = 0, o = 0, u = 0, nonvowels = 0;
String answer = null;
Scanner scan = new Scanner (System.in);
do {
System.out.println("Enter a String to be processed for vowels: ");
line = scan.nextLine( );
for(int i = 0; i < line.length(); i++){
char c = Character.toLowerCase(line.charAt(i));
switch (c)
{
case 'a':
a++;
break;
case 'e':
e++;
break;
case 'i':
vi++;
break;
case 'o':
o++;
break;
case 'u':
u++;
default:
nonvowels++;
break;
}
}
System.out.println(line);
System.out.println("a- " +a);
System.out.println("e- " +e);
System.out.println("i- " +vi);
System.out.println("o- " +o);
System.out.println("u- " +u);
System.out.println("Non-vowels -" +nonvowels);
System.out.println("Continue?(Y/N)");
answer = scan.nextLine();
}
while( answer.toLowerCase().equals( "y" ) );
}
}
Using a Map with the key as a String you can keep track of our counts in one object. You then could put as many Maps, one for each test/string into a List. Then you can loop over the list preforming the same test(s) on different data sets.
Being homework and all I'm not going to post any code.

Java program doesn't have any output when using a switch statement inside a while loop?

So I need the statements inside the while loop to repeat until the user enters 4 (which exits the program), but when I try to run the program, nothing is outputted to the screen (but it compiles just fine). Why would it do this? This answer is probably really simple, but any help would be really appreciated!
public class Driver
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int answer;
boolean bool = true;
while(bool);
{
System.out.println("\n\tGeometry Calculator\n" +
"\t1. Calculate the Area of a Circle\n" +
"\t2. Calculate the Area of a Rectangle\n" +
"\t3. Calculate the Area of a Triangle\n" +
"\t4. Quit\n");
System.out.print("\tEnter your choice (1-4): ");
answer = keyboard.nextInt();
switch(answer)
{
case 1:
System.out.println("\n\tCalculating the area of a circle...");
break;
case 2:
System.out.println("\n\tCalculating the area of a rectangle...");
break;
case 3:
System.out.println("\n\tCalculating the area of a triangle...");
break;
case 4:
System.out.println("\n\tQuiting...");
System.exit(0);
break;
default:
System.out.println("\n\tPlease enter a number between 1 and 4.");
}
if(answer == 4)
bool = false;
}
}
You have one tiny mistake. You have added ; after the while loop. Just delete it. Your code should be
while(bool)

Switching String to Integer

I need the syntax for adding in the variable parameter to a switch case that already has lots of parameters. The context is provided below.
I'm using a switch case to change a string answer to an integer return. Instead of having the user answer
1. This.
2. Something else.
I want the answer to look like
(y/n)
I've done it before with a code like this:
static public int getYN() {
String answer = "";
switch(keyboard.nextLine().substring(0, 1).toLowerCase()) {
case "y":
return 1;
case "n":
return 0;
default:
return 2;
}
}
And then using the statement:
int getAnswer = getYN();
System.out.println();
if (getAnswer == 1) {
System.out.println("Stuff.");
test = 1;
}
else {
System.out.println("Other stuff.");
System.out.println();
}
But, I don't know where to put the String answer variable into the switch case. Usually, if you aren't using many other parameters, it would just be
switch(answer) {
}
Check it inline, forget having a dedicated method to doing this check.
char getAnswer = keyboard.next().charAt(0);
System.out.println();
if (getAnswer == 'y' || getAnswer == 'Y')
{
System.out.println("Stuff.");
test = 1;
}
else if( getAnswer == 'n' || getAnswer == 'N')
{
System.out.println("Other stuff.");
System.out.println();
}
If you absolutely have to use a switch:
char getAnswer = keyboard.next().charAt(0);
switch(getAnswer)
{
case 'y':
System.out.println("Stuff.");
test = 1;
break;
case 'n':
System.out.println("Other stuff.");
System.out.println();
break;
}
You can achieve the same thing in one line:
public static int getYN(String s) {
return ("yn YN".indrxOf(s) + 3) % 3;
}
Both upper and lower cases are handled, and the "not found" default value of 2 is handled by adding 3 (indexOf() returns -1 when the target is not found) and modulus divusion takes care of the capital letter indexes.
Fairly neat even if I do say so myself.

Categories