Output generating too many rows - java

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...

Related

Yahtzee two pair can't get any value

I am in a beginner's java class. I have had this Yahtzee program now for weeks and I still cannot get this figured out.
Having problem getting a points from my checkTwopairs(). checkTwopairs() can see if there is a two pair. But I have a hard problem getting the points out of it. Any good way to do it?
public int checknumber(int nr) {
int sum = 0;
for (Dice d : diceList) {
if (d.getValue() == nr ){
sum++;
}
}
return sum;
}
public void checkTwopairs() {
for (int i = 1; i <= 6; i++) {
int a = checknumber(i);
if (a == 2) {
if (twopair == true && a == 2) {
} else {
twopair = true;
}
}
}
twopair = false;
}
I'm guessing you're looking for 2 pairs, meaning you get dice with {5,5,2,2,1} where you have 2 pairs -- a pair of 5's, and a pair of 2's.
I think you may be looking for something like this to modify your code:
public void checkTwopairs() {
boolean firstPair = false; // New local variable.
for (int i = 1; i <= 6; i++) {
int a = checknumber(i);
if (a == 2) {
//if (twopair == true && a == 2) <--- This second clause is unnecessary as we can only get here if a == 2
if (firstPair == true) {
twopair = true;
return; //This returns the method, so twopair cannot be set to false if two pairs are found
} else {
firstPair = true;
}
}
}
//Checked all dice, less than two pairs were found.
twopair = false;
}
Here is a one-method solution to replace both of those methods:
public void checkTwoPairs() {
int numPairs = 0;
//two pairs haven't been found yet
boolean twoPair = false;
//for each possible number
for(int i = 1; i <= 6; i++) {
int sum = 0;
//for each dice object
for(Dice d : diceList) {
//if i is the dice value
if(d.getValue() == i) {
//increment the number of matches
sum++;
}
}
//sum % 2 - gives you the number of pairs for that number checked
numPairs += (sum%2);
//if you have 2 pairs
if(numPairs == 2) {
//set twoPair = true ... and break out of the loop
twoPair = true;
break;
}
//if you don't have 2 pairs yet, go back through the loop
}
}

Generate a number and check if it is already in a ArrayList

I would like to generate 10 random numbers. But before I add a number to the ArrayList, I need to check if my Arraylist already contains a number which is in the range between randomNumber - 50 and randomNumber + 50.
For example, if random number is 120 :
120-50=70
120+50=170
If the ArrayList contains a number between 70 and 170, I will not add it to my ArrayList and run again the cycle...
What is wrong with my code?
package ee.tlu;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Testing {
public Testing() {
List < Integer > numbers = new ArrayList < > ();
Random rand = new Random();
int number = rand.nextInt(5000);
int n = 0;
boolean listis = false;
numbers.add(number);
while (n < 10) {
number = rand.nextInt(5000);
for (int k = number - 50; k < number + 50; k++) {
if (numbers.contains(k)) {
listis = true;
break;
}
}
if (!listis) {
numbers.add(number);
n += 1;
}
}
System.out.println(numbers);
}
public static void main(String[] args) {
new Testing();
}
}
You declare listis before you start the while-loop. It's never reset once it has been set to true. Move it inside the loop.
Also, you never check the number + 50 as you are having < instead of <= in your for-loop.
while (n < 10) {
boolean listis = false;
number = rand.nextInt(5000);
for (int k = number - 50; k <= number + 50; k++) {
if (numbers.contains(k)) {
listis = true;
break;
}
}
if (!listis) {
numbers.add(number);
n += 1;
}
}
I'm not sure if it's the only problem, but you should reset your listis flag in each iteration of the while loop :
while (n < 10) {
listis = false; // added
number = rand.nextInt(5000);
for (int k = number - 50; k < number + 50; k++) {
if (numbers.contains(k)) {
listis = true;
break;
}
}
if (!listis) {
numbers.add(number);
n += 1;
}
}
Otherwise, the first time you find a number that shouldn't be added, you will stop adding any numbers.
I would do this recursively. I haven't tested the below code, just a quick mockup on notepad. But hopefully this will help.
public class Testing {
public List < Integer > numbers = new ArrayList < > ();
public Testing() {
Random rand = new Random();
int number = rand.nextInt(5000);
// initial number in arraylist
numbers.add(number);
// add 9 more numbers to arraylist
addNumbers(9);
System.out.println(numbers);
}
public void addNumber(int amountLeft){
int newNumber = rand.nextInt(5000);
if(isValidNumberToAdd(newNumber))
{
numbers.add(newNumber);
}
if(amountLeft == 0)
{
return;
}
addNumber(amountLeft--);
}
public boolean isValidNumberToAdd(int newNumber)
{
Iterator<int> numbersIterator = numbers.iterator();
while (numbersIterator.hasNext()) {
int number = numbersIterator.next();
if(newNumber > number - 50 && newNumber < number + 50)
{
return false;
}
}
return true;
}
public static void main(String[] args) {
new Testing();
}
}
Simply use Set instead of List. Sets guarantee that:
Adding new element to the set works only if new element is not already present in the set.

Cinema seating arrangement

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

Can find all the prime numbers but doesn't include "2"?

It now can find all the prime numbers in the input range, but it can't find number 2, the smallest prime number.
for(int number=2;number<range;number++){
for(int testDivide=2;testDivide<Math.sqrt(number);testDivide++){
if(number%testDivide!=0) {
System.out.println(number);
}
break;
}
For range 10 it prints:
5
7
9
but no 2.
The reason your code is not producing correct results (missing 2 and 3; including 9) is that your primality test logic is backwards. A number is prime if the inner loop completes without finding any even divisors; instead you are printing the number if you find any non-divisor.
Try this instead:
for( int number = 2; number < range; number++) {
boolean divisible = false;
int limit = (int) Math.sqrt(number);
for (int testDivide = 2; !divisible && testDivide <= limit; testDivide++) {
divisible = number % testDivide == 0;
}
if (!divisible) {
System.out.println(number);
}
}
Note that a much more efficient way to generate all primes in a range is the Sieve of Eratosthenes.
check the code here:
package core;
public class Test2 {
public static void main(String[] args) {
int cnt = 0;
for (int i = 2;; i++) {
if (Priem(i)) {
cnt++;
System.out.println(i);
if (cnt == 200)
break;
}
}
}
public static boolean Priem(int n) {
for (int i = 2; i < n; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
}
Note that one of the best ways to generate a list of prime numbers is the "Sieve of Erwhatshisface":
Create a list of consecutive integers starting with 2, up to the max number you'd like to search. Take the first non-zero number in the list (2) and repeatedly step 2 from that location, zeroing out every 2nd list element.
Next take the second non-zero number (3) and repeatedly step 3 from that location, zeroing. Continue with each non-zero value in the list, until you've processed all of them (or at least halfway through, at which point you'll be stepping beyond the end of the list).
The non-zero numbers remaining are all primes.
Reposting code here as not fit in comments:
public static void main(String[] args) {
int cnt = 0;
for (int i = 2;; i++) {
if(i==2){
System.out.println(i);
continue;
}
if (Priem(i)) {
cnt++;
System.out.println(i);
if (cnt == 200)
break;
}
}
}
public static boolean Priem(int n) {
for (int i = 2; i <Math.sqrt(n)+1; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
I think you have your for loop a little mixed up.
for(int testDivide=2;testDivide<Math.sqrt(number);testDivide++){
}
Not sure why you are stopping when testDivide is equal to sqrt(number), you should stop when testDivide is greater than.
Also inside your inner for loop isn't correct either:
if(number%testDivide!=0) {
System.out.println(number);
}
break;
Basically all this will do is check to see of the number is divisible by 2 and then break. You only need to break when you find a number which cleanly divides (number%testDivide==0). Maybe keep a boolean which you set to true when you break and only print after the inner for loop finishes if that boolean is false.
Something along the lines:
for (int number=2; number<range; number++){
boolean found = false;
int limit = (int)Math.sqrt(number);
for (int testDivide=2; testDivide<=limit; testDivide++){
if(number%testDivide==0) {
found = true;
break;
}
}
if (!found) System.out.println(number);
}
In your code when number is 2, sqrt(2) is 1.41 and control doesn't go into the loop. I didn't get the logic behind iterating upto sqrt(number). Try this code
public class Test {
public static void main(String[] args) {
int range = 500; //I assume
for (int i = 2; i< range; i++) {
if (isPrime(i)) {
System.out.println(i);
}
}
}
public static boolean isPrime(int number) {
for (int i = 2; i <= number/2; i++) {
if (number % i == 0) {
return false;
}
if(i % 2 == 1) {
i++; //If not divided by 2 then
// need not to check for any even number
// Essentially incrementing i twice hereafter
}
}
return true;
}
}

Program does not run as expected

I'm doing a magicsquare program that allows a user to input numbers >0 to form a magicsquare. What a magic square is, is pretty much a square, meaning that n has to have n(squared) numbers. Much like ticTacToe, all the rows, columns, and diagonals each have the same sum to be considered a magic square When I run my program, It always confuses the 2D array set and claim that the set of numbers are a magicsquare when usually, it isnt necessarily so. Please help!
import java.util.Scanner;
public class SquareRunner
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
Square test = new Square();
System.out.println("Enter a row of integers. When you are finished, type 'n' in a new line");
boolean flag = false;
while(!flag)
{
String numbers = in.next();
if(numbers.equals("n"))
flag = true;
else
test.add(numbers);
}
test.isMagic();
}
}
public class Square
{
private int[][] values;
private int row;
public Square()
{
row = 0;
}
public void add(String numbers)
{
int b = 1;
int amount = numbers.length();
values = new int[amount][amount];
for(int j =0;j<amount;j++)
{
String a = numbers.substring(j,b);
int convert = Integer.parseInt(a);
values[row][j] = convert;
b++;
}
row++;
}
public Boolean isMagic()
{
int checkAmountColumns = values[0].length;
int checkAmountRows = values.length;
int isSquare = checkAmountColumns * checkAmountRows;
for(int q = 0;q<values.length;q++)
{
for(int w=0;w<values[0].length;w++)
{
int checkZero = values[q][w];
if(checkZero == 0)
{
System.out.print("To be a perfect square, your number of rows and columns, n must be a perfect ");
System.out.println("Square i.e. 9 total numbers is 3 numbers per row");
return false;
}
}
}
if(checkAmountColumns != checkAmountRows || Math.sqrt(isSquare) != checkAmountColumns)
{
System.out.print("To be a perfect square, your number of rows and columns, n must be a perfect ");
System.out.println("Square i.e. 9 total numbers is 3 numbers per row");
return false;
}
else
{
int magicNumber = 0;
int counter = 0;
int compareTo = 0;
//row to row
for(int i =0;i<values.length;i++)
{
for(int j = 0;j<values[0].length;j++)
{
values[i][j] += compareTo;
if(counter == 0)
values[i][j] += magicNumber;
}
counter ++;
compareTo = 0;
if(compareTo != magicNumber)
{
System.out.println("This Selection of numbers is not a perfect square");
return false;
}
}
//column to column
for(int i =0;i<values[0].length;i++)
{
for(int j = 0;j<values.length;j++)
{
values[j][i] += compareTo;
if(counter == 0)
values[j][i] += magicNumber;
}
counter ++;
compareTo = 0;
if(compareTo != magicNumber)
{
System.out.println("This Selection of numbers is not a perfect square");
return false;
}
}
System.out.println("This selection of numbers is a MagicSquare!");
return true;
}
}
}
The first thing I notice is that your add() method probably won't work correctly. Every time you call it, you overwrite the previous values member with a newly allocated array. This throws away the previous row that you entered.
Same answer as Greg.
Add this to your add method and delete the initialisation of your values array.
if(values == null){values = new int[amount][amount];}

Categories

Resources