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("");
}
Related
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();
}
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)) {
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
**
**
**
*
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.
Hi guys this is my program ive been using java for about 3 weeks. I have achieved to do this simple game, has taken me long, but what i would like to do is how to include a code that randomly chooses who goes first in the game, some advice would be great, (bare in mind im very amateur if not less)
This isnt homework, or an assignment or work... just something im learning next week in class thought id learn it earlier and be ahead... (slighly a neek haha)
Thanks to anyone who helps
import java.util.Scanner;
/**
* The simple NIM game.
* There are 21 matches in the pile. On each move, each user take turns picking
* up 1, 2, or 3 matches until there are no more matches left.
* The one who picks up the last match loses.
*/
public class SimpleNIM {
private int matchesLeft = 21;
private String player = "A";
/**
* Starts and runs the game
*/
public void start() {
Scanner input= new Scanner(System.in);
while (true) {
int pickmatches = 0;
do {
System.out.print(
"Player " + player + ": How many matches do want to pick? (1, 2, or 3) ");
pickmatches = input.nextInt();
if (validMove(pickmatches)) {
break;
}
System.out.println(
matchesLeft - pickmatches < 0
? "You can't pick "
+ pickmatches
+ " matches as only "
+ matchesLeft
+ " matches left"
: "That's an illegal move. "
+ "Choose 1, 2, or 3 matches.");
}
while (true);
updateMatchesLeft(pickmatches);
System.out.println(
"Player "
+ player
+ " takes "
+ pickmatches
+ ( (pickmatches == 1) ? " match, " : " matches, ")
+ "leaving "
+ matchesLeft
+ '\n');
player = otherPlayer(player);
if (gameOver()) {
System.out.println("Player " + player + " wins the game!");
break;
}
}
}
/**
* Update the number of matches left in pile.
* pickmatches No. of matches picked
*/
private void updateMatchesLeft(int pickmatches) {
matchesLeft = matchLeft - pickmatches;
}
/**
* Game Over?
* true if game is over.
*/
private boolean gameOver() {
}
/**
* Returns the other player
* The current player ("B" or "A")
* The other player ("A" or "B")
*/
private String otherPlayer(String p) {
// YOUR CODE GOES HERE
}
/**
* Valid move?
* numMatches The number of matches picked
* true if there are enough matches left and numMatches is between 1 and 3
*/
private boolean validMove(int numMatches) {
}
/**
* Plays the game
* args ignored
*/
public static void main(String[] args) {
SimpleNIM pickUpMatches = new SimpleNIM();
welcome();
pickUpMatches.start();
}
/**
* Displays the startup information banner.
*/
private static void welcome() {
System.out.println("WELCOME TO THE SIMPLE NIM GAME: 21 MATCHES IN PILE");
}
}
new Random().nextInt(n) gives you a random number between 0 and n-1, so you can do
Player[] players = ...
playerToStart = players[new Random().nextInt(players.length)];
to randomly choose one.
If you plan to pick multiple players consider reusing Random instance.
You could do something like:
public void start() {
Scanner input = new Scanner(System.in);
player = Math.random() < 0.5 ? "A" :"B";
do {
But please learn something about Java in general before.
Inside your welcome method add the lines:
if(new java.util.Random().nextBoolean())
player = "A";
else
player = "B";
Have a look at the documentation for Random class.
Add this line to your libraries
import java.util.Random;
Then this line adds a new random number generator, kind of like Scanner.
Random generator = new Random();
Use this resource for more information.
Random rand = new Random();
int result = rand.nextInt(2); // a random number, either 0 or 1, see http://docs.oracle.com/javase/6/docs/api/java/util/Random.html#nextInt(int)
if (result == 0) {
// Player 1 goes first
}
else {
// Player 2 goes first
}