Cinema seating arrangement - java

I'm wondering if anyone can help me, Im trying to create a simple cinema seating arrangement, where the x's are seats take and the o's are free. Problem is I cant seem to get the 0's to start where the X's finish. I'm new to java so what you see is the extent of my ability so far. Thanks for any help you can give at all!
public class Exercise4iv {
public static void main(final String[] args) {
int seats, taken, available, i, k;
seats = 50;
taken = 28;
available = seats - taken;
i = 0;
k = 0;
while (i <= taken) {
i++;
System.out.print("\t X");
if (i % 8 == 0) {
System.out.println();
}
}
while (k <= available) {
k++;
System.out.print("\t O");
if (k % 8 == 0) {
System.out.println();
}
}
}
}

if (k % 8 == 0) {
if you change this to
if ((k+taken+1) % 8 == 0) {
then it should correctly know when to print a newline

change second while loop to:
while( i<seats){
i++;
System.out.print("\t O");
if(i%8==0) System.out.println();}
}
this way the variable k is not required

Related

Why is this not working? (Java for loop condition part)

int cnt = 0, sum = 0;
for(int i = 1; ((i <= 1000) && (i%3 == 0) && (i%5 == 0)); i++){
if(cnt >= 5)
break;
System.out.println(i);
sum += i;
cnt++;
}
System.out.println(sum);
I want to get the first 5 numbers that are divisible by 3 as well as 5 between the range of [1, 1000]. This code does not shows any error but it returns 'sum' and 'cnt' both to it's default values (i.e. 0) and seems to me that it's not entering the for loop.
P.S. I am not advance level programmer. I'm trying this stuff just for exploration, so if any one could explain the actual reason behind this.
It sounds like you do not understand how a for loop works. #Silvio Mayolo and #experiment unit 1998X commented some very helpful links. I would encourage you to read through those and get comfortable with them.
In your example, your for loop has a very complex header.
for(int i = 1; ((i <= 1000) && (i%3 == 0) && (i%5 == 0)); i++){
Let's break this apart into sections.
for -- this is the keyword that starts the for loop
int i = 1; -- now you have created a variable in your loop. It is an int called i, and it has a starting value of 1.
(the termination expression) -- If the termination expression returns false, then loop stops looping. Let's see how you used it
i <= 1000 -- now you have added a rule --> in order for the for loop to perform a loop, the number i must be less than or equal to 1000. Ok, that is simple enough, you are now going to have at least 1000 valid values for i thus far.
i%3 == 0 -- now you have added another rule --> in order for the loop to perform a loop, the number i must have no remainder when divided by 3. Unfortunately, that is a problem because your starting value for i is 1, as mentioned earlier, and 1/3 DOES have a remainder. Therefore, the loop stops before it even starts.
This is your problem. If you want to check and see if i%3 == 0, you should not put that check inside of your termination expression. It should go inside of the enclosing block within the for loop. And the same applies for i%5 == 0.
Here is a runnable example to help you understand.
public class SOQ_20220516
{
public static void main(String[] args)
{
int cnt = 0;
int sum = 0;
for(int i = 1; i <= 1000; i++)
{
if(cnt >= 5)
{
break;
}
if ((i%3 == 0) && (i%5 == 0))
{
System.out.println(i);
sum += i;
cnt++;
}
}
System.out.println(sum);
System.out.println(cnt);
}
}
public class SOQ_20220516
{
public static void main(String[] args)
{
int cnt = 0;
int sum = 0;
for(int i = 1; i <= 1000; i++)
{
if(cnt >= 5)
{
break;
}
if ((i%3 == 0) && (i%5 == 0))
{
System.out.println(i);
sum += i;
cnt++;
}
}
System.out.println(sum);
System.out.println(cnt);
}
}
Blockquote

Trying to find a a perfect number within an upper limit in java without creating a method

I'm just trying to print the perfect numbers within a certain upper limit, but I get other numbers that show up, that aren't perfect numbers. I'm not trying to use a method, rather than just everything in the main loop. I need some help.
public static void main(String arg[]) {
int upper;
int sum = 0;
int i;
System.out.println("Enter upper limit");
Scanner stnd = new Scanner(System.in);
upper = stnd.nextInt();
for(int n = 1; n < upper; n++) {
i = 1;
sum = 0;
while (i <= n/2) {
if (n%i == 0) {
sum = sum + i;
}
i++;
if(sum == n) {
System.out.println(n+" is a perfect number");
break;
} else {
}
}
}
}
You've got a while loop in your code that adds up the factors of the number. The problem is that you're checking the sum, when the while loop isn't yet finished. In the case of 24, you've added up
1 + 2 + 3 + 4 + 6 + 8
which is 24, but your loop hasn't got to 12 yet.
You need to move
if(sum == n) {
System.out.println(n+" is a perfect number");
}
to after the while loop, rather than having it inside the loop.

Output generating too many rows

Ok, so what I would like to do is make a picture using asterisks. The picture is supposed to be no more or less than 10 rows and in each row is supposed to be any random amount of asterisks in the range of 1-10. The only problem I'm having is that I am not getting 10 rows, instead, I am getting anywhere from 11 - 17 rows. I'm not sure what I'm missing and I appreciate any insight you can offer me.
Thank you!
public class RandomPicture {
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
// Create a Random picture using asterisks
Random rand = new Random();
for (int count = 0; count <=2; count++)
{
if (rand.nextInt(2) == 0){
System.out.println("*");
} if (rand.nextInt(2) == 0){
System.out.println("**");
} if (rand.nextInt(2) == 0){
System.out.println("***");
} if (rand.nextInt(2) == 0){
System.out.println("****");
} if (rand.nextInt(2) == 0){
System.out.println("*****");
} if (rand.nextInt(2) == 0){
System.out.println("******");
} if (rand.nextInt(2) == 0){
System.out.println("*******");
} if (rand.nextInt(2) == 0){
System.out.println("********");
} if (rand.nextInt(2) == 0){
System.out.println("*********");
} if (rand.nextInt(2) == 0){
System.out.println("**********");
}
}
}
}
I think you are looking for something like that:
public static void main(String[] args)
{
// Create a Random picture using asterisks
Random rand = new Random();
for (int lineCnt = 0; lineCnt < 10; lineCnt++) {
for (int i = 0; i < (rand.nextInt(9) + 1); i++) {
System.out.print("*");
}
System.out.println();
}
}
Please hold in mind, that there are some more sophisticated methods to create a string with n characters (see 2804827).
Please take attention to the formatting of your code. It's awful...

Java number sequence loop

So hi i'm getting infinite loop problem i don't know whats wrong with my code i'm trying to make a number sequence format is at the bottom i think the problems are in my condition?
import java.util.Scanner;
public class tester {
public static void main(String[] args) {
Scanner x = new Scanner(System.in);
int n;
System.out.print("Enter how many numbers to display");
n = x.nextInt();
while(n!=0) { //is this right?
for ( int i = 0; i<=n; i++) {
if(i%2==0) {
n += 2;
System.out.print(n);
} else {
n += 3;
System.out.print(n);
}
}
}
}
}
Outputs i'm trying to get
Enter how many numbers to display : 5
1 3 6 8 11
2.
Enter how many numbers to display : 16
1 3 6 8 11 13 16 18 21 23 26 28 31 33 36 38 //but im getting infinite loops
// the sequence pattern is +2 then +3
The problem is here: while(n!=0) and here: for ( int i = 0; i<=n; i++). For the while loop, will keep on going until n is equal to 0. For the for loop, this will most likely keep on going for ever.
Your code has two problems:
If you provide a non negative value, this will keep on going for ever (since you are always only incrementing n).
Even if you do supply a negative number, n would n need to become exactly 0 to stop.
Depending on what you need to do, you will need to change the condition. Judging by the output, n would need to be positive and thus you would need to stipulate some upper range for n in which the while loop would stop.
EDIT: You only need to have 1 loop to do what you are after. Also, n denotes the amount of elements, thus it needs to stay fixed throughout the execution of the program. In your case, you where increasing it all the time.
Scanner x = new Scanner(System.in);
int n;
System.out.print("Enter how many numbers to display");
n = x.nextInt();
int count = 0;
int i = 1;
while (count < n) { //is this right?
if (count % 2 == 0) {
System.out.print(i + " ");
i += 2;
} else {
System.out.print(i + " ");
i += 3;
}
count++;
}
Two problems:
int stop = n; // declare one local var to stop the for loop
if (n != 0) { //switch to if condition
for (int i = 0; i <= stop; i++) {
//loop's exit condition wasn't met because 'n' was also being incremented
if (i % 2 == 0) {
n += 2;
System.out.print(n+" ");
} else {
n += 3;
System.out.print(n+" ");
}
}
}
Use 'if' condition in place of 'while' loop
You have to replace your while-loop with an if-condition like so:
import java.util.Scanner;
public class tester {
public static void main(String[] args) {
Scanner x = new Scanner(System.in);
int n;
System.out.print("Enter how many numbers to display");
n = x.nextInt();
int stop = n;
if(n!=0) { //if statement checks if n!=0
for ( int i = 0; i<=stop; i++) {
//stop replaces n because n is incremented in your for-loop
if(i%2==0) {
n += 2;
System.out.print(n);
} else {
n += 3;
System.out.print(n);
}
}
}
}
}
Based on your answers I found a solution that works:
int n;
System.out.print("Enter how many numbers to display");
n = x.nextInt();
int k = -2; // so that it starts with 1 when i add +3
int stop = n-1;
if(n!=0) {
for ( int i = 0; i<=stop; i++) {
if(i%2==0) {
k += 3;
System.out.print(k+" ");
} else {
k += 2;
System.out.print(k+" ");
}
}
}

java:implement 8 queen using depth first search

i am try to implement 8 queen using depth search for any initial state it work fine for empty board(no queen on the board) ,but i need it to work for initial state if there is a solution,if there is no solution for this initial state it will print there is no solution
Here is my code:
public class depth {
public static void main(String[] args) {
//we create a board
int[][] board = new int[8][8];
board [0][0]=1;
board [1][1]=1;
board [2][2]=1;
board [3][3]=1;
board [4][4]=1;
board [5][5]=1;
board [6][6]=1;
board [7][7]=1;
eightQueen(8, board, 0, 0, false);
System.out.println("the solution as pair");
for(int i=0;i<board.length;i++){
for(int j=0;j<board.length;j++)
if(board[i][j]!=0)
System.out.println(" ("+i+" ,"+j +")");
}
System.out.println("the number of node stored in memory "+count1);
}
public static int count1=0;
public static void eightQueen(int N, int[][] board, int i, int j, boolean found) {
long startTime = System.nanoTime();//time start
if (!found) {
if (IsValid(board, i, j)) {//check if the position is valid
board[i][j] = 1;
System.out.println("[Queen added at (" + i + "," + j + ")");
count1++;
PrintBoard(board);
if (i == N - 1) {//check if its the last queen
found = true;
PrintBoard(board);
double endTime = System.nanoTime();//end the method time
double duration = (endTime - startTime)*Math.pow(10.0, -9.0);
System.out.print("total Time"+"= "+duration+"\n");
}
//call the next step
eightQueen(N, board, i + 1, 0, found);
} else {
//if the position is not valid & if reach the last row we backtracking
while (j >= N - 1) {
int[] a = Backmethod(board, i, j);
i = a[0];
j = a[1];
System.out.println("back at (" + i + "," + j + ")");
PrintBoard(board);
}
//we do the next call
eightQueen(N, board, i, j + 1, false);
}
}
}
public static int[] Backmethod(int[][] board, int i, int j) {
int[] a = new int[2];
for (int x = i; x >= 0; x--) {
for (int y = j; y >= 0; y--) {
//search for the last queen
if (board[x][y] != 0) {
//deletes the last queen and returns the position
board[x][y] = 0;
a[0] = x;
a[1] = y;
return a;
}
}
}
return a;
}
public static boolean IsValid(int[][] board, int i, int j) {
int x;
//check the queens in column
for (x = 0; x < board.length; x++) {
if (board[i][x] != 0) {
return false;
}
}
//check the queens in row
for (x = 0; x < board.length; x++) {
if (board[x][j] != 0) {
return false;
}
}
//check the queens in the diagonals
if (!SafeDiag(board, i, j)) {
return false;
}
return true;
}
public static boolean SafeDiag(int[][] board, int i, int j) {
int xx = i;
int yy = j;
while (yy >= 0 && xx >= 0 && xx < board.length && yy < board.length) {
if (board[xx][yy] != 0) {
return false;
}
yy++;
xx++;
}
xx = i;
yy = j;
while (yy >= 0 && xx >= 0 && xx < board.length && yy < board.length) {
if (board[xx][yy] != 0) {
return false;
}
yy--;
xx--;
}
xx = i;
yy = j;
while (yy >= 0 && xx >= 0 && xx < board.length && yy < board.length) {
if (board[xx][yy] != 0) {
return false;
}
yy--;
xx++;
}
xx = i;
yy = j;
while (yy >= 0 && xx >= 0 && xx < board.length && yy < board.length) {
if (board[xx][yy] != 0) {
return false;
}
yy++;
xx--;
}
return true;
}
public static void PrintBoard(int[][] board) {
System.out.print(" ");
for (int j = 0; j < board.length; j++) {
System.out.print(j);
}
System.out.print("\n");
for (int i = 0; i < board.length; i++) {
System.out.print(i);
for (int j = 0; j < board.length; j++) {
if (board[i][j] == 0) {
System.out.print(" ");
} else {
System.out.print("Q");
}
}
System.out.print("\n");
}
}
}
for example for this initial state it give me the following error:
Exception in thread "main" java.lang.StackOverflowError
i am stuck, i think the error is infinite call for the method how to solve this problem.
any idea will be helpful,thanks in advance.
note:the broad is two dimensional array,when i put (1) it means there queen at this point.
note2:
we i put the initial state as the following it work:
board [0][0]=1;
board [1][1]=1;
board [2][2]=1;
board [3][3]=1;
board [4][4]=1;
board [5][5]=1;
board [6][6]=1;
board [7][1]=1;
[EDIT: Added conditional output tip.]
To add to #StephenC's answer:
This is a heck of a complicated piece of code, especially if you're not experienced in programming Java.
I executed your code, and it outputs this over and over and over and over (and over)
back at (0,0)
01234567
0
1 Q
2 Q
3 Q
4 Q
5 Q
6 Q
7 Q
back at (0,0)
And then crashes with this
Exception in thread "main" java.lang.StackOverflowError
at java.nio.Buffer.<init>(Unknown Source)
...
at java.io.PrintStream.print(Unknown Source)
at java.io.PrintStream.println(Unknown Source)
at Depth.eightQueen(Depth.java:56)
at Depth.eightQueen(Depth.java:60)
at Depth.eightQueen(Depth.java:60)
at Depth.eightQueen(Depth.java:60)
at Depth.eightQueen(Depth.java:60)
...
My first instinct is always to add some System.out.println(...)s to figure out where stuff is going wrong, but that won't work here.
The only two options I see are to
Get familiar with a debugger and use it to step through and analyze why it's never stopping the loop
Break it down man! How can you hope to deal with a massive problem like this without breaking it into digestible chunks???
Not to mention that the concept of 8-queens is complicated to begin with.
One further thought:
System.out.println()s are not useful as currently implemented, because there's infinite output. A debugger is the better solution here, but another option is to somehow limit your output. For example, create a counter at the top
private static final int iITERATIONS = 0;
and instead of
System.out.println("[ANUMBERFORTRACING]: ... USEFUL INFORMATION ...")
use
conditionalSDO((iITERATIONS < 5), "[ANUMBERFORTRACING]: ... USEFUL INFORMATION");
Here is the function:
private static final void conditionalSDO(boolean b_condition, String s_message) {
if(b_condition) {
System.out.println(s_message);
}
}
Another alternative is to not limit the output, but to write it to a file.
I hope this information helps you.
(Note: I edited the OP's code to be compilable.)
You asked for ideas on how to solve it (as distinct from solutions!) so, here's a couple of hints:
Hint #1:
If you get a StackOverflowError in a recursive program it can mean one of two things:
your problem is too "deep", OR
you've got a bug in your code that is causing it to recurse infinitely.
In this case, the depth of the problem is small (8), so this must be a recursion bug.
Hint #2:
If you examine the stack trace, you will see the method names and line numbers for each of the calls in the stack. This ... and some thought ... should help you figure out the pattern of recursion in your code (as implemented!).
Hint #3:
Use a debugger Luke ...
Hint #4:
If you want other people to read your code, pay more attention to style. Your indentation is messed up in the most important method, and you have committed the (IMO) unforgivable sin of ignoring the Java style rules for identifiers. A method name MUST start with a lowercase letter, and a class name MUST start with an uppercase letter.
(I stopped reading your code very quickly ... on principle.)
Try to alter your method IsValid in the lines where for (x = 0; x < board.length - 1; x++).
public static boolean IsValid(int[][] board, int i, int j) {
int x;
//check the queens in column
for (x = 0; x < board.length - 1; x++) {
if (board[i][x] != 0) {
return false;
}
}
//check the queens in row
for (x = 0; x < board.length - 1; x++) {
if (board[x][j] != 0) {
return false;
}
}
//check the queens in the diagonals
if (!SafeDiag(board, i, j)) {
return false;
}
return true;
}

Categories

Resources