So what I'm doing is creating a stack and then find a way to search for a random number in the stack. So basically if the code is:
Stack thisstack = new Stack();
Scanner userinput = new Scanner(System.in);
a = userinput.nextInt();
b = userinput.nextInt();
c = userinput.nextInt();
showpush(thisstack, a);
showpush(thisstack, b);
showpush(thisstack, c);
My question is how would i find a number the user inputs, and be able to throw an exception if we look for a number that isn't there. so if the stack the user inputs is [42, 543, 12] and we look for 42 it shows 42 but if we look for 43 it says something like "number not in stack"
Since Stack class inherits from Vector class, you have access to its contains() method.
contains() returns true if the object is in the stack; false if not, so one trivial implementation of the showpush() method would be:
void showpush(Stack stack, int num){
if (stack.contains(num)){
System.out.println(num);
} else {
System.out.println("number not in stack");
}
}
where num is your search target, and stack... well your stack.
One thing to note here is that when declaring a Stack (since it is a generic type) you also have to declare its type arguments (to ensure type safety), which bears the following change in thisstack's declaration:
Stack<Integer> thisstack = new Stack<Integer>();
You can also check Mureinik's answer here.
Edit/Appendix
Just for completeness, I have added a small demo with two different types of user input (int and float) being pushed into the stack. This is possible when declaring the stack with the more general <Object> type argument, as follows:
import java.util.Stack;
import java.util.Scanner;
public class Jst {
void showpush(Stack stack, Object obj){
if (stack.contains(obj)){
System.out.println("Found "+obj+" in stack");
} else {
System.out.println(obj+" not in stack");
}
}
public static void main(String[] Arguments){
Jst j = new Jst(); //either this way or declare showpush as static
Stack<Object> thisstack = new Stack<Object>();
Scanner userinput = new Scanner(System.in);
int a,pb;
float b,pa;
// get user input
System.out.print("Enter two numbers (int, float):");
try {
a = userinput.nextInt();
b = userinput.nextFloat();
} catch (Exception e) {
System.out.println("Exception : "+e.toString());
return;
}
// push user input into stack
System.out.print("\nPushing user input into stack...");
thisstack.push(a);
thisstack.push(b);
// check stack
System.out.println("Checking stack...");
j.showpush(thisstack, a);
j.showpush(thisstack, b);
// pop stack contents
System.out.print("\nPopping stack contents...");
pa = (float)thisstack.pop();
pb = (int)thisstack.pop();
System.out.println("Popped contents : [ "+pa+", "+pb+" ] (Notice that Stack is LIFO)");
// check stack
System.out.println("Checking stack...");
j.showpush(thisstack, a);
j.showpush(thisstack, b);
// push b back in stack
System.out.print("\nPushing "+b+" back into stack...");
thisstack.push(b);
// check stack
System.out.println("Checking stack...");
j.showpush(thisstack, a);
j.showpush(thisstack, b);
}
}
which yields:
C:\>java Jst
Enter two numbers (int, float):1 23.4
Pushing user input into stack...
Checking stack...
Found 1 in stack
Found 23.4 in stack
Popping stack contents...
Popped contents : [ 23.4, 1 ] (Notice that Stack is LIFO)
Checking stack...
1 not in stack
23.4 not in stack
Pushing 23.4 back into stack...
Checking stack...
1 not in stack
Found 23.4 in stack
Related
public class TulosteluaLikeABoss {
public static void tulostaTahtia(int maara) {
// part 1
int i = 0;
while (maara >i) {
System.out.print("*");
i++;
}
System.out.println("");
}
public static void tulostaTyhjaa(int maara) {
// part 1.1
int i = 0;
while (maara > i) {
System.out.print(" ");
i++;
}
}
//something is wrong below
public static void tulostaKolmio(int koko) {
// part 2
int j = koko;
int k = 0;
while (koko >= k) {
tulostaTahtia(k);
tulostaTyhjaa(j);
k++;
j = j-1;
}
}
// from here below is irrelevant
public static void jouluKuusi(int korkeus) {
// part 3
}
public static void main(String[] args) {
// Testit eivät katso main-metodia, voit muutella tätä vapaasti.
tulostaKolmio(5);
System.out.println("---");
jouluKuusi(4);
System.out.println("---");
jouluKuusi(10);
}
}
I'm trying to do a Java basics course and the task is to print an inward triangle using stars *
I got my program to print that, but when I try to submit, I get error message saying: When tried to call method tulostaKolmio(1), wrong amount of lines were printed. expected <1> but was <2>. I'm pretty annoyed by this, since I ran the code using tulostaKolmio(1) and the program printed just 1 line that had 1 star like it was supposed to. If the code looks strange it's because this is a 3 part task and I'm only doing the second part.
tulostaKolmio(1) assigns koko the value of 1. The while loop in the method will run (koko + 1) number of times. During the first run in the loop tulostaTahita(0) gets called (since k=0 right now), altough it will not print any starts at this call it will print a new line because you have that outside the while loop in the tulostaTahita method.
During the second run in the loop, k=1 and thus tulostaTahita(1) is called. This will print another line so in the end you are left with 2 lines (where the first one is empty).
To solve this you want to add an if statement to make sure tulostaTahita only prints a new line when maara is greater than 0.
See update 1 below for my guess as to why the error is happening
I'm trying to develop an application with some C#/WPF and C++. I am having a problem on the C++ side on a part of the code that involves optimizing an object using GNU Scientific Library (GSL) optimization functions. I will avoid including any of the C#/WPF/GSL code in order to keep this question more generic and because the problem is within my C++ code.
For the minimal, complete and verifiable example below, here is what I have. I have a class Foo. And a class Optimizer. An object of class Optimizer is a member of class Foo, so that objects of Foo can optimize themselves when it is required.
The way GSL optimization functions take in external parameters is through a void pointer. I first define a struct Params to hold all the required parameters. Then I define an object of Params and convert it into a void pointer. A copy of this data is made with memcpy_s and a member void pointer optimParamsPtr of Optimizer class points to it so it can access the parameters when the optimizer is called to run later in time. When optimParamsPtr is accessed by CostFn(), I get the following error.
Managed Debugging Assistant 'FatalExecutionEngineError' : 'The runtime
has encountered a fatal error. The address of the error was at
0x6f25e01e, on thread 0x431c. The error code is 0xc0000005. This error
may be a bug in the CLR or in the unsafe or non-verifiable portions of
user code. Common sources of this bug include user marshaling errors
for COM-interop or PInvoke, which may corrupt the stack.'
Just to ensure the validity of the void pointer I made, I call CostFn() at line 81 with the void * pointer passed as an argument to InitOptimizer() and everything works. But in line 85 when the same CostFn() is called with the optimParamsPtr pointing to data copied by memcpy_s, I get the error. So I am guessing something is going wrong with the memcpy_s step. Anyone have any ideas as to what?
#include "pch.h"
#include <iostream>
using namespace System;
using namespace System::Runtime::InteropServices;
using namespace std;
// An optimizer for various kinds of objects
class Optimizer // GSL requires this to be an unmanaged class
{
public:
double InitOptimizer(int ptrID, void *optimParams, size_t optimParamsSize);
void FreeOptimizer();
void * optimParamsPtr;
private:
double cost = 0;
};
ref class Foo // A class whose objects can be optimized
{
private:
int a; // An internal variable that can be changed to optimize the object
Optimizer *fooOptimizer; // Optimizer for a Foo object
public:
Foo(int val) // Constructor
{
a = val;
fooOptimizer = new Optimizer;
}
~Foo()
{
if (fooOptimizer != NULL)
{
delete fooOptimizer;
}
}
void SetA(int val) // Mutator
{
a = val;
}
int GetA() // Accessor
{
return a;
}
double Optimize(int ptrID); // Optimize object
// ptrID is a variable just to change behavior of Optimize() and show what works and what doesn't
};
ref struct Params // Parameters required by the cost function
{
int cost_scaling;
Foo ^ FooObj;
};
double CostFn(void *params) // GSL requires cost function to be of this type and cannot be a member of a class
{
// Cast void * to Params type
GCHandle h = GCHandle::FromIntPtr(IntPtr(params));
Params ^ paramsArg = safe_cast<Params^>(h.Target);
h.Free(); // Deallocate
// Return the cost
int val = paramsArg->FooObj->GetA();
return (double)(paramsArg->cost_scaling * val);
}
double Optimizer::InitOptimizer(int ptrID, void *optimParamsArg, size_t optimParamsSizeArg)
{
optimParamsPtr = ::operator new(optimParamsSizeArg);
memcpy_s(optimParamsPtr, optimParamsSizeArg, optimParamsArg, optimParamsSizeArg);
double ret_val;
// Here is where the GSL stuff would be. But I replace that with a call to CostFn to show the error
if (ptrID == 1)
{
ret_val = CostFn(optimParamsArg); // Works
}
else
{
ret_val = CostFn(optimParamsPtr); // Doesn't work
}
return ret_val;
}
// Release memory used by unmanaged variables in Optimizer
void Optimizer::FreeOptimizer()
{
if (optimParamsPtr != NULL)
{
delete optimParamsPtr;
}
}
double Foo::Optimize(int ptrID)
{
// Create and initialize params object
Params^ paramsArg = gcnew Params;
paramsArg->cost_scaling = 11;
paramsArg->FooObj = this;
// Convert Params type object to void *
void * paramsArgVPtr = GCHandle::ToIntPtr(GCHandle::Alloc(paramsArg)).ToPointer();
size_t paramsArgSize = sizeof(paramsArg); // size of memory block in bytes pointed to by void pointer
double result = 0;
// Initialize optimizer
result = fooOptimizer->InitOptimizer(ptrID, paramsArgVPtr, paramsArgSize);
// Here is where the loop that does the optimization will be. Removed from this example for simplicity.
return result;
}
int main()
{
Foo Foo1(2);
std::cout << Foo1.Optimize(1) << endl; // Use orig void * arg in line 81 and it works
std::cout << Foo1.Optimize(2) << endl; // Use memcpy_s-ed new void * public member of Optimizer in line 85 and it doesn't work
}
Just to reiterate I need to copy the params to a member in the optimizer because the optimizer will run all through the lifetime of the Foo object. So it needs to exist as long as the Optimizer object exist and not just in the scope of Foo::Optimize()
/clr support need to be selected in project properties for the code to compile. Running on an x64 solution platform.
Update 1: While trying to debug this, I got suspicious of the way I get the size of paramsArg at line 109. Looks like I am getting the size of paramsArg as size of int cost_scaling plus size of the memory storing the address to FooObj instead of the size of memory storing FooObj itself. I realized this after stumbling across this answer to another post. I confirmed this by checking the value of paramsArg after adding some new dummy double members to Foo class. As expected the value of paramsArg doesn't change. I suppose this explains why I get the error. A solution would be to write code to correctly calculate the size of a Foo class object and set that to paramsArg instead of using sizeof. But that is turning out to be too complicated and probably another question in itself. For example, how to get size of a ref class object? Anyways hopefully someone will find this helpful.
What should be considered to make a mutable class immutable? For example: Can we still have push and pop methods in an immutable stack class? Or we should simply remove any method that changes the state of the instantiated object?
The bottom line is: You'd be better to remove the method modifying the state of the instantiated object from the class. But if you want to keep it, then it should create a new object with a different state from the original one and return the new object back.
Here is a more specific answer:
There shouldn't be any methods changing the object state in an immutable class.
There are a lot of void methods which change the state of this object in a mutable class. So we should change the signature of them in a way the return a new object instead of changing "this" object's state.
Also there are a lot of non-void methods which change the state of "this" object and return the value they changed in "this". The signature of these methods should also be changed in a way that they return a new object instead of changing the state of "this". Talking about lists, usually another method (like "peek") is also needed to get a certain value. Check the sample bellow to get what do I mean:
Check out these "push" and "pop" methods for a mutable stack class:
public class Stack <E> {
…
public void push (E e) {
ensureCapacity(); // This method checks for capacity
elements[size++] = e;
}
This method adds a new element at the top of the stack and changes the state of "this" object in this way.
public E pop () {
if (size == 0) throw new IllegalStateException("Stack.pop");
E result = elements[--size];
elements[size] = null;
return result;
}
…
}
This method removes the element at the top of the stack and returns it back and changes the state of "this" object by removing the element.
Now, suppose that we need to change these methods to make this stack immutable. Let's deal with "push" method first:
"push" is a void method which changes the state of "this" object by adding a new element to it. To make the stack immutable we will create a new stack similar to "this" and add the new element to this new stack and return it back:
public class ImmStack <E> {
...
/**
* this method pushes the item to a new object and keeps the original object unchanged
* #param e The item to be pushed
* #return A new list
* #PRE An original list object is required as well as an item to be pushed
* #POST A new list would be returned
*/
#SuppressWarnings({ "unchecked", "rawtypes" }) // All items in this.elements[] are of type E
public ImmStack<E> push (E e) {
ImmStack<E> stc = new ImmStack(getNewElements());
stc.elements=ensureCapacity(stc.elements);
stc.elements[size] = e;
stc.size = size +1;
return stc;
}
"pop" method changes the state of "this" object by removing an element. To make the class immutable we will reate a new stack similar to "this" and remove the element from this new stack and return it back:
/**
* This pop method returns a new stack without the element at the top of the original list
* #return The new stack
* #POST The new stack would be returned
*/
#SuppressWarnings({ "unchecked", "rawtypes" }) // All items in this.elements[] are of type E
public ImmStack<E> pop () {
if (size == 0) throw new IllegalStateException("Stack.pop");
ImmStack<E> stc = new ImmStack(getNewElements());
stc.elements=ensureCapacity(stc.elements);
stc.elements[size-1] = null;
stc.size=size-1;
return stc;
}
The old "pop" method was returning the element at the top. We also need a new method which returns the element at the top to cover this feature:
/**
* Returns item at front of queue without removing.
* #return item at front
* #throws java.util.NoSuchElementException if empty
*/
public E top()
{
if (this.isEmpty())
{
throw new NoSuchElementException("Queue underflow");
}
return elements[size-1];
}
This was just an example. You might have more methods to change in your class to make it immutable.
If your stack is immutable, then by definition it cannot be changed. The push() and pop() methods cannot be completed.
When a method cannot be completed successfully, you can throw an exception. When a method can never be completed successfully, the standard exception to throw is UnsupportedOperationException.
For example:
public E[] push (E e) {
throw new UnsupportedOperationException();
}
EDIT:
You note in a comment that your push() method is just returning a deep copy of the stack with the new element. It looks like you're representing the immutable stack as an instance of a class, and the pushed stack as an array.
You can get the size of one of the two arrays referenced by newElements with newElements.length. So you could write code like this:
public E[] push (E e) {
E[] newElements=getNewElements();
int oldLength = newElements.length;
newElements=ensureCapacity(newElements);
int lastIndexInNewArray = oldLength;
newElements[ lastIndexInNewArray ] = e;
return newElements;
}
Below is an implementation of immutable stack in C#.
Pushing and popping give you back an entirely new stack, and Peek lets you look at the top of the stack without popping it.
Note that copying the entire stack is not necessary.
That is how immutable structures are implemented in any nontrivial cases. Nontrivial immutable structures are very useful in certain cases. Posters saying that this cannot be done are much misinformed.
The original code and more information can be found here:
https://blogs.msdn.microsoft.com/ericlippert/2007/12/04/immutability-in-c-part-two-a-simple-immutable-stack/
public interface IStack<T> : IEnumerable<T>
{
IStack<T> Push(T value);
IStack<T> Pop();
T Peek();
bool IsEmpty { get; }
}
public sealed class Stack<T> : IStack<T>
{
private sealed class EmptyStack : IStack<T>
{
public bool IsEmpty { get { return true; } }
public T Peek() { throw new Exception("Empty stack"); }
public IStack<T> Push(T value) { return new Stack<T>(value, this); }
public IStack<T> Pop() { throw new Exception("Empty stack"); }
public IEnumerator<T> GetEnumerator() { yield break; }
IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); }
}
private static readonly EmptyStack empty = new EmptyStack();
public static IStack<T> Empty { get { return empty; } }
private readonly T head;
private readonly IStack<T> tail;
private Stack(T head, IStack<T> tail)
{
this.head = head;
this.tail = tail;
}
public bool IsEmpty { get { return false; } }
public T Peek() { return head; }
public IStack<T> Pop() { return tail; }
public IStack<T> Push(T value) { return new Stack<T>(value, this); }
public IEnumerator<T> GetEnumerator()
{
for(IStack<T> stack = this; !stack.IsEmpty ; stack = stack.Pop())
yield return stack.Peek();
}
IEnumerator IEnumerable.GetEnumerator() {return this.GetEnumerator();}
}
Consider this in D programming language:
import luad.all
class C1
{
auto l1 = new LuaState;
l1["somebool"] = true;
this()
~this()
}
class C2
{
C1 cc = new C1;
auto l2 = new LuaState;
// here I want to inject l1["somebool"] to l2
}
void main() { C2 cx = new C2; }
As a solution, it is possible that I make a local variable
bool var = cc.l1["somebool"]
and then insert it in l2 - but this does not seem to be the best solution.
Is there any way to copy one lua stack defined inside a class to another stack in another class?
I don't know much about LuaD or Lua, but you can extract globals into a struct as shown in the last example on this page. And then you can set the values from the struct into l2 state.
// warning: untested
struct State
{
bool somebool;
}
State state;
l1.globals.toStruct!State(state);
foreach (member; __traits(allMembers, State))
{
l2.globals.set(member, __traits(getMember, state, member));
}
The DSL I'm working on allows users to define a 'complete text substitution' variable. When parsing the code, we then need to look up the value of the variable and start parsing again from that code.
The substitution can be very simple (single constants) or entire statements or code blocks.
This is a mock grammar which I hope illustrates my point.
grammar a;
entry
: (set_variable
| print_line)*
;
set_variable
: 'SET' ID '=' STRING_CONSTANT ';'
;
print_line
: 'PRINT' ID ';'
;
STRING_CONSTANT: '\'' ('\'\'' | ~('\''))* '\'' ;
ID: [a-z][a-zA-Z0-9_]* ;
VARIABLE: '&' ID;
BLANK: [ \t\n\r]+ -> channel(HIDDEN) ;
Then the following statements executed consecutively should be valid;
SET foo = 'Hello world!';
PRINT foo;
SET bar = 'foo;'
PRINT &bar // should be interpreted as 'PRINT foo;'
SET baz = 'PRINT foo; PRINT'; // one complete statement and one incomplete statement
&baz foo; // should be interpreted as 'PRINT foo; PRINT foo;'
Any time the & variable token is discovered, we immediately switch to interpreting the value of that variable instead. As above, this can mean that you set up the code in such a way that is is invalid, full of half-statements that are only completed when the value is just right. The variables can be redefined at any point in the text.
Strictly speaking the current language definition doesn't disallow nesting &vars inside each other, but the current parsing doesn't handle this and I would not be upset if it wasn't allowed.
Currently I'm building an interpreter using a visitor, but this one I'm stuck on.
How can I build a lexer/parser/interpreter which will allow me to do this? Thanks for any help!
So I have found one solution to the issue. I think it could be better - as it potentially does a lot of array copying - but at least it works for now.
EDIT: I was wrong before, and my solution would consume ANY & that it found, including those in valid locations such as inside string constants. This seems like a better solution:
First, I extended the InputStream so that it is able to rewrite the input steam when a & is encountered. This unfortunately involves copying the array, which I can maybe resolve in the future:
MacroInputStream.java
package preprocessor;
import org.antlr.v4.runtime.ANTLRInputStream;
public class MacroInputStream extends ANTLRInputStream {
private HashMap<String, String> map;
public MacroInputStream(String s, HashMap<String, String> map) {
super(s);
this.map = map;
}
public void rewrite(int startIndex, int stopIndex, String replaceText) {
int length = stopIndex-startIndex+1;
char[] replData = replaceText.toCharArray();
if (replData.length == length) {
for (int i = 0; i < length; i++) data[startIndex+i] = replData[i];
} else {
char[] newData = new char[data.length+replData.length-length];
System.arraycopy(data, 0, newData, 0, startIndex);
System.arraycopy(replData, 0, newData, startIndex, replData.length);
System.arraycopy(data, stopIndex+1, newData, startIndex+replData.length, data.length-(stopIndex+1));
data = newData;
n = data.length;
}
}
}
Secondly, I extended the Lexer so that when a VARIABLE token is encountered, the rewrite method above is called:
MacroGrammarLexer.java
package language;
import language.DSL_GrammarLexer;
import org.antlr.v4.runtime.Token;
import java.util.HashMap;
public class MacroGrammarLexer extends MacroGrammarLexer{
private HashMap<String, String> map;
public DSL_GrammarLexerPre(MacroInputStream input, HashMap<String, String> map) {
super(input);
this.map = map;
// TODO Auto-generated constructor stub
}
private MacroInputStream getInput() {
return (MacroInputStream) _input;
}
#Override
public Token nextToken() {
Token t = super.nextToken();
if (t.getType() == VARIABLE) {
System.out.println("Encountered token " + t.getText()+" ===> rewriting!!!");
getInput().rewrite(t.getStartIndex(), t.getStopIndex(),
map.get(t.getText().substring(1)));
getInput().seek(t.getStartIndex()); // reset input stream to previous
return super.nextToken();
}
return t;
}
}
Lastly, I modified the generated parser to set the variables at the time of parsing:
DSL_GrammarParser.java
...
...
HashMap<String, String> map; // same map as before, passed as a new argument.
...
...
public final SetContext set() throws RecognitionException {
SetContext _localctx = new SetContext(_ctx, getState());
enterRule(_localctx, 130, RULE_set);
try {
enterOuterAlt(_localctx, 1);
{
String vname = null; String vval = null; // set up variables
setState(1215); match(SET);
setState(1216); vname = variable_name().getText(); // set vname
setState(1217); match(EQUALS);
setState(1218); vval = string_constant().getText(); // set vval
System.out.println("Found SET " + vname +" = " + vval+";");
map.put(vname, vval);
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
...
...
Unfortunately this method is final so this will make maintenance a bit more difficult, but it works for now.
The standard pattern to handling your requirements is to implement a symbol table. The simplest form is as a key:value store. In your visitor, add var declarations as encountered, and read out the values as var references are encountered.
As described, your DSL does not define a scoping requirement on the variables declared. If you do require scoped variables, then use a stack of key:value stores, pushing and popping on scope entry and exit.
See this related StackOverflow answer.
Separately, since your strings may contain commands, you can simply parse the contents as part of your initial parse. That is, expand your grammar with a rule that includes the full set of valid contents:
set_variable
: 'SET' ID '=' stringLiteral ';'
;
stringLiteral:
Quote Quote? (
( set_variable
| print_line
| VARIABLE
| ID
)
| STRING_CONSTANT // redefine without the quotes
)
Quote
;