Values not getting printed outside a for loop - servlets

in my program a simple shopping application for my lab exercise, i just calculated the price of items inside a for loop but when i try to print it outside it is not getting printed...pls give me some suggestion.
for (int i = 1; i < 7; i++) {
String selection = request.getParameter("a" + i);
if (selection.equals("l")) {
price = Integer.parseInt(request.getParameter("b" + i));
total = total + price;
out.println("<h3>You have purchased the item:<br>Price is:</h3>" + price);
}
}
out.println("THE TOTAL IS"+total);
out.println("</body>");
out.println("</html>");

String selection = request.getParameter("a" + i);
//Here print the selection there is the problem
if (selection.equals("l")) ///Here alway it is false thats why you are getting this.
{
}

It gets not printed because its out of scope. Your total
variable only lives within the loop.
You have basic programming skills and know about variable scope, right?
http://www.java-made-easy.com/variable-scope.html

Related

Is there any way to collapse information inside extent report?

I have a huge extent report which shows results basis on a loop.
Sample code:
String[] values = {"1","2".....upto 1000};
for(int i =0; i < values.length; i++) {
log("comparison started for " + i+1);
if(s.contains("abc")) {
log( i + "Success for " + s)
} else {
log(i + "Fail for " + s)
}
Now in report it shows all Pass/Fail which makes the report very heavy/ bulkier.
I want to create an expand/collapse icon next to :
log("comparison started for " + i+1);
So that, for each loop, the information remain hidden, until expanded in report.

Is there an efficient algorithm for calculating which tiles are within a set walking distance of your character in a 2d grid?

Lets say that on a 2d grid of 20x20, you have your character at position (5,5).
He is able to walk up to 4 tiles in his move. However, there may be obstacles blocking your path such as a wall.
Is there any efficient / easy way for calculating exactly which tiles he would be able to walk to without checking every single possible move ( e.g. move up 0 and right 0 then move up 0 and right 1 e.t.c )?
At the moment I'm calculating the places that you can walk through with this horrific thing:
int playerx = GridPane.getRowIndex(button);
int playery = GridPane.getColumnIndex(button);
int position = playery*8+playerx;
for (int i = 0; i < 5; i++)
{
for (int j = i-4; j < 5-i; j++)
{
try
{
int expectedCollumn = playerx+j;
int actualCollumn = ((position+i+j*8)-((position+i+j*8)%8))/8;
if(expectedCollumn==actualCollumn)
{
Button temp = (Button)gridPane.getChildren()
.get(position+i+j*8);
if (!temp.getText().equals("W") &&
!temp.getText().equals("P"))
{
temp.setText("T");
}
}
actualCollumn = ((position-i+j*8)-((position-i+j*8)%8))/8;
if(expectedCollumn==actualCollumn)
{
Button temp2 = (Button)
gridPane.getChildren().get(position-i+j*8);
if (!temp2.getText().equals("W") &&
!temp2.getText().equals("P"))
{
temp2.setText("T");
}
}
}
}
}
However, its showing as if you are able to walk to the otherside of the wall and I'm not sure how I would go about fixing this.
Many thanks in advance.
For path finding, you should figure out how this works:
https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm
and then move on to A* or something more efficient.
Thanks to everyone that answered but the solution was simple
incase somehow someone finds this post and is interested it was a simple recursive call
void getReachableTiles(Tile current, Int stamina, List<Tile> visited, List<Tile> reachable) {
if (stamina <= 0) return;
List<Tile> neighbours = new List<>(current + up, current + left, ..)
for (Tile t in neighbours) {
if (!visited.contains(t)) {
visited.append(t);
if (!t.isWall()) {
reachable.append(t);
getReachableTiles(t, stamina - 1, visited, reachable);
}
}
}
}

Making smaller lower-higher console game

So im a pretty new programmer so forgive me if i make any mistakes.
I need to make a higher or lower game for my class but im a little bit stuck now.
The purpose of this whole game is to guess the number which is random generated by the computer. But here's the tricky part, the user only needs to get 8 chances to guess the number right. If not the game must end and print something like: you lost, the number was.....
I came this far;
public static void main(String[] args) {
int timesGuessed = 0;
int randomNummer = (int)(Math.random()*100);
int number;
boolean won = true;
Scanner input = new Scanner(System.in);
do{
System.out.print("Guess the number: ");
number = input.nextInt();
timesGuessed++;
if(timesGuessed == 8){
won = false;
}
if(number > randomNummer){
System.out.println("Lower!");
}
else if(number < randomNummer){
System.out.println("Higher!");
}
}
while(number != randomNummer);
if(won == true){
System.out.println("The number is guessed right in " + timesGuessed + " attemts.");
}
else{
System.out.println("You lost. The number was " + randomNummer + ".");
}
}
Now the game lets you finish even though you already had 8 chances. Thats what i want to change. It needs to stop when you failed the eight time.
Thank you for the help, it would be very appreciated.
You also need to check your won variable in the condition of your loop. You may also want to add an else so it doesn't print "Higher" or "Lower" after the final try.

OutOfMemoryError during heuristic search

I'm writing a program to solve an 8 tile sliding puzzle for an AI class. in theory this is pretty easy, but the number of node states generated is pretty large (estimated 180,000 or so). We're comparing different heuristic functions in class, so my code has to be able to handle even some very inefficient functions. I'm getting "OutOfMemoryError: Java heap space" when using java's PriorityQueue class. Heres the relevant code withing my solver function: (the error is on the openList.add(temp); line)
public void solve(char[] init,int searchOrder)
{
State initial = new State(init,searchOrder); //create initial state
openList = new PriorityQueue<State>(); //create open list
closedList = new LinkedList<State>(); // create closed list
generated = new HashSet(); //Keeps track of all nodes generated to cut down search time
openList.add(initial); //add initial state to the open list
State expanded,temp = null,solution = null; //State currently being expanded
int nodesStored = 0, nodesExpanded = 0;
boolean same; //used for checking for state redundancy
TreeGeneration:
while(openList.size() > 0)
{
expanded = openList.poll();
closedList.addLast(expanded);
for (int k = 0; k < 4; k++)
{
if (k == 0)
{
temp = expanded.moveLeft();
}
else if (k == 1)
{
temp = expanded.moveRight();
}
else if (k == 2)
{
temp = expanded.moveAbove();
}
else
{
temp = expanded.moveBelow();
}
if(temp.isSolution())
{
solution = temp;
nodesStored = openList.size() + closedList.size();
nodesExpanded = closedList.size();
break TreeGeneration;
}
if(!generated.contains(temp))
{
// System.out.println(temp.toString());
openList.add(temp); // error here
generated.add(temp);
}
// System.out.println(openList.toString());
}
}
Am I doing something wrong here, or should I be using something else to handle this quantity of data? Thanks.
By default, JVM starts with 64 MB heap space, you can increase this amount by passing a parameter like below;
java -Xmx1024m YOUR_CLASS
this gives 1024 MB heap space in memory, you can change the amount of memory as you need.
If you are using NetBeans, Netbeans doesn't scale heap space automatically, you can achieve this by following below steps;
1- Right click on your project
2- Navigate to Set Configuration -> Customize
3-Add -Xmx256m into VM Options then click Ok
Now, you can run your project with custom heap space.

Recursive Stackoverflow Error

Alright, so I'm trying to make a Java program to solve a picross board, but I keep getting a Stackoverflow error. I'm currently just teaching myself a little Java, and so I like to use the things I know rather than finding a solution online, although my way is obviously not as efficient. The only way I could think of solving this was through a type of brute force, trying every possibility. The thing is, I know that this function works because it works for smaller sized boards, the only problem is that with larger boards, I tend to get errors before the function finishes.
so char[][] a is just the game board with all the X's and O's. int[][] b is an array with the numbers assigned for the picross board like the numbers on the top and to the left of the game. isDone() just checks if the board matches up with the given numbers, and shift() shifts one column down. I didn't want to paste my entire program, so if you need more information, let me know. Thanks!
I added the code for shift since someone asked. Shift just moves all the chars in one row up one cell.
Update: I'm thinking that maybe my code isn't spinning through every combination, and so it skips over the correct answer. Can anyone verify is this is actually trying every possible combination? Because that would explain why I'm getting stackoverflow errors. On the other hand though, how many iterations can this go through before it's too much?
public static void shifter(char[][] a, int[][] b, int[] clockwork)
{
boolean correct = true;
correct = isDone(a, b);
if(correct)
return;
clockwork[a[0].length - 1]++;
for(int x = a[0].length - 1; x > 0; x--)
{
if(clockwork[x] > a.length)
{
shift(a, x - 1);
clockwork[x - 1]++;
clockwork[x] = 1;
}
correct = isDone(a, b);
if(correct)
return;
}
shift(a, a[0].length - 1);
correct = isDone(a, b);
if(correct)
return;
shifter(a, b, clockwork);
return;
}
public static char[][] shift(char[][] a, int y)
{
char temp = a[0][y];
for(int shifter = 0; shifter < a.length - 1; shifter++)
{
a[shifter][y] = a[shifter + 1][y];
}
a[a.length - 1][y] = temp;
return a;
}
Check Recursive call.and give the termination condition.
if(terminate condition)
{
exit();
}
else
{
call shifter()
}

Resources