Create number matrix in Java - java

I'm trying to write a program that will prompt the user for a number between 1 and 9 and will create a matrix x by x where x is the number given. It should produce random numbers from 1 to x^2 to fill in the matrix. I have it worked out where, if I input '5' I get one row with 5 random digits and then four lines with just one number each. What am I missing?
import java.util.Scanner;
import java.util.Random;
public class MatrixFiller
{
public static void main(String[] args)
{
//Getting input from the user
Scanner input = new Scanner(System.in);
System.out.print("Size of Matrix(a number between 1 and 9): ");
int matrixn = input.nextInt();
input.close();
//max is the largest possible number that can be calculated
//with the given number squared.
int max = (matrixn * matrixn);
//Counters for building the matrix
int i = 0;
int j = 0;
//Will create a line with x numbers on it but then produces
//x lines with only one number. If given 5 it produces a
//line with 5 numbers then four more lines with one number
//each.
do {
do {
Random rand = new Random();
int mout = rand.nextInt(max - 0);
System.out.print(mout + " ");
i++;
}
while (i < matrixn);
System.out.println();
j++;
}
while (j < matrixn);
}
}

You need to reset i at the beginning of the loop, otherwise it is still matrixn from the previous line.
do {
i = 0; // It won't work without this
do {
Random rand = new Random();
int mout = rand.nextInt(max - 0);
System.out.print(mout + " ");
i++;
} while (i < matrixn);
System.out.println();
j++;
} while (j < matrixn);
While this works, it would be much better to use for loops instead.

The key is resetting that value of i to zero at the top of your first do loop.
Or you could use for loops as it seems cleaner for your purposes:
Random rand = new Random();
for (i=0; i<matrixn; i++) {
for (j=0; j<matrixn; j++) {
int mout = rand.nextInt(max);
System.out.print(mout + " ");
}
System.out.println();
}

Your Inner Loop only one time executed, i must be start from begging each time.
do{
i = 0 ;
do {
Random rand = new Random();
int mout = rand.nextInt(max – 0);
System.out.print(mout + “ “);
i ++;
} while(i<matrixn);
system.our.println();
j++;
} while(j < matrixn);

Related

How do I "Line-Feed"?

This program is meant to display an array and compute prime numbers between 1 and whatever the user enters. On some IDEs that "Capture Output", the list of prime numbers will not "word-wrap". Instead, it will display one VERY long line of numbers. This can be handled by inserting a "line-feed" in the display code that is activated every 15 numbers. I have no clue how to do this, my code is below.
import java.util.Scanner;
import java.text.DecimalFormat;
public class Lab11avst {
public static void main(String[] args) {
// This main method needs additions for the 100 point version.
Scanner input = new Scanner(System.in);
System.out.print("Enter the primes upper bound ====>> ");
final int MAX = input.nextInt();
boolean primes[];
primes = new boolean[MAX];
computePrimes(primes);
displayPrimes(primes);
}
public static void computePrimes(boolean primes[]) {
System.out.println("\nCOMPUTING PRIME NUMBERS");
int newLine = 15;
int multiplicator = 1;
int list[] = new int[1000];
for (int k=2; k < primes.length; k++) {
primes[k] = true;
}
for (int k=2; k < primes.length; k++)
for (int x=2*k;x<primes.length;x+=k)
primes[x] = false;
}
public static void displayPrimes(boolean primes[]) {
DecimalFormat output = new DecimalFormat("0000");
System.out.println("\n\nPRIMES BETWEEN 1 AND " + primes.length);
int numPrimes = 0;
for (int k=2; k < primes.length; k++) {
if (numPrimes % 15 == 0) System.out.println("");
if (primes[k]) System.out.print(output.format(k) + " ");
++numPrimes;
}
}
}
If you have to proceed with your current method of computing prime numbers, then you can just keep track of how many primes have been printed, and add a line break for every 15 numbers. I suggest making a slight change to your displayPrimes() method:
public static void displayPrimes(boolean primes[]) {
DecimalFormat output = new DecimalFormat("0000");
System.out.println("\n\nPRIMES BETWEEN 1 AND " + primes.length);
int numPrimes = 0;
for (int k = 2; k < primes.length; k++) {
if (numPrimes % 15 == 0) System.out.println("");
if (primes[k]) System.out.print(output.format(k) + " ");
++numPrimes;
}
}
I use System.out.println here, which guarantees that the correct line break will be used for any platform.
However, a nicer way to approach the entire problem would be to just compute the actual prime numbers themselves, and then just iterate that array and display. Using this approach would require a complete refactor of code, maybe not what you want, and also probably too broad for a single question.
Let numPrimes indeed count the printed primes:
int numPrimes = 0;
for (int k = 2; k < primes.length; k++) {
if (primes[k]) {
if (numPrimes % 15 == 0) {
System.out.println();
}
System.out.print(output.format(k) + " ");
++numPrimes;
}
}
And \n is on Unix/Linux and MacOS, Windows uses \r\n:
System.out.println("\nCOMPUTING PRIME NUMBERS");
should be
System.out.println();
System.out.println("COMPUTING PRIME NUMBERS");

Generating random number sequences & sorting them out in java

Good day,
I am currently working on this program, which has to generate as many numbers as I enter (between 1-100) and the number has to be in the range of 0 - 1 000 000.
Then, the program must print them out in a random order and after that using the insertion sort, it must sort the randomly generated numbers.
I've been tackling this for about 7 hours now, searched online for answers, but haven't found anything yet. I was hoping to get a fix for my problem here!
What the program is supposed to do:
Person enters how many random numbers they want the program to generate (between 1-100)
Print out the amount of random numbers (random numbers must must be in the range of 0 - 1 000 000), the person entered before.
Sort the numbers using insertion sorting and print them out.
This is what I currently have:
It doesn't print out the sorted list.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the amount:");
int amount = scan.nextInt();
int []numbers = new int[amount];
Random rand = new Random();
System.out.println("Random order:");
int MAX = 1000000;
int MIN = 0;
for (int i = 0; i < amount; i++) {
numbers[i] = rand.nextInt(MAX - MIN + 1) + MIN;
System.out.print(numbers[i] + ", ");
}
System.out.println("");
System.out.print("From smallest to biggest:");
sort(numbers);
}
public static int[] sort(int[] list) {
int i, j, key, temp;
for(i = 1; i < list.length; i++) {
key = list[i];
j = i-1;
while (j >= 0 && list[j] > key) {
temp = list[j];
list[j] = list[j+1];
list[j+1] = temp;
j--;
}
System.out.print(list);
}
return list;
}
}
I think u forgot to call the sort method.

How do I compare elements between two arrays and then print the equal elements?

I'm coding a lottery program, and right now I'm kind of stuck. I let the user pick seven numbers, and at the end I want the program to tell the user which numbers he answered correctly.
I'm having so much trouble understanding arrays that I'm not sure how to store the correctly guessed numbers in an array and then print the elements in the array at the end. I've tried all sorts of variations but nothing is working for me.
package whatevs;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Random;
import java.util.Scanner;
public class lottery {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int[] userNumbers = new int[7];
int[] winningNumbers = new int[7];
int guesses;
int i;
int counter = 0;
int[]correctGuessed=new int[8];
int x;
ArrayList<Integer> list = new ArrayList<Integer>();
for (x=1; x<40; x++) {
list.add(new Integer(x));
}
Collections.shuffle(list);
for (x=0; x<7;x++) {
winningNumbers[x] = list.get(x);
}
System.out.println("Pick 7 numbers between 1 and 39: ");
for(i = 0; i < 7; i++){
guesses = reader.nextInt();
userNumbers[i] = guesses;
// System.out.println(userNumbers[i]);
for(x = 0; x<7;x++){
if(winningNumbers[x] == userNumbers[i]){
correctGuessed[x] = userNumbers[i];
counter+=1;
}
}
if (counter == 7){
System.out.println("You won!");
}
else
System.out.println("You had " + counter + " numbers correct: " + correctGuessed[x] );
}
}
I would use Sets instead of arrays. Sets have two advantages over arrays:
they ensure that there is no duplicate in the set (which is what you want, since you have distinct 40 numbers, and want the user to pick 7 distinct numbers)
they are much higher-level, and thus have many useful methods that bare arrays don't have
So here is the logic you should have:
Fill a list with 40 numbers
Shuffle it
Create a HashSet<Integer> and add the first 7 elements of the list. Those are the winning numbers
Create a new empty Hashset<Integer>
Ask the user to enter numbers. Add each number to this new HashSet, and keep asking until the set has 7 numbers
Use the retainAll() method of HashSet to know which of the guessed numbers are also part of the winning numbers. The javadoc is your friend to understand what this method does.
Use list.contains(v) to check if wining values are among the guessed one.
Something like this:
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
Integer[] userNumbers = new Integer[7];
Integer[] winningNumbers = new Integer[7];
int guesses;
int i;
int counter = 0;
int[] correctGuessed = new int[8];
int x;
ArrayList<Integer> list = new ArrayList<Integer>();
for (x = 1; x < 40; x++) {
list.add(Integer.valueOf(x));
}
Collections.shuffle(list);
for (x = 0; x < 7; x++) {
winningNumbers[x] = list.get(x);
}
System.out.println("Pick 7 numbers between 1 and 39: ");
for (i = 0; i < 7; i++) {
guesses = reader.nextInt();
userNumbers[i] = guesses;
}
List<Integer> winList = Arrays.asList(winningNumbers);
List<Integer> guessList = Arrays.asList(userNumbers);
List<Integer> matchList = new ArrayList<Integer>();
for (Integer guess : guessList) {
if (winList.contains(guess)) {
matchList.add(guess);
}
}
counter = matchList.size();
if (counter == 7) {
System.out.println("You won!");
} else {
System.out.println("You had " + counter + " numbers correct: " + Arrays.toString(matchList.toArray()));
}
}// main
Your code is a little complex but it is almost good to work.
Some remarks :
The object which contains the guessed numbers should not be a array of 7 elements : int[7] because otherwise it contains always 7 elements while the user may found less than 7 numbers. In this case, the other values will be to 0 (default value of int) and it you use Integer[7], it will be to NULL. It is probably not a suitable choice. You should rather declare :
Set<Integer> correctGuessed = new HashSet<Integer>();
instead of int[]correctGuessed=new int[8];
When a number is guessed, you assign the found number in this way : correctGuessed[x] = userNumbers[i];
You could replace now by this :
correctGuessed.add(userNumbers[i]);
At the end, you write in the output :
`System.out.println("You had " + counter + " numbers correct: " + correctGuessed[x] );`
It is not right for two reasons :
- x has always as value 7 after the loop. So, it is not necessarily the value of the index of the array you have just filled. In your original solution, you should use a break if you want to keep the value of x when the number is guessed :
for(x = 0; x<7;x++){
if(winningNumbers[x] == userNumbers[i]){
correctGuessed[x] = userNumbers[i];
counter+=1;
break;
}
}
you refer "to numbers correct" in the output. So, it seems more logical to display all guessed number :
System.out.println("You had " + counter + " numbers correct: " + correctGuessed);
The final solution is very near from our one :
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int[] userNumbers = new int[7];
int[] winningNumbers = new int[7];
int guesses;
int i;
int counter = 0;
Set<Integer> correctGuessed = new HashSet<Integer>();
int x;
ArrayList<Integer> list = new ArrayList<Integer>();
for (x = 1; x < 40; x++) {
list.add(new Integer(x));
}
Collections.shuffle(list);
for (x = 0; x < 7; x++) {
winningNumbers[x] = list.get(x);
}
System.out.println("Pick 7 numbers between 1 and 39: ");
for (i = 0; i < 7; i++) {
guesses = reader.nextInt();
userNumbers[i] = guesses;
for (x = 0; x < 7; x++) {
if (winningNumbers[x] == userNumbers[i]) {
correctGuessed.add(userNumbers[i]);
counter += 1;
}
}
if (counter == 7) {
System.out.println("You won!");
}
else
System.out.println("You had " + counter + " numbers correct: " + correctGuessed);
}
}
Your code quickly fixed looks like this:
System.out.println("Pick 7 numbers between 1 and 39: ");
for(i = 0; i < 7; i++) {
guesses = reader.nextInt();
userNumbers[i] = guesses;
// System.out.println(userNumbers[i]);
for (x = 0; x < 7; x++) {
if (winningNumbers[x] == userNumbers[i]) {
correctGuessed[counter] = userNumbers[i];
counter += 1;
}
}
}
if (counter == 7){
System.out.println("You won!");
}
else
System.out.println("You had " + counter + " numbers correct: " + Arrays.toString(correctGuessed));
There is however a lot that can be improved, as other users already said. You don't want to use an array to store the winning values, you could use a Set to do that:
Set<Integer> correctGuesses = new HashSet<>();
for(i = 0; i < 7; i++) {
guesses = reader.nextInt();
userNumbers[i] = guesses;
for (x = 0; x < 7; x++) {
if (winningNumbers[x] == userNumbers[i]) {
correctGuesses.add(userNumbers[i]);
}
}
}
if (correctGuesses.size() == 7){
System.out.println("You won!");
}
else {
System.out.println("You had " + correctGuesses.size() + " numbers correct: " + correctGuesses);
}
I suggest not to use arrays at all, since they might be pretty complex to use. If you use Collection types, you have a lot of handy shorthand methods. Instead of looping over the array with winning numbers to see if the userNumber is in it, you can just use contains(userGuess). You also don't need to save everything. If you don't need to save the numbers the user has guessed, you could just not store them and only work with the current guess. For example:
System.out.println("Pick 7 numbers between 1 and 39: ");
for(i = 0; i < 7; i++) {
int currentGuess = reader.nextInt();
if (winningNumbers.contains(currentGuess)) {
correctGuesses.add(currentGuess);
}
}
But if you want to make sure that the user played distinct numbers in your lottery, you will want to save the users guesses. So you can use a Set again, and add the guess every time the user guesses. You could use a while loop to keep asking for a number until the user has given you 7 unique numbers. Something like this:
while (guessedNumbers.size() < 7){
int currentGuess = reader.nextInt();
guessedNumbers.add(currentGuess);
if (winningNumbers.contains(currentGuess)) {
correctGuesses.add(currentGuess);
}
}
This should give you enough material to go refactor the other code with all the hints of JB Nizet and Alex.
May I mention one extra thing: try to use methods and variables with intention revealing names. You are doing good already, but try to be as specific as possible, if the int contains 1 guess, call it guessedNumber and not guesses. Or if the user has won when the counter is 7, you could introduce a boolean won for example, or an extra method. I must say the code looks pretty good already, considering the fact that you are struggling with arrays.

Java: Unable to get Median calculated with code

I have two files that I am using for my Array median code. The first file( ArrayMedian.java) is used to collect and then calculate the median, the second file is the tester file ( ArrayMedianTest.java)
I was supplied with some source code and needed to modify it accept a set range for each number in the dataset. I got that part done and the random range displays, but now when I get to he array it no longer calculates, I really can't put my finger on what is going wrong.
Another thing I am trying to do is in the ArrayMedian, is put a while loop in there to make it terminate if a '0' is input for the dataset, but it does not seem to want to work in that file, could it be due to no main in the file?
package bonus2.u06.exercise.ex3;
import java.util.Scanner;
public class ArrayMedian {
private int[] arr; // just declare array
Scanner keyboard; // shared field
// initialize keyboard and array
public void init() {
keyboard = new Scanner( System.in );
System.out.print("Enter the dataset size: ");
int size = keyboard.nextInt(); // must be odd number
arr = new int[ size ]; // instantiate
}
// Randomize the array
public void getRange() {
//System.out.println("\nYou entered: ");
System.out.print("Enter a Range: ");
int range = keyboard.nextInt();
System.out.print("array: \n");
for(int i = 0; i < arr.length; i++){
int myRnd = (int)( range * Math.random() );
System.out.print(" " + myRnd + " ");
}
}
// find the median of array
public int calcMedian() {
int half_length = arr.length/2;
for (int i = 0; i < arr.length; i++) {
int count = 0;
for (int j = 0; j < arr.length; j++) {
if (arr[i] > arr[j])
count++;
}
if (count == half_length) {
//<========= terminate this method
return arr[i];
}
}
return 0;
}
}
ArrayMedianTest:
package bonus2.u06.exercise.ex3;
public class ArrayMedianTest {
public static void main(String args[]) {
// instantiate
ArrayMedian obj = new ArrayMedian();
// execute all methods
obj.init();
obj.getRange();
int median = obj.calcMedian();
System.out.println("\nmedian : " + median);
System.out.println("\n--- done ---");
}
}
Turn out, your algorithm works perfectly fine, except in the getRange() method, you forgot to set the values of the array, so the array is an array of zeros. Here is how it should look:
public void getRange() {
//System.out.println("\nYou entered: ");
System.out.print("Enter a Range: ");
int range = keyboard.nextInt();
System.out.print("array: \n");
for(int i = 0; i < arr.length; i++){
int myRnd = (int)( range * Math.random() );
System.out.print(" " + myRnd + " ");
arr[i] = myRnd; // <-- You missed this line right here!
}
}
Also, as a recomendation, if you want to put code in stackoverflow, it has to have a spacing of four at the begining of the line plus any indenting you might use. Good luck programming!

Random Dice Generator

A run is a sequence of adjacent repeated values . Write a program that generates a sequence of random die tosses and that prints the die values, marking only the longest run. The program should take as input the total number of die tosses (ex 10), then print:
1 6 6 3 (2 2 2 2 2) 5 2
Im quite confused on how to compare each number in order to get the correct output. Maybe using an array to store the values. Any answers or input will be of help thank you!
import java.util.Random;
import java.util.Scanner;
public class Dice
{
Random generator = new Random();
Scanner keyboard = new Scanner(System.in);
public void DiceCount()
{
int count;
int sides = 6;
int number;
System.out.println("How many die? ");
count = keyboard.nextInt();
for(int i=0; i < count; i++)
{
number = generator.nextInt(sides);
System.out.print(number);
}
}
}
First, replace int number; with int[] numbers = new int[count];. Next, replace number = ... with numbers[i] = ....
This will give you an array of random numbers (don't print them yet!). As you generate your numbers, note how many equal numbers you get in a row (add a special counter for that). Also add variable that stores the length of the longest run so far. Every time you get a number that's equal to the prior number, increment the counter; otherwise, compare the counter to the max, change the max if necessary, and set the counter to 1. When you update the max, mark the position where the run starts (you can tell from the current position and the length of the run).
Now it's time to detect the longest run: go through the numbers array, and put an opening parenthesis where the run starts. Put a closing parenthesis when you reach the end of the run, and finish the printing to complete the output for the assignment.
import java.util.Random;
import java.util.Scanner;
public class Dice {
Random generator = new Random();
Scanner keyboard = new Scanner(System.in);
public void DiceCount() {
int sides = 6;
System.out.println("How many die? ");
int count = keyboard.nextInt();
int[] array = new int[count];
int longestLength = 1, currentLength = 1, longestLengthIndex = 0, currentLengthIndex = 1;
int currentNum = -1;
for (int i = 0; i < count; i++) {
array[i] = generator.nextInt(sides);
System.out.print(array[i] + " ");
if (currentNum == array[i]) {
currentLength++;
if (currentLength > longestLength) {
longestLengthIndex = currentLengthIndex;
longestLength = currentLength;
}
} else {
currentLength = 1;
currentLengthIndex = i;
}
currentNum = array[i];
}
System.out.println();
for (int i = 0; i < count; i++)
System.out.print((i == longestLengthIndex ? "(" : "") + array[i] + (i == (longestLengthIndex + longestLength - 1) ? ") " : " "));
}
}
Note: this will only take the first longest range. So if you have 1123335666 it will do 112(333)5666.
If you need 112(333)5(666) or 1123335(666) then I leave that to you. It's very trivial.
import java.util.Random;
public class Dice {
public static void main(String[] args) {
//make rolls
Random rand = new Random();
int[] array = new int[20];
int longestRun = 1;
int currentRun = 1;
int longestRunStart = 0;
int currentRunStart = 1;
System.out.print("Generated array: \n");
for (int i = 0; i < array.length; i++) {
array[i] = rand.nextInt(6); //add random number
System.out.print(array[i] + " "); //print array
if (i != 0 && array[i - 1] == array[i]) {
//if new number equals last number...
currentRun++; //record current run
if (currentRun > longestRun) {
longestRunStart = currentRunStart; //set index to newest run
longestRun = currentRun; //set above record to current run
}
} else {
//if new number is different from the last number...
currentRun = 1; //reset the current run length
currentRunStart = i; //reset the current run start index
}
}
//record results
System.out.print("\nIdentifying longest run: \n");
for (int i = 0; i < longestRunStart; i++) { System.out.print(array[i] + " "); } //prints all numbers leading up to the run
System.out.print("( "); //start parentheses
for (int i = longestRunStart; i < (longestRunStart + longestRun); i++) { System.out.print(array[i] + " "); } //prints the run itself
System.out.print(") "); //end parentheses
for (int i = (longestRunStart + longestRun); i < 20; i++) { System.out.print(array[i] + " "); } //all remaining numbers
}
}```

Categories