Problem with a task of printing inward triangle with stars - printing

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.

Related

Why is quantity++; not the same as print(quantity++);? Is this a gotcha?

Example code:
void main() {
int quantity = 300;
print(quantity++); // 300
}
I would have thought quantity would now equal 301?
void main() {
int quantity = 300;
quantity++;
print(quantity); // 301
print(quantity++); // 301 >> In this case ++ does nothing??
}
Seems to work fine though. Why does it not work as part of a print statement? For example print(quantity+1); works fine, so why doesn't print(quantity++);?
What is happening under the hood?
quantity++ means use the value of quantity, then increment it.
If you did
print(quantity++)
print(quantity)
you'd see the value has changed.
Use ++quantity if you want the value incremented before you use it

How to clean up EPStatement#iterator() whose underlying statement is "INSERT INTO"

I'm investigating an issue with Esper 5.5.0. In the code base which I'm working on, an "INSERT INTO" statement is used and it pulls out data with EPStatement#iterator() from the "INSERT INTO" statement. It does return a non-empty Iterator (which looks weird to me though).
The issue is that the Iterator keeps accumulating data and never gets cleaned up. I'm trying to find a way to clean up the data in the Iterator but I don't know how I can do that. Its remove() method throws an Exception and deleting data from the derived window doesn't have any effect on the EPStatement object which corresponds to the "INSERT INTO" statement. How can I clean up the data in the Iterator which corresponds to the "INSERT INTO" statement? (EDIT: Not the one corresponds to the derived window, the one for the "INSERT INTO" statement itself)
Unfortunately I'm even unable to create a simple reproducer. They do something like the following but the Iterator is always empty when I try to replicate that behavior in new code. I would also like to know what is missing to replicate the behavior.
public class MyTest {
#Test
void eplStatementReturningNonEmptyIterator() {
EPServiceProvider engine = EPServiceProviderManager.getDefaultProvider();
EPRuntime rt = engine.getEPRuntime();
EPAdministrator adm = engine.getEPAdministrator();
adm.getConfiguration().addEventType(PersonEvent.class);
adm.createEPL("create window PersonEventWindow.win:keepall() as PersonEvent");
EPStatement epl = adm.createEPL("insert into PersonEventWindow select irstream * from PersonEvent");
rt.sendEvent(new PersonEvent("foo", 1));
rt.sendEvent(new PersonEvent("bar", 2));
// passes, but this question is not about this one
assert count(rt.executeQuery("select * from PersonEventWindow").iterator()) == 2;
// This question is about this one, I want to clean up the Iterator which epl.iterator() returns
assert count(epl.iterator()) == 2;
// (this assertion ^ fails actually; I cannot even replicate the issue)
}
private static int count(Iterator<?> it) {
int count = 0;
while (it.hasNext()) {
it.next();
count++;
}
return count;
}
public static class PersonEvent {
private String name;
private int age;
public PersonEvent(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
}
This code creates named window PersonEventWindow#keepall that keeps all events that ever arrived (its what keepall means). The code executes a fire-and=forget query rt.executeQuery that selects all events from the named window and the iterator returned provides each event. Iterators I don't think allow remove. One option, use a time window that automatically removes data from the named window like for example PersonEventWindow#time(10) which keeps only the last 10 seconds. Another option, execute a fire-and-forget query like rt.executeQuery("delete from PersonEventWindow") and that deletes all events from the named window.
It turned out that the Iterator for "insert into..." returns elements if it selects from a window. In order to clean up the Iterator, we can delete data from the window which the "insert into" query selects data from.
The following code verifies my explanation I believe:
public class MyTest3 {
EPServiceProvider engine;
EPAdministrator epa;
EPRuntime epr;
#BeforeEach
void setUp() {
engine = EPServiceProviderManager.getDefaultProvider();
epa = engine.getEPAdministrator();
epr = engine.getEPRuntime();
}
#Test
#DisplayName("The Iterator gets cleaned up by delete from MyWindow")
void cleanUpIterator() {
epa.getConfiguration().addEventType(MyEvent.class);
epa.createEPL("create window MyWindow.std:unique(id) as MyEvent");
epa.createEPL("insert into MyWindow select id from MyEvent");
epr.sendEvent(new MyEvent(1));
epr.sendEvent(new MyEvent(2));
EPStatement insertIntoAnotherWindow = epa.createEPL("insert into AnotherWindow select id from MyWindow");
assertThat(count(insertIntoAnotherWindow.iterator())).isEqualTo(2); // this returns the events surprisingly
epr.executeQuery("delete from MyWindow");
assertThat(count(insertIntoAnotherWindow.iterator())).isEqualTo(0); // now it's empty
}
public static class MyEvent {
private final int id;
public MyEvent(int id) {
this.id = id;
}
public int getId() {
return id;
}
}
#AfterEach
void tearDown() {
engine.destroy();
}
private static int count(Iterator<?> it) {
int count = 0;
while (it.hasNext()) {
it.next();
count++;
}
return count;
}
}

Code to locate a specific item in a linked list and remove it

For my Computer Science course we are needing to create 2 functions. One function needs to locate the serial position of the item being searched for (an int in this case) and the index of the previous item. The locateNode function (the function described above) needs to be used within the Remove function as well as other functions already written by the professor in the class. Remove is simply supposed to take the item before the one being removed and make it point to the item that was being pointed to by the removed item. Finally it will take the removed node and push it into an avail list within the same array (essentially there are 2 linked lists in the one array.) My functions are giving me the wrong output and I currently do not know which is wrong or if both functions are wrong.
void SortedList::Remove(ItemType anItem, bool& success)
// IN OUT
{
int previous, position;
success=locateNode(anItem, previous, position);
cerr<<success<<endl;
if (success)
{
int current=list[0].next;
list[previous].next=list[list[previous].next].next;
for (int i=1; i<position; i++)
{
current=list[i].next;
}
PushAvail(current);
}
} // end Remove
bool SortedList::locateNode(
ItemType anItem, int& previous, int& position) const
{
position=1;
previous=0;
int current=list[0].next;
bool isPresent = false;
for (int count=1; count <= size; count++)
{
if (list[current].item >= anItem)
{
if ( list[current].item == anItem)
{
cerr<<"Position "<< position<< endl;
cerr<<"Previous "<< previous<< endl;
isPresent = true;
}
return isPresent;
}
position++;
previous=list[previous].next;
current=list[current].next;
}
return isPresent;
}

Method declaration in java

I have a question regarding this code, you can see in some methods that there are comments with a return, that is because I think I have to use a return method instead of a void method. My teacher told me to transform them to a void class, but isn't a method which modifies field variables suposed to return something? I'm in doubt because sometimes my teacher seems to not know so much about programming or has some doubts so, thank for your help beforehand.
public class ArraysClass {
private int[] array;
private int arrayLength;
public ArraysClass() {
setArrayLength();
array = new int[arrayLength];
}
public int setArrayLength() {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number to set the length of the array:");
arrayLength = scanner.nextInt();
System.out.println();
return arrayLength;
}
public void fillArray() {
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < arrayLength; i++) {
System.out.println("Type a number to fill position " + i);
array[i] = scanner.nextInt();
}
// return array;
System.out.println();
}
public void findNumber() {
Scanner scanner = new Scanner(System.in);
int tofind, position;
System.out.println("Enter a number to search it in the array:");
tofind = scanner.nextInt();
position = Arrays.binarySearch(array, tofind);
if (position < 0) {
System.out.println("We did not find your number.");
} else {
System.out.println("The number you typed is in the next position: " + position);
}
System.out.println();
}
public void fillMethod() {
Scanner scanner = new Scanner(System.in);
int tofill;
System.out.println("Enter a number to fill the entire array with:");
tofill = scanner.nextInt();
Arrays.fill(array, tofill);
System.out.println();
//return array;
}
public void Sortmethod() {
Arrays.sort(array);
//return array;
}
private void showArray() {
System.out.println("Showing the array...");
for (int i = 0; i < arrayLength; i++) {
System.out.println(array[i]);
}
System.out.println();
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArraysClass arrayobj = new ArraysClass();
int choose;
do {
do {
System.out.println("1-Fill the array");
System.out.println("2-Find a number in the array");
System.out.println("3-Fill the entire array with a number");
System.out.println("4-Sort the array");
System.out.println("5-Show the array");
System.out.println("6-Exit");
System.out.println("Which one do you want to use?:");
choose = scanner.nextInt();
} while (choose < 1 && choose > 6);
switch (choose) {
case 1:
arrayobj.fillArray();
break;
case 2:
arrayobj.findNumber();
break;
case 3:
arrayobj.fillMethod();
break;
case 4:
arrayobj.Sortmethod();
break;
case 5:
arrayobj.showArray();
break;
case 6:
break;
}
} while (choose != 6);
}
}
In general, a method should return something if you need value from it. It is an approach used by some programmers to return a boolean even for do-only methods for success or failure or an int, for a status code. I do not follow these approaches. When I implement a method, I always ask myself how would I like to use that method. If I need a value from it, then it will have its type. Otherwise, it will be void. Let us see your methods:
setArrayLength: In general, from this name I would expect that you pass an int to it, representing the length and the method to be void. This is very common for setters, but here you are reading the actual value inside the method which is clearly inferior compared to having an int parameter, as your method will be useless if one wants to set the array length using a value not read from the console.
fillArray: I would expect this to be void, so I agree with its declaration, but again, the reading part should not be here.
findNumber: Should get the number to be found as a parameter and return an int, which represents its index, -1 if not found.
fillMethod: Should be void and should have an int parameter, which represents the value to be used to fill the array.
sortMethod: ok, maybe return the resulting array, but depends on your needs.
showArray: I would expect a PrintStream there, you will not necessarily output to System.out
General mistake: You mix methods with in/out operations to the console, the code is not general enough this way.

How does one obtain data that has been returned from a method? (Java)

This might be a really stupid question but what happens to data that is returned from a method? For example, if I have a method that adds two numbers and I tell it to return the sum, how would I access that information from the place where the method was called?
Assuming your question is related with java.
You could assign the whole method to a new variable.
public class Test {
public static void main(String args[]){
int value1=2;
int value2=5;
int sum=sum(value1,value2);
System.out.println("The sum is :"+ sum);
}
public static int sum(int value1,int value2){
return value1+value2;
}
}
What is actually happening, is that the method signature sum(value1,value2) holds the result of the 2 numbers summation. There is also another way of writing the code inside the method but the result will be the same.
For example:
public class Test {
public static void main(String args[]){
int sum=sum(2,5);
System.out.println("The sum is :"+ sum);
}
public static int sum(int value1,int value2){
int sum=value1+value2;
return sum;
}
}
P.S. You could try to use the above samples directly. They will compile and run.
In most languages, you access the result of a function by putting the function call on the right hand side of an assignment expression.
For example, in Python, you can assign the result of calling the built-in len function on a list to a variable called x by doing the following:
x = len([1, 2, 3])

Resources