Print pyramid pattern in java [duplicate] - java

This question already has answers here:
Java algorithm to make a straight pyramid [closed]
(4 answers)
Closed 8 years ago.
public class Main {
public static void main(String[] args) {
int i,j,k;
for(i=1;i<=4;i++)
{
for(j=1;j<=i;j++)
{
for(k=3;k>0;k--)
{
System.out.println(" ");
}
System.out.println("*");
}
System.out.println("\n");
}
}
}
output is :
*
*
*
*
*
*
*
*
*
*
BUILD SUCCESSFUL (total time: 0 seconds)

Try this:
public static void main(String[] args) {
for(int i=0;i<5;i++) {
for(int j=0;j<5-i;j++) {
System.out.print(" ");
}
for(int k=0;k<=i;k++) {
System.out.print("* ");
}
System.out.println();
}
}
Output:
*
* *
* * *
* * * *
* * * * *
Just for your knowledge System.out.println will print on a new line where System.out.print will print in the same line.

Related

How to print half right side of sphere pattern in Java

I am trying to print right side of sphere, please suggest me an idea to print
expected output. I have added my program below which i can print first row how do i print rest. Thanks in advance...!!
My program
public class PatternRight {
public static void main(String[] stars)
{
int size =5;
for(int col=0;col<=size;col++)
{
System.out.print(" *");
}
}
}
Actual output
* * * *
Expected output
* * * *
* * *
* *
*
* *
* * *
* * * *
How do i print the rest of rows..?
This is definitely not the best way however it gets the work done!
If you want people to help you, try being polite next time.
for(i=4;i>=1;i--)
{
for(j=4;j>i;j--)
{
System.out.print(" ");
}
for(k=1;k<=i;k++)
{
System.out.print("*");
}
System.out.println("");
}
for(i=2;i<=4;i++)
{
for(j=4;j>i;j--)
{
System.out.print(" ");
}
for(k=1;k<=i;k++)
{
System.out.print("*");
}
System.out.println("");
}

Same condition in C and Java but different Output

I'm doing pattern programming in C and java. I have written code for both the languages with same condition so i'm expecting the same output but i'm not getting same output.
Here is C code of pattern program
#include<stdio.h>
int main()
{
int i,j;
for(i=1;i<=5;i++)
{
for(j=1;j<=9;j++)
{
if(j<=(6-i)||j>=(4+i))
printf("*");
else
printf(" ");
}
printf("\n");
}
}
Output:
*********
**** ****
*** ***
** **
* *
Java Code:
public class Main {
public static void main(String [] args) {
int i,j;
for(i=1;i<=5;i++)
{
for(j=1;j<=9;j++)
{
if(j<=(6-i)||j>=(4+i))
System.out.print("*");
else
System.out.println();
}
}
}
}
Output:
*************
*******
*****
***
*
Help me to fix this problem
The Java version prints a new line instead of a space like in the C version. Try this instead.
public class Main {
public static void main(String [] args) {
int i,j;
for(i=1;i<=5;i++)
{
for(j=1;j<=9;j++)
{
if(j<=(6-i)||j>=(4+i))
System.out.print("*");
else
System.out.print(" "); // Prints space
}
System.out.println(); // Prints a newline for each row
}
}
}
In your Java program you forget to write a line of code corresponding to printf(" "); in your C code. This in Java will be like System.out.print(" ");
Try this modified code :
public class Main {
public static void main(String[] args) {
int i, j;
for (i = 1; i <= 5; i++) {
for (j = 1; j <= 9; j++) {
if (j <= (6 - i) || j >= (4 + i))
System.out.print("*"); // in C printf("*");
else
System.out.print(" "); // in C printf(" ");
}
System.out.println(); // in C printf("\n");
}
}
}
Output :
*********
**** ****
*** ***
** **
* *

How do I reroll the dice in Yahtzee

I am I very beginner programmer and I am stuck on how I can reroll the dice in my program. The project that I am working on is Yahtzee. In Yahtzee, you roll 5 dice and you can choose what dice to reroll ('r') and what dice to keep ('k'). In all, I am trying to roll 2 times.
package yahtzee1;
import java.util.Scanner;
public class Yahtzee1 {
/**
* Allows the get information from the user like to keep or reroll
* #param prompt
* #return
*/
public static char getcharFromUser(String prompt) {
Scanner sc = new Scanner(System.in);
System.out.println(prompt);
char c = sc.next().charAt(0);
return c;
}
/**
* generate 5 random numbers from 1 to 6, inclusive
* #param dice array to store the numbers
*/
public static void roll(int[] dice) {
for (int i = 0; i < 5; i++) {
dice[i] = (int) (Math.random() * 6 + 1);
}
}
/**
* generate 5 random numbers from 1 to 6, inclusive
*
* #param dice array to store the numbers
*/
public static void printDice(int[] dice) {
for (int i = 0; i < 5; i++) {
System.out.print(dice[i]);
}
}
/**
* After the 5 dice are "rolled" user picks which dice to re-roll or keep
* #param dice
* #param option
*/
public static void reRoll(int[] dice, String option) {
//help here
}
/**
*
* #param dice
*/
public static void playRound(int [] dice){
for (int i = 0; i < 2;i++){
reRoll(dice, option);
roll(dice);
printDice(dice);
}
}
/**
* play Yahtzee
* #param args the command line arguments
*/
public static void main(String[] args) {
int[] dice = new int[6];
playRound(dice);
}
}
the section in my code where I need help is in the method reRoll.
You can do something like this:
public static void reRoll(int[] dice, String option) {
//Change the split parameter to whatever you need the delimiter to be
for(String numString: option.split(" ")){
int die = Integer.parseInt(numString);
dice[die-1] = (int) (Math.random() * 6 + 1);
}
}
public static void playRound(int [] dice){
roll(dice);
printDice(dice);
Scanner sc = new Scanner(System.in);
for (int i = 0; i < 2;i++){
System.out.print("Enter dice to reroll: ");
String option = sc.nextLine();
reRoll(dice, option);
printDice(dice);
}
sc.close();
}

Java - Hangman Game - trouble with charAt on StringBuffer variable

So I am trying to make a hang man game using a website that returns random word. I'm using that random word for the hangman game.
What I am stuck on is validating a guess the user makes. Here is the code, I am just putting everything in main first then making separate methods to do the work for me after this works.
public static void main(String[] args) throws Exception {
randomWord = TestingStuff.sendGet();
int totalTries = 1;
char[] guesses = new char[26];
int length = randomWord.length();
Scanner console = new Scanner(System.in);
System.out.print("* * * * * * * * * * * * * * *"
+ "\n* Welcome to Hangman! *"
+ "\n* * * * * * * * * * * * * * *");
System.out.println("\nYou get 10 tries to guess the word by entering in letters!\n");
System.out.println(randomWord);
/*
Cycles through the array based on tries to find letter
*/
while (totalTries <= 10) {
System.out.print("Try #" + totalTries);
System.out.print("\nWhat is your guess? ");
String guess = console.next();
char finalGuess = guess.charAt(0);
guesses[totalTries - 1] = finalGuess; //Puts finalGuess into the array
for (int i = 0; i < totalTries; i++) { //checks to see if the letter is already guessed
if (finalGuess != guesses[i]) {
for (int j = 0; i < length; j++) { //scans each letter of random word
if (finalGuess.equals(randomWord.charAt(j))) {
}
}
} else {
System.out.println("Letter already guessed, try again! ");
}
}
}
}
What I am stuck on is inside of the while loop where it says:
for (int i = 0; i < totalTries; i++) { //checks to see if the letter is already guessed
if (finalGuess != guesses[i]) {
for (int j = 0; i < length; j++) { //scans each letter of random word
if (finalGuess.equals(randomWord.charAt(j))) {
}
}
} else {
System.out.println("Letter already guessed, try again! ");
}
}
It is giving me an error saying "char cannot be dereferenced". Am I missing something here?
finalGuess is a primitive char - you can't use methods, such as equals on it. You could just compare the two chars using the == operator:
if (finalGuess == randomWord.charAt(j)) {

Histogram from grade array list in Java

I'm trying to make a histogram from an arrayList containing student grades. I have already made a grade breakdown as shown here:
/**
* Returns a simple, 5-element array with the counts for each of the letter grades,
* (A, B, C, D, and F), based on the 10-point scale
* #return 5-element array
*/
private int[] calculateGradingBreakdown() {
int[] breakdown;
breakdown = new int[7];
for (Student kids: this.students) {
int grade = kids.getNumericGrade();
if (grade >= 90) {
breakdown[0] += 1;
} else if (grade >= 80) {
breakdown[1] += 1;
} else if (grade >= 70) {
breakdown[2] += 1;
} else if (grade >= 60) {
breakdown[3] += 1;
} else {
breakdown[4] += 1;
}
}
return breakdown;
}
/**
* Returns a string that lists the grade letter and the count of students
* receiving the grade on the roster
* #return grade breakdown
*/
public String getGradeBreakdown() {
String gradeBreakdown = null;
int[] breakdown = this.calculateGradingBreakdown();
gradeBreakdown = ("A: " + breakdown[0] + "\nB: " + breakdown[1] + "\nC: " + breakdown[2]
+ "\nD: " + breakdown[3] + "\nF: " + breakdown[4]);
return gradeBreakdown;
}
The code I have for the histogram has changed a few times, but needs to include the methods listed below. I have left my current code in, but am struggling as to how to get the histogram to work as listed.
/**
* Accepts a number of stars (*) to be created, creates a String with that
* number of *'s side-by-side, and then returns that string.
*/
private String makeStarRow(int number) {
int[] breakdown = this.calculateGradingBreakdown();
number = breakdown[];
String stars =
}
/**
* Returns a string holding a horizontal histogram of *'s
*/
public String getGradeHistogram() {
String gradeHistogram = null;
int[] breakdown = this.calculateGradingBreakdown();
gradeHistogram = (this.makeStarRow(breakdown[0]));
gradeHistogram += (this.makeStarRow(breakdown[1]));
gradeHistogram += (this.makeStarRow(breakdown[2]));
gradeHistogram += (this.makeStarRow(breakdown[3]));
gradeHistogram += (this.makeStarRow(breakdown[4]));
return gradeHistogram;
}
The output should look like this to end for the grade breakdown and histogram (with the numbers being according to the input in another class):
A: 2
B: 2
C: 2
D: 0
F: 1
**
**
**
*
For your interest and reference, here's a solution using Java 8 streams:
void printHistogram(List<Integer> scores) {
scores.stream().collect(Collectors.groupingBy(n -> n < 60 ? 5 : n / 10));
.entrySet().stream().sorted(Map.Entry::comparingByKey)
.map(entry -> entry.getValue().size());
.map(size -> Stream.iterate(() -> "*").limit(size).collect(Collectors.joining()))
.forEach(System.out::println);
}
One of the ways to create the string of repeating symbols is to use Arrays.fill:
private String makeStarRow(int number) {
char[] starChars = new char[number];
Arrays.fill(starChars, '*');
String stars = new String(starChars) + '\n';
return stars;
}
Note that according to the getGradeHistogram method it's likely that you need a '\n' appended to the end of the stars String.
Thanks for the help guys. I actually got a working solution:
/**
* Accepts a number of stars (*) to be created, creates a String with that
* number of *'s side-by-side, and then returns that string.
*/
private String makeStarRow(int number) {
while (number > 0) {
System.out.print("*");
number--;
}
if (number < 1) {
System.out.println();
}
return null;
}
/**
* Returns a string holding a horizontal histogram of *'s
* #return histogram
*/
public String getGradeHistogram() {
int[] histogram = this.calculateGradingBreakdown();
for (int xi = 0; xi < this.students.size(); xi++) {
int meh = histogram[xi];
this.makeStarRow(meh);
}
return "";
}
It prints out what I was looking for. Hopefully this helps someone in the future.
A: 2
B: 2
C: 2
D: 0
F: 1
**
**
**
*

Categories

Resources