Random 2d array isn't being printed - java

public class Alfabhto {
int[][] pinakas = new int[3][6];
String[] gramata ={"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter an alphanumeric combination");
String fail = s.nextLine();
System.out.println(pinakas[i][j]);
}
public int[][] Numbers() {
Random rand = new Random();
for (int i=0;i<3;i++)
{
for (int j=0;j<6;j++)
{
pinakas[i][j] = rand.nextInt(38)-12;
}
}
return pinakas;
}
}
First of all, I am very new at java. The main function works properly and the user is asked to give an input. Some elements aren't used here (like the gramata array) so ignore them.
The problem is: the method numbers should fill the pinakas array with random numbers and then print them. It does nothing if it's in the method. Outside it brings up errors because it can't get "pinakas" array or i and j. Any ideas?

There is several issues with that code, see comments:
// Need to import Random
import java.util.Random;
public class Alfabhto {
String[] gramata ={"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
// This neesd to be final for Numbers to access it
final int[][] pinakas = new int[3][6];
// There's no reason for Numbers to be public, or to extend Alfabhto, or in
// fact to be a class at all. Recommend making it a static method within
// Alfabhto (in which case gramata and pinakas must also be static), or an
// instance method if appropriate (in which case pinaka does not need to be
// final anymore, though you might leave it that way if you never
// intend to replace the array with a different one.
// Also recommend making that method (static or instance) a private method.
public class Numbers extends Alfabhto {
public Numbers() {
// Create this once and reuse it
Random rand = new Random();
// Note using <, not <=, on the loops
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 6; j++) {
pinakas[i][j] = rand.nextInt(38) - 12;
System.out.println(pinakas[i][j]);
}
}
}
}
// Since Numbers is an inner class, we need to be able to create instances of Alfabhto
private Alfabhto() {
}
// We need something in Alfabhto to run the Numbers constructor
private void run() {
// Run the code in the Numbers constructor
new Numbers();
}
public static void main(String[] args) {
/* None of this does anything, presumably you'll use it later...
Scanner s = new Scanner(System.in);
System.out.println("Enter an alphanumeric combination");
String fail = s.nextLine();
*/
// Run our run method, which will run the code in the Numbers constructor
new Alfabhto().run();
}
}

In your main function, you never create an instance of Numbers so whatever your wrote in there is not being called. Once you create a new Numbers(), it should print something out.

Related

Program continues to run after method is finished

I have made a simple program, with two classes. The method works fine, however it continues to run after completing my method resulting in this being seen in the output and I have no idea why:
Your myArrayOne method calls itself. That's the problem with infinite recursion.
public static int myArrayOne() {
// that's the problem
return myArrayOne();
}
That is probably what are you trying to accomplish:
// void --> List<Integer>
// static
public List<Integer> myArrayOne() {
ArrayList<Integer> packOfCards = new ArrayList<Integer>();
Random rand = new Random();
for (int j = 0; j<5; j++)
{
pick = rand.nextInt(10);
packOfCards.add(pick);
}
// myArrayOne(); --> packOfCards
return packOfCards;
}
public static void main(String[] args) {
myattributes attributes = new myattributes();
List<Integer> values = attributes.myArrayOne();
}

How do you make an Arraylist of RandomNumber integers? java

So I am relatively new to the programming scene and I am confused as to why my code doesn't work. I am trying to make an arraylist of flowers and then use a random number generator to create a random number of certain flowers, and store them in the array. In my logic, I thought that I created a variable to store the numbers (ex randomRoses) and stored the number in the array so I could easily print out how many of each flower there is by just calling the arraylist and the position. (ex flowerArray[0] would print out 8 Roses) but sadly it does not.
public class Flower
{
private int randomRoses;
private int randomTulips;
private int randomOrchids;
public ArrayList <Integer> flowerArray;
public Flower()
{
r = new Random();
t = new Random();
o = new Random();
int randomRoses = (r.nextInt(10) + 0);
int randomTulips = (t.nextInt(10) + 0);
int randomOrchids = (o.nextInt(10) + 0);
flowerArray = new ArrayList<Integer>
}
public void add2Array ()
{
flowerArray.add(randomRoses); //flowerArray[0] is the # of roses
flowerArray.add(randomTulips); //flowerArray[1] is the # of tulips
flowerArray.add(randomOrchids); //flowerArray[2] is the # of orchids
}
public void printArray()
{
System.out.println(flowerArray[0]);
}
You can use the same random object, no need to create 3 instances of it for the random integer generation,
Random r = new Random();
for (int i = 0; i < 3; i++) {
flowerArray.add(r.nextInt(10));
}
System.out.println(flowerArray);
you can not do flowerArray[0] because you have an arrayList and not an array.
you can instead do: flowerArray.get(0) for getting the integer at pos zero
Here your array list is associated with a class object. When you initialize your array list you need to add your entries to the array list in the constructor itself. So when you say object.printArray() its actually returning you the empty array list, that's why you are getting 0 every time. Try This.
class Flower
{
private int randomRoses;
private int randomTulips;
private int randomOrchids;
public ArrayList<Integer> flowerArray;
public Flower()
{
Random r = new Random();
Random t = new Random();
Random o = new Random();
int randomRoses = (r.nextInt(10));
int randomTulips = (t.nextInt(10));
int randomOrchids = (o.nextInt(10));
System.out.println(randomRoses);
System.out.println(randomTulips);
System.out.println(randomOrchids);
flowerArray = new ArrayList<Integer>();
flowerArray.add(randomRoses); //flowerArray[0] is the # of roses
flowerArray.add(randomTulips); //flowerArray[1] is the # of tulips
flowerArray.add(randomOrchids); //flowerArray[2] is the # of orchids
}
public void printArray()
{
System.out.println(flowerArray.get(0));
}
}
public class Test {
public static void main(String[] args) {
Flower f = new Flower();
f.printArray();
}
}
And in array list you can get elements by using get(index) method.
This will give the output you expect.
public void printArray
{
System.out.println(flowerArray.get(0)+" Roses");
System.out.println(flowerArray.get(1)+" Tulips");
System.out.println(flowerArray.get(2)+" Orchids");
}
Also you missed a semi-colon after the statement defining the arraylist.
Make the correction:
flowerArray=new ArrayList<Integer>;
How did it compile without that semi-colon?
It is not working because your syntax for getting the ith flower is wrong.
You're using a java.util.ArrayList so the correct way to get an object from that ArrayList is by calling the get() method.
System.out.println(flowerArray.get(0));
Hope that helps.

Code 'running' forever in Java

I am pretty new at Java and I am finding difficulty in solving the problem. Basically the code get a number, and generate a vector in the function generateVector. When I run this code, I am asked to put a number and then the software stay running forever. If possible, could you guys help me without other functions that is kind advanced? I am still learning. Thanks.
import java.util.Scanner;
public class Atividade02 {
static Scanner dados = new Scanner(System.in);
static int n;
//Main
public static void main(String args[]){
System.out.println("Type a number: ");
n = dados.nextInt();
int[] VetorA = generateVector(n);
for(int i=0; i<VetorA.length; i++){
System.out.println("Position: "+ VetorA[i]);
}
}
//Função
public static int[] generateVector(int n){
int[] VetorA = new int [n];
for (int i=0; i<n; i++){
VetorA[i] = dados.nextInt();
}
return VetorA;
}
}
I am asked to put a number and then the software stay running forever.
Did you enter in the n numbers required by generateVector? The program is probably just blocked on input from the user.
Try to modfiy the class as follows:
import java.util.Scanner;
public class Atividade02 {
// Added private access modifiers for properties.
// It's not necessary here, but as a general rule, try to not allow direct access to
// class properties when possible.
// Use accessor methods instead, it's a good habit
private static Scanner dados = new Scanner(System.in);
private static int n = 0;
// Main
public static void main(String args[]){
// Ask for vector size
System.out.print("Define vector size: ");
n = dados.nextInt();
// Make some space
System.out.println();
// Changed the method signature, since n it's declared
// as a class (static) property it is visible in every method of this class
int[] vetorA = generateVector();
// Make some other space
System.out.println();
// Show results
for (int i = 0; i < vetorA.length; i++){
System.out.println("Number "+ vetorA[i] +" has Position: "+ i);
}
}
// The method is intended for internal use
// So you can keep this private too.
private static int[] generateVector(){
int[] vetorA = new int[n];
for (int i = 0; i < n; i++) {
System.out.print("Insert a number into the vector: ");
vetorA[i] = dados.nextInt();
}
return vetorA;
}
}
Also when naming variables stick with the Java naming convention, only classes start with capital letters.

Print random integers without duplicates [duplicate]

This question already has answers here:
Generating Unique Random Numbers in Java
(21 answers)
Closed 9 years ago.
I have this assignment:
Print 5 random integer between 1-52 with no duplicate using if/else.
Here's my code so far. It prints some numbers, but it sometimes prints duplicates.
import java.util.Random;
public class RandomCards {
public static void main(String[] args) {
Random randomCards = new Random();
int card;
for (int x = 1; x <= 5; x++) {
card = randomCards.nextInt(52) + 1;
}
if (card != randomCards) // if the value of card is not equal, proceed
{
System.out.print(card + " ");
} else {
return card; // if the value are the same get random integers again
}
}
}
public static void main(String args[]) {
Random randomNumber = new Random();
// Set stores only Unique values
Set<Integer> cards = new HashSet<Integer>();
// Iterate over to generate random numbers
while (cards.size() < 5) {
int r = randomNumber.nextInt(52) + 1;
cards.add(r);
}
for(Integer card : cards) {
System.out.println(card);
}
}
You can use this
Random randomCards = new Random();
int[] card={0,0,0,0,0};
while(card[card.length-1] == 0) {
int temp=randomCards.nextInt(52);
for(int j=0;j< card.length ; j++){
if(card[j] == 0){
card[j] = temp;
break;
}
}
}
for(int j=0;j< card.length ; j++){
System.out.println(card[j]);
}
It's not clear what you're asking, but I note from your code that you don't have any duplicate detection. You need to save each value that you generate and check for duplicates when you create a new one. I suggest creating a Set<Integer> to hold your generated values, calling add() for each new card, and checking contains() to see whether a new value has already been selected. You'd want to change your loop condition to something like cards.size() < 5 as well.
Finally, note that your use of return card is incorrect and will result in a compile-time error. return is used to end a method and send a value back to where it was called from; the main method (which is always void) has no return value, and ending the method wouldn't make sense there anyway. It looks like some code may have been copied and pasted from a version where drawCard() was its own method. Instead, just keep looping until you find 5 unique cards (such as by using the size() method I mentioned earlier).
Maybe this?
Random rand = new Random();
// ArrayList to store non-duplicate cards.
ArrayList<Integer> cards = new ArrayList<Integer>();
// Iterate over to generate random numbers
while (cards.size() < 5)
{
int r = rand.nextInt(52) + 1;
if (!cards.contains(r))
cards.add(r); // Only add if there is no such number in list
}
Hope this helps.
Hope this would be of any help.
It comprises of separate methods for computation, setting the lower and upper bound and printing the list when it has 5integers in it. Using TreeSet solves your problem of duplicates. Here it goes,
package com.project.stackoverflow;
import java.util.Random;
import java.util.Scanner;
import java.util.TreeSet;
public class RandomGenerator {
public TreeSet<Integer> compute() {
TreeSet<Integer> generatedList = new TreeSet<Integer>();
Scanner s = new Scanner(System.in);
System.out.println("Enter the lower bound for checking random numbers:");
long lowBound = s.nextLong();
System.out.println("Enter the upper bound for checking random numbers:");
long topBound = s.nextLong();
Random randomNumbers = new Random();
for (int i = 0; i < topBound; i++) {
if (generatedList.size()==5) {
break;
}
else {
generatorFunc(lowBound, topBound,randomNumbers,generatedList);
}
}
return generatedList;
}
public void generatorFunc(long lowBound,long topBound,Random randomNumbers, TreeSet <Integer> generatedList) {
long limit = topBound - lowBound;
long part = (long)(limit * randomNumbers.nextDouble());
int randomNum = (int) (part + lowBound);
generatedList.add(randomNum);
}
public void printList() {
TreeSet<Integer> testListVals = compute();
System.out.println("New" + testListVals);
}
public static void main(String[] args) {
RandomGenerator obj = new RandomGenerator();
obj.printList();
}
}
If your problem is just about the duplicates, then you can store each random number generated in an array, and for every successive call to nextint(), check if it already exists in the array of stored values, and till it does, call nextint() again for that iteration itself, else store it in the array and go to next iteration.

How to instantiate a new public Java class if a parameter is required?

I need an array to be public (accessible to other methods in the class) but the array needs an input value "T" to create it. How do I instantiate a "global" variable that requires user input?
My code is as follows:
public class PercolationStats {
**private double myarray[];**
public PercolationStats(int N, int T) {
**double myarray = new double[T];**
for (i=0;i<T;i++) {
Percolation percExperiment as new Percolation(N);
//do more stuff, make calls to percExperiment.publicmethods
myarray[i] = percExperiment.returnvalue;
}
}
public static void main(String[] args) {
int N = StdIn.readInt();
int T = StdIn.readInt();
PercolationStats percstats = new PercolationStats(N, T);
//do more stuff, including finding mean and stddev of myarray[]
StdOut.println(output);
}
Another example in pseudocode:
class PercolationStats {
Constructor(N, T) {
new Percolation(N) //x"T" times
}
Main {
new PercolationStats(N, T) //call constructor
}
}
class Percolation {
Constructor(N) {
**new WQF(N)** //another class that creates an array with size dependent on N
}
Main {
**make calls to WQF.publicmethods**
}
}
In the second example, it seems to me that I need to have the new instance of class WQF made in the constructor of the Percolation in order to accept the parameter N. However, WQF would not be accessible to the Main method of Percolation.
Help!
Don't include the type declaration in your constructor. You are creating a local variable that masks the field. It should look like this:
public class PercolationStats {
public double myarray[];
public PercolationStats(int n, int y) {
myarray = new double[t];
for (i=0; i<t; i++) {
Percolation percExperiment = new Percolation(n);
//do more stuff, make calls to percExperiment.publicmethods
myarray[i] = percExperiment.returnvalue;
}
}
public static void main(String[] args) {
int n = StdIn.readInt();
int t = StdIn.readInt();
PercolationStats percstats = new PercolationStats(n, t);
//do more stuff, including finding mean and stddev of myarray[]
StdOut.println(output);
}
}
There's certainly no problem using a variable as the length when creating a new array.
Tedd Hopp's answer corrects the bug in your code.
I'd just like to point out that myarray is NOT a global variable.
Java doesn't have global variables,
the closest it has is static variables, and
myarray isn't one of those either. It is an instance variable, as you have declared it.
(And an instance variable is the right way to implement this ... IMO)

Categories