Printing A Diamond Shape In Java, Based On User Input - java

I have a problem with a program I am trying to write. A user inputs a positive odd integer, otherwise the program prompts the user until they do. When they do, the program prints a diamond shape corresponding to the user input.
I have this piece so far that prints the left hand diagonal of such a figure, but cannot figure out how to print the rest of it. Here is the code:
import java.util.Scanner;
public class DrawingProgram {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Welcome to the drawing program:");
System.out.println("Please Input a Positive Odd Integer:");
char userAnswer;
int userInput;
userInput = keyboard.nextInt();
if (userInput%2 == 0){
System.out.println("That is not a Positive Odd Integer!");
}
else if (userInput < 0){
System.out.println("That is not a Positive Odd Integer");
}
else if (userInput%2 == 1){
for (int row = 1; row<= userInput; row++){
for (int col = 1; col<= userInput; col++ ){
if (row+col==userInput-1 )
System.out.print( "*");
else
System.out.print( " ");
}
System.out.print("\n");
}
}
}
}

A user inputs a positive odd integer, otherwise the program prompts
the user until they do
You need to scan in a loop
do
{
userInput = keyboard.nextInt();
if (userInput % 2 == 0)
System.out.println("That is not an Odd Integer!");
if(userInput < 0)
System.out.println("That is not a Positive Odd Integer");
} while(userInput < 0 || userInput %2 == 0);
Now you can remove that validation else if (userInput%2 == 1){
Now the first thing I realize when checking at your loop is if (row+col==userInput-1 || ) which won't compile as you have a comparison operator with nothing following.
Note that you can replace System.out.print("\n"); with System.out.println("") but that's not really important...
Now replace your loop condition so that they start as 0
for (int row = 0; row <= userInput; row++){
for (int col = 0; col <= userInput; col++ ){
Now since you want a Diamond, you need to have 4 diagonal, so 2 loops (one for top and bottom)...
for (int i = 1; i < userInput; i += 2)//Draw the top of the diamond
{
for (int j = 0; j < userInput - 1 - i / 2; j++)//Output correct number of spaces before
{
System.out.print(" ");
}
for (int j = 0; j < i; j++)//Output correct number of asterix
{
System.out.print("*");
}
System.out.print("\n");//Skip to next line
}
for (int i = userInput; i > 0; i -= 2)//Draw the bottom of the diamond
{
for (int j = 0; j < userInput -1 - i / 2; j++)
{
System.out.print(" ");
}
for (int j = 0; j < i; j++)
{
System.out.print("*");
}
System.out.print("\n");
}
So the final code would look like this
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Welcome to the drawing program:");
System.out.println("Please Input a Positive Odd Integer:");
char userAnswer;
int userInput;
do
{
userInput = keyboard.nextInt();
if (userInput % 2 == 0)
{
System.out.println("That is not an Odd Integer!");
}
if (userInput < 0)
{
System.out.println("That is not a Positive Odd Integer");
}
} while (userInput < 0 || userInput % 2 == 0);
for (int i = 1; i < userInput; i += 2) //This is the number of iterations needed to print the top of diamond (from 1 to userInput by step of two for example with 5 = {1, 3, 5} so 3 rows.
{
for (int j = 0; j < userInput - 1 - i / 2; j++)//write correct number of spaces before, example with 5 = j < 5 - 1 -i / 2, so it would first print 4 spaces before, with 1 less untill it reach 0
{
System.out.print(" ");//write a space
}
for (int j = 0; j < i; j++)
{
System.out.print("*");//write an asterix
}
System.out.println("");
}
// Same logic apply here but backward as it is bottom of diamond
for (int i = userInput; i > 0; i -= 2)
{
for (int j = 0; j < userInput -1 - i / 2; j++)
{
System.out.print(" ");
}
for (int j = 0; j < i; j++)
{
System.out.print("*");
}
System.out.print("\n");
}
}

Related

Java lottery using arrays

I have to create a lottery game where you randomly generate six winning numbers simulating a lottery. Ask the user to enter six numbers and see if they win the lottery!
I have done a lot of it, but now im stuck. I am really new to java so forgive me. When it prompts to ask for another number it does it but it still displays it for the self-made lottery picks that display. Also, when displaying the numbers for the computer made lottery picks they are the same numbers over again that repeat and aren't 6 numbers. The counter doesn't work as well it maybe a little thing but i can't figure it out. Thank you
package arraysIntroduction;
import java.util.Scanner;
public class sizeQuestion {
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
int [] user =new int [6];
int i;
//Fill user array
System.err.println("Welcome to Miwand's Lottery");
System.out.println("Please enter your 6 desiered number to enter the lottery");
System.out.println("Pick from 1 to 49");
for ( i=0;i<user.length;i++) // gets numbers until it equals 6
{
System.out.println("Number:");
user[i]= in.nextInt(); // Gets numbers from user
while (user[i] < 0 ) // if its a negative number tell user to enter again
{
System.err.println("Negative number, please enter again:");
user[i]=in.nextInt();
}
if (user[i] > 49) // if the number goes past 49 prompt again
{
System.err.println("Please enter numbers from 1 - 49");
}
}
//print out the numbers generated
for ( i=0;i < user.length; i++){
System.out.print(+user[i]+ " ");
}
System.out.println(" ");
int[] lottery = new int[6];
int guesses;
int counter=0;
int j;
int x;
{
for (j = 0; j < 6; j++) {
int randomNum = (int) (Math.random() *49 +1); // Random number created here.
for ( x = 0; x < j; x++) {
if (lottery[x] == randomNum) // Here, code checks if same random number generated before.
{
randomNum = (int) (Math.random() *49 +1);// If random number is same, another number generated.
}
lottery[j] = randomNum;
}
}
//prints out computer generated numbers
for (i = 0; i < lottery.length; i++){
for (x = 0; x< j; x++){
System.out.print(lottery[i] + " ");
if (user[i] == lottery[x] ){
counter++;
}
}
}
}
if (counter < 2){
System.out.println("Try again!");
}
if (counter == 3){
System.out.println("3 numbers matched! You won $300!");
}
if (counter == 4){
System.out.println("4 numbers matched! You won 500!");
}
if (counter == 5){
System.out.println(" 5 numbers matched! You won $1000!");
}
else if (counter == 6){
System.out.println("JACCKKKPOOOOTTTTTTT!!!!!! YOU WIN 1 MILLION DOLLARS!");
}
}
}
I saw multiple problems in your program.
First, the printout problem can be solved by moving the print statement from inner loop to outer loop
for (i = 0; i < lottery.length; i++) {
System.out.print(lottery[i] + " ");
for (x = 0; x < j; x++) {
if (user[i] == lottery[x]) {
counter++;
}
}
}
Also, you are not assigning the first random number correctly and it is always using the default, which is 0
Solution:
for (j = 0; j < 6; j++) {
int randomNum = (int) (Math.random() * 49 + 1); // Random number created here.
for (x = 0; x < j; x++) {
if (lottery[x] == randomNum) // Here, code checks if same random number generated before.
{
randomNum = (int) (Math.random() * 49 + 1);// If random number is same, another number generated.
}
}
lottery[j] = randomNum;
}
Plus, you didn't check if counter is equal to 2
Solution:
if (counter <= 2) {
System.out.println("Try again!");
}
And, the logic in "If random number is same, another number generated." may not be correct, since it may generate the same number again. You need a while loop to generate a new number until it is not equal to any of the generated numbers.
Another thing about coding style is that for any "for loops"
This :
int i=0;
for (i = 0; i < length; i++)
Should be replaced by this:
for (int i = 0; i < length; i++)
As I already said in the comments, you should move the print statement from the inner loop to the outer loop.
Your code should look like this:
for (i = 0; i < lottery.length; i++) { // outer loop
System.out.print(lottery[i] + " ");
for (x = 0; x < j; x++) { // inner loop
if (user[i] == lottery[x]) {
counter++;
}
}
}

Java (not so)Simple formatting

Hey guys so my homework was to:
1)Prompt the user to enter the number of cells C
2)Declare an integer array cell[] with C elements
3)Prompt the user to enter the number of time steps N
3)Prompt the user to enter the index of cells that contain 1(enter negative index to finish)
4)Run the cellular automaton for N time steps, using the rules defined above
5)On each time step, display the cells, printing a ‘#’ if the cell contains a 1,
a space if the cell contains a 0
A desired output would be:
Enter number of cells (<= 80): 10
Enter number of time steps: 10
Enter the index of occupied cells (negative index to end): 4 6 -1
0123456789
# #
####
## #
### ##
# ####
### #
# # ##
######
# #
# ##
# ###
My code so far is this:
import java.util.Scanner;
class P7{
public static void main(String[] args){
int i, N, C, index;
Scanner in = new Scanner(System.in);
System.out.println("Enter number of cells(<=80):");
C = in.nextInt();
int[] cell = new int[C];
System.out.println("Enter number of time steps:");
N = in.nextInt();
System.out.println("Enter the index of occupied cells(-num to end):");
for(i = 0; i < C; i++){
cell[i] = 0;
}
while(true){
index = in.nextInt();
if(index < 0){
break;
}
cell[index] = 1;
}
for(i = 0; i < N; i++)
updateCells(cell);
displayCells(cell);
}
public static void updateCells(int array[]){
int i;
int[] temp = new int[array.length];
for(i = 1; i < array.length - 1; i++){
if(array[i]==1 && array[i-1]==1 && array[i+1]==1)
temp[i] = 0;
else if(array[i]==1 && array[i-1]==1 && array[i+1]==0)
temp[i] = 1;
else if(array[i]==0 && array[i-1]==1 && array[i+1]==1)
temp[i] = 1;
else if(array[i]==0 && array[i-1]==1 && array[i+1]==0)
temp[i] = 0;
else if(array[i]==1 && array[i-1]==0 && array[i+1]==1)
temp[i] = 1;
else if(array[i]==1 && array[i-1]==0 && array[i+1]==0)
temp[i] = 1;
else if(array[i]==0 && array[i-1]==0 && array[i+1]==1)
temp[i] = 1;
else if(array[i]==0 && array[i-1]==0 && array[i+1]==0)
temp[i] = 0;
}
for(i = 0; i < array.length; i++){
array[i] = temp[i];
}
}
public static void displayCells(int data[]){
int i;
for(i=0;i < data.length; i++){
if(data[i] == 1)
System.out.println("#");
else if(data[i] == 0)
System.out.println(" ");
}
}
}
This is my current output:
Enter number of cells(<=80): 10
Enter number of time steps: 3
Enter the index of occupied cells(-num to end):
1
2
3
4
-1
#
#
#
#
Any and all help will be appreciated :D
I actually don't understand what you trying to do, try this if that might would help. If you have the question in written or any pdf, then I can probably tell. Best
import java.util.Scanner;
public class P7{
public static void main(String[] args){
int i, N, C, index;
Scanner in = new Scanner(System.in);
System.out.println("Enter number of cells(<=80):");
C = in.nextInt();
int[] cell = new int[C];
System.out.println("Enter number of time steps:");
N = in.nextInt();
System.out.println("Enter the index of occupied cells(-num to end):");
for(i = 0; i < N; i++){
cell[i] = 0;
}
while(true){
index = in.nextInt();
if(index < 0){
break;
}
cell[index] = 1;
}
for(i = 0; i < N; i++)
updateCells(cell);
displayCells(cell);
}
public static void updateCells(int cell[]){
int i;
int[] temp = new int[cell.length];
for(i = 1; i < cell.length - 1; i++){
if(cell[i]==1 && cell[i-1]==1 && cell[i+1]==1)
temp[i] = 0;
else if(cell[i]==1 && cell[i-1]==1 && cell[i+1]==0)
temp[i] = 1;
else if(cell[i]==0 && cell[i-1]==1 && cell[i+1]==1)
temp[i] = 1;
else if(cell[i]==0 && cell[i-1]==1 && cell[i+1]==0)
temp[i] = 0;
else if(cell[i]==1 && cell[i-1]==0 && cell[i+1]==1)
temp[i] = 1;
else if(cell[i]==1 && cell[i-1]==0 && cell[i+1]==0)
temp[i] = 1;
else if(cell[i]==0 && cell[i-1]==0 && cell[i+1]==1)
temp[i] = 1;
else if(cell[i]==0 && cell[i-1]==0 && cell[i+1]==0)
temp[i] = 0;
}
for(i = 0; i < cell.length; i++){
cell[i] = temp[i];
}
}
public static void displayCells(int cell[]){
int i;
for(i=0;i < cell.length; i++){
if(cell[i] == 1)
System.out.print("#");
else if(cell[i] == 0)
System.out.print(" ");
}
}
}`enter code here`

How to I validated an input for being an Int and within a number range?

The program displays a question and the user is meant to input a number 1 to 5. 5 questions for 5 users. However, the program doesn't recognize a good input, or a bad, as long as its an Int. I have to enter input a bunch of times before it goes it runs Survey.presentQuestions() again. I can't figure out why.
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
Survey.presentQuestion(j, i);
do{
TempAns = in.nextInt();
while (!(in.hasNextInt()))
{
System.out.println("Please enter integer value from 1 to 5!");
in.next();
}
}while(TempAns >= 1 && TempAns <= 5);
Survey.ResultArray[i][j] = TempAns;
}
}
Update try this instead
for (int i = 0; i < 5; i++) {
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
System.out.println("Student: "+(i+1)+" Grade: "+(j+1));
System.out.println("Please enter integer value from 1 to 5!");
TempAns = getNumber();
}
}
and this other method
public int getNumber(){
Scanner in =new Scanner(System.in);
int validatedNumber;
do{
try{
String toValidate=in.next();
validatedNumber= Integer.parseInt(toValidate);
if (validatedNumber>0 && validatedNumber<6){
return validatedNumber;
}else{
System.out.println("Between 1 and 5!!");
}
}catch(Exception e){
System.out.println("You have to chose a number!");
}
}while(true);
}
I assume you want the user to enter an integer 1-5 and proceed to the next question? If so, try this:
Replace:
do{
TempAns = in.nextInt();
while (!(in.hasNextInt()))
{
System.out.println("Please enter integer value from 1 to 5!");
in.next();
}
}while(TempAns >= 1 && TempAns <= 5);
With:
while (true) {
TempAns = in.nextInt();
if (TempAns >= 1 && TempAns <= 5)
return;
else
System.out.println("Please enter integer value from 1 to 5!");
}

How can I write this same statement using for loops instead of while loops?

The idea here is to learn how to apply different methods to the same problem in order to learn and see the differences
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer value-> ");
int k = input.nextInt();
input = new Scanner(System.in);
System.out.print("Enter a larger value-> ");
int j = input.nextInt();
int i = k;
while (i <= j)
{
if (i%2 == 0)
{
System.out.println(i);
}
i++;
}
I am trying this, but it is clearly wrong, how can I fix it, or where should i look?
for(i<=j;i % 2 ==0;i++)
{
System.out.println(i);
}}
When doing conversion from one loop to the other, it will be much easier if we first understand the intention of the original loop. From what you have:
while (i <= j){
if (i%2 == 0)
System.out.println(i);
i++;
}
In plain English, it means:
From the lower bound input to the upper bound input, print out all the even numbers (inclusive of zeroes).
Now based on that, we write a for-loop.
for(int x=k, x<=j; x++) //k is lower bound, j is upper bound
if(x % 2 == 0) //if current number is even or 0
System.out.println(x); //print that number
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer value-> ");
int k = input.nextInt();
input = new Scanner(System.in);
System.out.print("Enter a larger value-> ");
int j = input.nextInt();
int i = k;
for (;i <= j;i++) {
if (i%2 == 0) {
System.out.println(i);
}
}
Translated in for loop.
for (int i = k; i <= j; i++) {
if (i%2 ==0) {
System.out.println(i);
}
}

Changing elements in a two dimensional array

What I'm trying to do is generate a 15x15 square of "-" and accept a user input coordinate which will then replace the "-" with a "x" currently my program is just printing a vertical line of "-"
import java.util.*;
public class GameOfLife
{
public static void main(String[] args)
{
int[][] boardList = new int[15][15];
Scanner myScanner = new Scanner(System.in);
boolean done = false;
do
{
System.out.println("1 - Add a being \n 2 - Show current board \n 3 - Show next generation \n 4 - Clear board \n 5 - Add preload pattern \n 6 - Exit");
int choice = Integer.parseInt(myScanner.nextLine());
if (choice == 1)
{
System.out.print("Enter the x coordinate: ");
String answer = myScanner.nextLine();
int xCoordinate = Integer.parseInt(answer);
System.out.print("Enter the y coordinate: ");
String answer2 = myScanner.nextLine();
int yCoordinate = Integer.parseInt(answer2);
for(int i = 0; i < 15; i++)
{
for(int j = 0; j < 15; j++)
{
if(xCoordinate == i)
{
if(yCoordinate == j)
{
System.out.printf("x", boardList[i][j]);
}
}
else
System.out.printf("-", boardList[i][j]);
System.out.println();
}
}
}
}
}
}
here you have , this works ... u need to put System.out.println(); outside inner loop as well as put
if(xCoordinate == i){
if(yCoordinate == j){
to one condition ...
public static void main(String[] args) {
int[][] boardList = new int[15][15];
Scanner myScanner = new Scanner(System.in);
boolean done = true;
do {
System.out
.println("1 - Add a being \n 2 - Show current board \n 3 - Show next generation \n 4 - Clear board \n 5 - Add preload pattern \n 6 - Exit");
int choice = Integer.parseInt(myScanner.nextLine());
if (choice == 1) {
System.out.print("Enter the x coordinate: ");
String answer = myScanner.nextLine();
int xCoordinate = Integer.parseInt(answer);
System.out.print("Enter the y coordinate: ");
String answer2 = myScanner.nextLine();
int yCoordinate = Integer.parseInt(answer2);
for (int i = 0; i < 15; i++) {
for (int j = 0; j < 15; j++) {
if (xCoordinate == i && yCoordinate == j) {
System.out.printf("x", boardList[i][j]);
} else
System.out.printf("-", boardList[i][j]);
}
System.out.println();
}
}
} while (done);
}
//EDIT note that i changed done to true just to demonstrate that it works ...
try this
for(int i = 0; i < 15; i++)
{
for(int j = 0; j < 15; j++)
{
if(xCoordinate == i && yCoordinate==j)
System.out.printf("x", boardList[i][j]);
else
System.out.printf("-", boardList[i][j]);
}
System.out.println();
}
You need to print the new line after you finish printing a whole row first
If I understand well, You want a two dimensional array initialized with '-', to do so you could do
int[][] boardList = new int[15][15];
for (int row = 0; row < 15; row ++)
for (int col = 0; col < 15; col++)
boardList[row][col] = '-';
And then, once you store the user data in xCoordinate and Ycoordinate, you simple do:
boardList[xCoordinate][Ycoordinate] = 'x';
You can try this code:
import java.util.Scanner;
public class StackOverflow
{
public static void main(String[] args)
{
int[][] boardList = new int[15][15];
Scanner myScanner = new Scanner(System.in);
boolean done = false;
System.out.println("1 - Add a being \n 2 - Show current board \n 3 - Show next generation \n 4 - Clear board \n 5 - Add preload pattern \n 6 - Exit");
int choice = Integer.parseInt(myScanner.nextLine());
if (choice == 1)
{
System.out.print("Enter the x coordinate: ");
String answer = myScanner.nextLine();
int xCoordinate = Integer.parseInt(answer);
System.out.print("Enter the y coordinate: ");
String answer2 = myScanner.nextLine();
int yCoordinate = Integer.parseInt(answer2);
for(int i = 0; i < 15; i++)
{
for(int j = 0; j < 15; j++)
{
if(xCoordinate == i)
{
if(yCoordinate == j)
{
System.out.printf("x", boardList[i][j]);
}
else
{
System.out.printf("-", boardList[i][j]);
}
}
else
{
System.out.printf("-", boardList[i][j]);
}
}
System.out.println();
}
}
}
}

Categories