How to make hollow box using two for loops - java

Use nested for loops statements to draw hallow boxes of "*"s. The boxes have the same number of rows and columns and this number should be input from the user (valid range: 5 to 21). I'm having trouble coming up with a way to make the box hollow. this is what i have for the code and it comes as a complete square, but i need it to be hollow or just the border.
System.out.println("How many rows/columns(5-21)?");
rows=input.nextInt();
while(rows<5||rows>21){
System.out.println("Out of range. Reenter: ");
rows=input.nextInt();
}
for(m=1;m<=rows;m++){
for(c=1;c<=rows;c++){
System.out.print("*");
}
System.out.println();
}
the output should look like this:
How many rows/columns (5-21)? 25
Out of range. Reenter: 7
*******
* *
* *
* *
* *
* *
*******

You need to print only some of the *s, so add a test before the print("*"). One option would be to explicitly test the four conditions (top, bottom, left, right) and OR them together logically:
if( (m==1) || //top
(m==rows) || //bottom
(c==1) || //left
(c==rows) //right
) {
System.out.print("*");
} else {
System.out.print(" ");
}
Each m== test or c== test identifies one piece of the square. Since the four tests
are ORed together, the if() is true (and a * is printed) if any one of the four tests is true. If none of them are true, the else runs and prints a space.
I also recommend renaming m to rowIndex and c to colIndex or something. When you come back to the code a week or two later, more descriptive names will make it easier to pick up where you left off. (Ask me how I know!)

import java.util.Scanner;
public class icibos {
public static void main(String[] args) {
Scanner gir = new Scanner(System.in);
System.out.print("Karenin kenarını girin: ");
int kenar = gir.nextInt();
for (int i = 1; i <= kenar; i++) {
for (int j = 1; j <= kenar; j++) {
if (i == 1 || i == kenar || j == 1 || j == kenar)
System.out.print("*");
else
System.out.print(" ");
}
System.out.println();
}
}
}

for (int i=1;i<=lgh;i++){
for (int a=1;a<=lgh;a++){
if(i>1 && i<lgh && a>1 && a<lgh)
System.out.print(" ");
else
System.out.print("*");
}
System.out.println("");
}

Try this , its bit hard code.
Working Example here
String myStars="*******";
String oneStar="*";
int count=0;
System.out.println(myStars);
count++;
while(count<=7)
{
System.out.println(oneStar+" "+oneStar);
count++;
}
System.out.print(myStars);

You can try this
Example is Here
String pattern;
int noOfTimes;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the pattern to print : ");
pattern = scanner.nextLine();
System.out.print("Enter number of times it should get printed : ");
noOfTimes = scanner.nextInt();
for(int i=1; i<=noOfTimes; i++) {
System.out.println();
if(i==1 || i==noOfTimes) {
for(int j=1; j<=noOfTimes; j++){
System.out.print(pattern+" ");
}
}
else {
for(int k=1; k<=noOfTimes;k++) {
if(k==1 || k == noOfTimes) {
System.out.print(pattern + " ");
}
else {
System.out.print(" ");
}
}
}
}

import java.util.Scanner;
public class holsqr{
public static void main(String args[]){
Scanner ma=new Scanner(System.in);
System.out.print("Enter the number:");
int max=ma.nextInt();
for(int i=1;i<=max;i++){
for(int j=1;j<=max;j++){
if((i==1)||(i==max)){
System.out.print("#");
}else{
if(j==1||j==max){
System.out.print("#");
}
else{
System.out.print(" ");
}
}
}
System.out.println();
}
}
}

It pretty simple, using two while loop:
public static void main(String[] args) {
int size = 0;
int r = 0;
String star = "*";
String space = " ";
System.out.print("Input size of side of square: ");
Scanner input = new Scanner(System.in);
size = input.nextInt();
while (r < size) {
int c = 0;
while (c < size) {
System.out.print(r > 0 && r < size - 1 && c > 0 && c < size - 1 ? space : star);
++c;
}
System.out.println();
++r;
}
}

Related

How can I update the data inside of an array to be false instead of true?

This program is to reserve time available from three different games. So far in the program, I had printed the two different menus on that shows the game and the other one shows the available time Slots. the Program is set to be an infinite loop so other users have the chance to pick a game and reserve time as well. This is where my problem comes, the second time the program runs it stills displays the time that was previously picked.
import java.util.Scanner;
public class GameReservationSystem {
public static Scanner input = new Scanner(System.in);
static String[] timeSlots = {"1-2pm", "2-3pm", "3-4pm", "4-5pm"};
static String[] Games = {"Backganmon", "Chess", "Dominoes"};
static boolean avaliableTime[][] = new boolean[Games.length][timeSlots.length];
static int userChoice;
public static void main(String[] args) {
for (int i = 0; i < Games.length; i++) {
for (int j = 0; j < timeSlots.length; j++) {
avaliableTime[i][j] = true;
}
}
mainMenu();
}
public static void mainMenu() {
while (true) {
characterPrint('-');
for (int i = 0; i < Games.length; i++) {
System.out.print(i + ". ");
System.out.println(Games[i]);
}
characterPrint('-');
System.out.println("input a number to choose your game!");
userChoice = input.nextInt();
reserveMenu(userChoice);
}
}
public static void reserveMenu(int userChoice) {
int reserveTime = 0;
if (userChoice >= 0 && userChoice < Games.length) {
characterPrint('-');
System.out.println("This are the avaliable times to play" + Games[userChoice]);
for (int i = 0; i < timeSlots.length; i++) {
System.out.print(i + ". ");
System.out.println(timeSlots[i]);
}
characterPrint('-');
System.out.println("Input a number to reserve a time: ");
reserveTime = input.nextInt();
}
if (reserveTime >= 0 && reserveTime < timeSlots.length) {
avaliableTime[userChoice][reserveTime] = false;
System.out.println("You have succesfully reserve a time to play " + Games[userChoice] + " at" + timeSlots[reserveTime]);
}
}
public static void characterPrint(char c) {
for (int i = 0; i < 30; i++) {
System.out.print(c);
}
System.out.println();
}
}
In fact, your problem isn't that you didn't change the boolean values in your table from true to false. Instead, your problem is that you didn't use information in the table before you make reservations. What you were doing is to always set that value to false and print "succesfully reserve", without checking whether that time has already been reserved by someone else.
Try the following code. I also add some codes to handle invalid input number.
By the way, "avaliableTime" looks like a typo, so I changed it to "availableTime".
import java.util.Scanner;
public class GameReservationSystem {
public static Scanner input = new Scanner(System.in);
static String[] timeSlots = {"1-2pm", "2-3pm", "3-4pm", "4-5pm"};
static String[] Games = {"Backganmon", "Chess", "Dominoes"};
static boolean availableTime[][] = new boolean[Games.length][timeSlots.length];
static int userChoice;
public static void main(String[] args) {
for (int i = 0; i < Games.length; i++) {
for (int j = 0; j < timeSlots.length; j++) {
availableTime[i][j] = true;
}
}
mainMenu();
}
public static void mainMenu() {
while (true) {
characterPrint('-');
for (int i = 0; i < Games.length; i++) {
System.out.print(i + ". ");
System.out.println(Games[i]);
}
characterPrint('-');
System.out.println("input a number to choose your game!");
userChoice = input.nextInt();
reserveMenu(userChoice);
}
}
public static void reserveMenu(int userChoice) {
int reserveTime = 0;
if (userChoice >= 0 && userChoice < Games.length) {
characterPrint('-');
System.out.println("This are the avaliable times to play" + Games[userChoice]);
for (int i = 0; i < timeSlots.length; i++) {
if (availableTime[userChoice][i]) {
//if false, this time is not available and should not be displayed.
System.out.print(i + ". ");
System.out.println(timeSlots[i]);
}
}
characterPrint('-');
System.out.println("Input a number to reserve a time: ");
reserveTime = input.nextInt();
}else {
//handle unexpected game number.
System.out.println("Invalid game number, please try again.");
}
if (reserveTime >= 0 && reserveTime < timeSlots.length) {
//what if someone typed 0 although 0 wasn't displayed? (0 wasn't displayed, for example, because it has been reserved by someone else.)
//So you should check whether it is available by the following line.
if (availableTime[userChoice][reserveTime]) {
//if true, this time hasn't been reserved, so it is a valid input.
availableTime[userChoice][reserveTime] = false;
System.out.println("You have succesfully reserve a time to play " + Games[userChoice] + " at" + timeSlots[reserveTime]);
}else {
//if already false, this time has already been reserved by someone else,
//thus it is an invalid input.
System.out.println("This time has already been reserved, please try again.");
}
}else {
System.out.println("Invalid time number, please try again.");
}
}
public static void characterPrint(char c) {
for (int i = 0; i < 30; i++) {
System.out.print(c);
}
System.out.println();
}
}

Output oversize 2D array

I'm doing an assignment (no I'm not asking you guys to do it for me I just need help with a small part)
Basically I have an oversize 2D array that needs to be outputed when the user chooses.
I'll include all of my code so far but be warned, it's too long. I would appreciate any help, thanks
import java.util.Scanner;
import java.io.FileInputStream;
import java.io.IOException;
public class customerDatabase {
public static Scanner scnr = new Scanner(System.in);
public static void main(String[] args) throws IOException {
FileInputStream fileByteStream = new FileInputStream("myfile.txt");
Scanner inFS = new Scanner(fileByteStream);
char choice = 'z';
int i = 0;
String[][] customerInfo = new String[100][5];
int arrayLength = 0;
while(inFS.hasNext()){
customerInfo[i][0]=inFS.next(); //first name
customerInfo[i][1]=inFS.next(); //last name
customerInfo[i][2]=inFS.next(); //email
customerInfo[i][3]=inFS.nextLine(); //phone number
++i;
++arrayLength;
}
while(choice != 'q'){
choice = printMenu();
}if(choice == 'o'){
outputDatabase(customerInfo,arrayLength);
}
}
public static char printMenu(){
char userChar = 'z';
String choiceString;
System.out.println();
System.out.println("MENU");
System.out.println("o - Output customer database");
System.out.println("s - Sort by name");
System.out.println("a - Add a customer");
System.out.println("r - Remove a customer");
System.out.println("u - Update customer information");
System.out.println("f - Find a customer");
System.out.println("q - Quit");
System.out.println();
while((userChar != 'o') && (userChar != 's') && (userChar!= 'a') && (userChar != 'r') && (userChar != 'u') &&(userChar != 'f') && (userChar!= 'q')){
System.out.println("Choose an option:");
choiceString = scnr.nextLine();
userChar = choiceString.charAt(0);
}
return userChar;
}
public static void outputDatabase(String[][] userArray, int arraySize){
int i;
int j;
for(i=0; i < arraySize; ++i) {
for(j=0; j < arraySize; ++j) {
System.out.print(userArray[i][j]);
}
}
}
}
Then there's a text file which includes names and emails and phone numbers (which is what is being inserted into the array that is being output).
Basically I have an oversize 2d array that needs to be output when the
user chooses for it to be.
You have four properties i.e. First Name, Last Name, Email & Phone Number and hence, your inner loop should only go from index zero to index three,
for(int i=0; i < arraySize; ++i) {
for(int j=0; j < 4; ++j) {
System.out.print(userArray[i][j]);
}
}
Currently, you are setting it to arraySize which will result in an exception if arraySize is greater than four.

Play again feature issue

The program works the way it should but gets user's input on whether they want to play again or not and then does nothing after that. I am setting all of the original input values to 0 which is probably why. How can I get a new input from the user when they want to play again. If someone knows a better way make this program without arrays I would greatly appreciate it if you could post the code below.
import java.util.Scanner;
import java.util.*;
public class Shapes {
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
System.out.print("You can view any of the following shapes: ");
System.out.print("\n1 Square");
System.out.print("\n2 Right-angle Triangle");
System.out.print("\n3 Pyramid");
System.out.print("\n4 Hourglass");
System.out.print("\n5 Diamond");
System.out.print("\nEnter a integer to choose a shape: ");
String shape = userInput.nextLine();
System.out.print("\nEnter the height of the shape: ");
int inputOne = userInput.nextInt();
System.out.print("Enter a character: ");
char ch = userInput.next().charAt(0);
System.out.println("\n");
do {
if (shape.equalsIgnoreCase("1")) {
square(ch, inputOne);
System.out.println();
}
if (shape.equalsIgnoreCase("2")) {
triangle(ch, inputOne);
System.out.println();
}
if (shape.equalsIgnoreCase("3")) {
pyramid(ch, inputOne);
System.out.println();
}
if (shape.equalsIgnoreCase("4")) {
diamond(ch, inputOne);
System.out.println();
}
if (shape.equalsIgnoreCase("5")) {
hourglass(ch, inputOne);
System.out.println();
}
shape = "0";
inputOne = 0;
ch = 0;
} while (playAgain());
}
private static boolean playAgain() {
Scanner keyboard = new Scanner(System.in);
System.out.print("Play again? (Y/N): ");
String replay = keyboard.nextLine();
return replay.equalsIgnoreCase("Y");
}
public static void square(char c, int n) {
char[] a = new char[n];
Arrays.fill(a, c);
for (; n-- > 0;)
System.out.println(a);
}
public static void triangle(char c, int n) {
for (int i = 1; i <= n; i++) {
char[] a = new char[i];
Arrays.fill(a, c);
System.out.println(a);
}
}
public static void pyramid(char c, int n) {
for (int i = 0; i < n; i++) {
while (true) {
char[] s = new char[n - i - 1];
Arrays.fill(s, ' ');
System.out.print(s);
char[] a = new char[i * 2 + 1];
Arrays.fill(a, c);
System.out.println(a);
}
}
}
public static void diamond(char c, int n) {
boolean odd = n % 2 == 1;
n++;
int mid = n / 2;
int mi = mid;
if (odd)
mi--;
for (int y = 1; y < n; y++) {
for (int x = 1; x < n; x++) {
System.out.print((Math.abs(x + y - n) > mi || Math.abs(x - y) > mi) ? ' ' : c);
}
System.out.println();
}
}
public static void hourglass(char c, int n) {
boolean odd = n % 2 == 1;
if (odd)
n++;
int mid = n / 2;
for (int y = 0; y < n; y++) {
if (odd && y == mid)
continue;
for (int x = 1; x < n; x++) {
int a = 0;
if (Math.abs(x + y - mid) >= mid)
a++;
if (Math.abs(x - y - mid) >= mid)
a++;
System.out.print((a % 2 == 0) ? c : ' ');
}
System.out.println();
}
}
}
You only prompt the user for input once and you set them to 0. On the next iteration of the loop, shape is 0 so none of the if statements evaluate to true and thus your program does nothing.
Retrieve the user's input inside the loop and remove zeroing-out the variables:
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
do {
System.out.print("You can view any of the following shapes: ");
System.out.print("\n1 Square");
System.out.print("\n2 Right-angle Triangle");
System.out.print("\n3 Pyramid");
System.out.print("\n4 Hourglass");
System.out.print("\n5 Diamond");
System.out.print("\nEnter a integer to choose a shape: ");
String shape = userInput.nextLine();
System.out.print("\nEnter the height of the shape: ");
int inputOne = userInput.nextInt();
System.out.print("Enter a character: ");
char ch = userInput.next().charAt(0);
System.out.println("\n");
if (shape.equalsIgnoreCase("1")) {
square(ch, inputOne);
System.out.println();
}
if (shape.equalsIgnoreCase("2")) {
triangle(ch, inputOne);
System.out.println();
}
if (shape.equalsIgnoreCase("3")) {
pyramid(ch, inputOne);
System.out.println();
}
if (shape.equalsIgnoreCase("4")) {
diamond(ch, inputOne);
System.out.println();
}
if (shape.equalsIgnoreCase("5")) {
hourglass(ch, inputOne);
System.out.println();
}
} while (playAgain());
}
You need to prompt for the user input inside of the do/while loop. Right now you are prompting the user right above the loop - so it only happens once in your code.
//move this stuff into the do/while
Scanner userInput = new Scanner(System.in);
System.out.print("You can view any of the following shapes: ");
System.out.print("\n1 Square");
System.out.print("\n2 Right-angle Triangle");
System.out.print("\n3 Pyramid");
System.out.print("\n4 Hourglass");
System.out.print("\n5 Diamond");
System.out.print("\nEnter a integer to choose a shape: ");
String shape = userInput.nextLine();
System.out.print("\nEnter the height of the shape: ");
int inputOne = userInput.nextInt();
System.out.print("Enter a character: ");
char ch = userInput.next().charAt(0);
System.out.println("\n");
do {
^^^^ move that stuff in here
}while(playAgain())
It's also worth noting that this would be easy to discover if you simply step through your code in a debugger.

Java 2D Seating Array for a Theater

import java.util.*;
/**
* Write a description of class TheaterApp here.
*
* #author (your name)
* #version (a version number or a date)
*/
public class TheaterApp {
static int [][] seats = {
{10,10,10,10,10,10,10,10},
{10,10,10,10,10,10,10,10},
{10,10,20,20,20,20,10,10},
{20,20,30,30,30,30,20,20},
{30,30,40,40,40,40,30,30},
{30,40,40,50,50,40,40,40}};
/**
* Constructor for objects of class TheaterApp
*/
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
String ans;
do {
System.out.print("Enter request, please (or 'help' or 'quit') ");
ans = input.next();
if (ans.equals("help")) {
System.out.println("Possible commands");
System.out.println("price <price>");
System.out.println("seat <row> <seat>");
System.out.println("left");
System.out.println("remaining <price>");
System.out.println("print");
System.out.println("quit");
System.out.println("help");
} else if (ans.equals("price")) {
int p = input.nextInt();
for (int i = 0; i < seats.length; i++) {
for (int j = 0; j < seats[i].length; j++) {
if (seats[i][j] == 0) {
System.out.println("Next available seat at position: " + i + " " + j);
}
}
}
// Find the 'best' seat at the given price
} else if (ans.equals("seat")) {
int r = input.nextInt();
int c = input.nextInt();
int k;
int i;
int j;
for (int l = 0; l < 6; l++) {
k = 1;
for(i=0;i<6;i++) {
for(j=0;j<8;j++) {
if (k == input.nextInt()) {
// check if the seat has already been reserved
if (seats[i][j]== 0) {
System.out.println("That seat has already been reserved");
}
// if its not reserved then reserve it
else {
seats[i][j]= 0;
}
}
k++;
System.out.println(seats[i][j]);
}
}
}
// Reserve the given row and seat, if possible
} else if (ans.equals("left")) {
// Print the total available seats
} else if (ans.equals("remaining")) {
int p = input.nextInt();
// Print the total available seats at this price
} else if (ans.equals("print")) {
for (int r = 0; r < seats.length; ++r) {
for (int s = 0; s < seats[r].length; ++s) {
System.out.print(seats[r][s] + " ");
}
System.out.println();
}
} else if (!ans.equals("quit")) {
System.out.println("Come again?");
}
} while (!ans.equals("quit"));
System.out.println("Good bye");
}
}
This array represents theater seats and I have to mark sold seats by changing the price to 0. I also have to make sure seats are open when a user asks for a a certain spot, and when a user enters a price, find any seats that are open.
So I'm pretty sure I figured out the code for finding the best seat at any given price. I can't figure out how to do the remaining code.
I just need to find out how to print the total available seats and also how to print the total available seats when a certain price is entered.
Thanks.
You'd just use nested for loops, like you did before, except now you'd have some kind of a availableSeats counter you'll increment every time a seat meets a certain condition.
Like so:
int availableSeats = 0;
for(i=0;i<6;i++) {
for(j=0;j<8;j++) {
if(seats[i][j] == sometargetprice){
availableSeats++;
}
}
}
System.out.println("Total of " + availableSeats + " are available.");
Unless I'm not understanding the problem correctly.

Loop the program until 0(exit)(java)

I have this java code that basically just prints a christmas tree of X height.However, the program ask for the number, then print the tree and then just end.I would like it to loop until I enter 0,wich would end the program,and also I would like to make it print only if the number entered is from 1-40(not over 40).Im begining in the java world and I dont know how to do that.Heres my code for now:
public class xtree {
public static void main(String[] args)
{
Scanner scan = new Scanner(in);
out.print("please enter a number: ");
int temp = scan.nextInt();
int x = (temp-1)*2 +1;
int y = x/2;
int z = 1;
for(int i=0; i<temp-1; i++)
{
for(int j=0; j<=y; j++)
{
out.print(" ");
}
for(int k = 0; k<z; k++)
{
out.print("*");
}
out.println();
y--;
z+=2;
}
for(int i =0; i<=x/2; i++)
{
out.print(" ");
}
out.println("*");
}
}
Thank you, im a beginner to java so please be lenient ;)
Well, I would separate the method out into two:
A printChristmasTree method, which accepts the height as a parameter
Your main method, which just deals with taking user input and calling printChristmasTree or exiting
Most of your current main method would go into the printChristmasTree, and main would be a loop. Something like:
public static void main(String[] args) {
Scanner scan = new Scanner(in);
while (true) {
System.out.print("Please enter a number (0-40): ");
int height = scan.nextInt();
if (height == 0) {
// Exit the program
return;
} else if (height >= 1 && height <= 40) {
printChristmasTree(height);
} else {
System.out.println("Invalid input.");
}
}
}
There are other approaches you could use instead of returning from a while (true) loop, but this looks the simplest to me.
The separation of the "taking input" from the "printing the Christmas tree" aspects leads to much more readable code than keeping them combined, in my view - and it's more flexible in terms of things like writing a different program to print all valid Christmas trees.
Use a while loop:
Scanner scan = new Scanner(System.in);
System.out.print("please enter a number: ");
int temp = scan.nextInt();
while (temp>0) {
int x = (temp-1)*2 +1;
int y = x/2;
int z = 1;
for(int i=0; i<temp-1; i++)
{
for(int j=0; j<=y; j++)
{
System.out.print(" ");
}
for(int k = 0; k<z; k++)
{
System.out.print("*");
}
System.out.println();
y--;
z+=2;
}
for(int i =0; i<=x/2; i++)
{
System.out.print(" ");
}
System.out.println("*");
temp = scan.nextInt();
}
Here's the code for doing that:
public class xtree {
public static void main(String[] args)
{
int temp;
do{
Scanner scan = new Scanner(in);
out.print("please enter a number: ");
temp = scan.nextInt();
if(temp >= 1 && temp <= 40){ //don't display a tree higher than 40
int x = (temp-1)*2 +1;
int y = x/2;
int z = 1;
for(int i=0; i<temp-1; i++)
{
for(int j=0; j<=y; j++)
{
out.print(" ");
}
for(int k = 0; k<z; k++)
{
out.print("*");
}
out.println();
y--;
z+=2;
}
for(int i =0; i<=x/2; i++)
{
out.print(" ");
}
out.println("*");
}else if(temp != 0){
out.print("Please enter a number between 1 and 40!");
}
}while(temp != 0);
}
}

Categories

Resources