Hey guys im making a game to help me study for finals. It is basically flash cards. I want the program to print out my question and answer by randomly selecting one. The thing is i dont want he same random number to be picked twice. how do i make sure the same number isn't picked twice till im out of questions? I am trying to make each random number be stored in blacklist so i can just check if the number is already in there before the program prints.
import java.util.ArrayList;
import java.util.Random;
public class Games {
static ArrayList<Integer> blacklist = new ArrayList<Integer>();
static int number;
static String[][] yes = {{"Apostolic Orgin", "Comes form the apostles"},
{"Biblical inerrancy", "the doctrine that the books are free from error reading the truth"},
{"Divine Inspiration", "the assistance the holy spirit gave the authors or the bible so they could write"},
{"fundamentalist approach", "interpretation of the bible and christian doctrine based on the literal meaning og bible's word"}, {"pentateuch", "first 5 books of old testament"}};
public static void main(String[] args) {
Printer(pickQuestion(), pickAnswer());
}
public static int RandomNumber(int i) {
int c;
Random r = new Random();
c = r.nextInt(i);
return c;
}
public static void Printer(String question, String answer) {
System.out.println("Question: " + question);
System.out.println("Answer: " + answer);
}
public static String pickQuestion() {
number = RandomNumber(yes.length);
return yes[number][0];
}
public static String pickAnswer() {
return yes[number][1];
}
}
The easiest option is to pre-shuffle the list of questions, either messing with the question and answer arrays directly, or by creating an array of integers from 1 to n where is the number of questions, shuffling that, and then loading the "card" in the position pointed to by that value in the array.
That is, create
[1,2,3,4,5]
Shuffle:
[5,1,3,4,2]
And load question 5, then question 1, etc.
This latter option would make a few things easier, not least of which is debugging!
Creating the array in order is a trivial for loop, and there are plenty of standard algorithms for shuffling too.
Random shuffling of an array
Related
I have set up an array to randomize 5 different numbers in one class. In a different class I have prompted a user to guess the random number, and must reference the number each time to determine whether they have guessed correctly or not. My issue is that the numbers being randomized are in the data type int[], and I need to compare them to the data type int. When trying to reference the randomized numbers I get the error "Type mismatch: cannot convert from int[] to int". Any advice on how I would do that?
Class diceNumGen
final static int ARRAY_SIZE = 5;
public static int[] randNumArray = new int [ARRAY_SIZE];
public static int[] randNums(){
for(int i=0; i < randNumArray.length; i++) {
randNumArray[i] = (int) (Math.random()*12);
System.out.println(randNumArray);
}
return randNumArray.clone();
}}
Class Bet
static Bet bet = new Bet();
diceNumGen newClassObj = new diceNumGen();
int secondArray = diceNumGen.randNumArray;
//Set Turns variable where turns = 5
public int turnsToGo = 5;
//Set up the bet() method
public void bet() {
//Sets up the options as an array to be on the JOptionPane, each are numbered 0, 1, and 2 respectively
String[] options = {"Guess below 7", "Guess 7", "Guess above 7"};
welcome here, I'm newcomer too, this is my first answer.
I assume that you are using java, because of keywords, it is good to define the programming language in the question or tags to get better responses.
the first thing about your code is you don't need a whole class for generating an array, an ordinary function like this would be OK too:
static int[] randomGen(int len){
java.util.Random rand = new java.util.Random();
int[] randoms = new int[len];
for (int i = 0; i < len; i++) {
randoms[i] = rand.nextInt(12);
}
return randoms;
}
the next thing is, please indent your code, un-indented code (or badly indented code) will confuse the reader.
and about your question, at the first point why are you creating random array with the size of 5? if you just need one random number, just create one random number (with your Math.random() or better, nextInt(12) in Random class)
if user have 5 chances to guess same number you don't need 5 random numbers. just use this:
int randomNumber = (int) (Math.random() * 12);
or if you want user to guess 5 separate numbers, you need a for loop to iterate this random array per user guess.
Good luck in learning java.
i've been trying to make a program that takes (for example) 3 cards at random.
But i don't want my program to grab the same card twice, so that means it can't have duplicates, but i don't know how to do this with a image Array.
String[] card = {
"Aclubs.png",
"2clubs.png",
"3clubs.png",
};
PImage[] cards = new PImage [card.length];
void setup() {
size(1000,1000);
randomCards();
drawCards();
}
int randomCards() {
int i = (round(random(0,2)));
cards[i] = loadImage(card[i]);
return i;
}
void drawCards() {
for (int g = 0; g < 12000; g = g+round((displayWidth * 0.9))/12) {
image(cards[randomCards()], 25+g, 50);
}
}
Instead of using an array, use an ArrayList. Then remove the cards you use. Here's a small example:
ArrayList<String> things = new ArrayList<String>();
things.add("cat");
things.add("dog");
things.add("lizard");
while (!things.isEmpty()) {
int index = int(random(things.size()));
String thing = things.remove(index);
println(thing);
}
Of course, this isn't the only way to do it. You could use a Java Set, or you could use a data structure that holds what you've already picked, or you could store all of the options in a data structure, then shuffle it, then just chose from an index that you increment. Or you could use one of the array functions in the reference to do it.
It's hard to answer general "how do I do this" type questions. Stack Overflow is designed for more specific "I tried X, expected Y, but got Z instead" type questions. So you really should get into the habit of trying things out first. Ask yourself how you would do this in real life, then look at the reference to see if there are any classes or functions that would help with that. Break your problem down into smaller pieces. Write down how you would do this in real life, in English. Pretend you're handing those instructions to a friend. Could they follow your instructions to accomplish the goal? When you have those instructions written out, that's an algorithm that you can start thinking about implementing in code. Staring at code you've already written won't get you very far. Then when you do get stuck, you can ask a more specific question, and it'll be a lot easier to help you.
I do have a problem, i have numbers from 1-49, now the question here is how do i get the maximum number of random sets of six from the given sample. like
int[] a1 = { 1, 2, 3 ,5,6,7 ... 49};
how many unique combination of numbers or arrays can i get from that one big array from 1 to 49 like below
1,2,3,4,5,6
2,1,4,5,8,9
2,1,0,2,4,5
................
What am trying to get is the maximum output or number of possible unique arrays with a length of six i could get . to be honest i have tried writing a loop that reads through the array, but how to capture six random digits is where am stuck i can go any further than
for(int x=0;<a1.length;x++)
{
// here i believe i must turn the captured information
// into a muti dimentional array to cpature like '1,2,3,4,5,6' but how. am stuck
}
If I understand your question correctly, what you need is the binomial coefficient n! / k! (n - k)!, which in this case would be 49! / (6! * (49 - 6)!) = 13983816. No need to write code if the only thing you want to know is the number of possible combinations.
If you really wanted to list all of them, you'd need a little patience. One way to achieve this is via a recursive approach:
public class NOverK {
private static final int[] numbers = new int[6];
private static final int MAX = 49;
private static void output() {
System.out.println();
for (int n : numbers) {
System.out.print(n + " ");
}
}
private static void allCombinations(int x, int start) {
if (x > 0) {
for (int i = start; i <= MAX; i++) {
numbers[numbers.length - x] = i;
allCombinations(x - 1, i + 1);
}
} else {
output();
}
}
public static void main(String[] args) {
allCombinations(6, 1);
}
}
This question has been asked at Stack Overflow a few times in the past. For example, look at this answer:
Click here: Algorithm to return all combinations of k elements from n
The answers to this question contain numerous solutions of your question in different programming languages (Java, Python, C, C# etc.), too. Check out or adjust a solution that meets your requirements.
You can search for other questions/answers in Stack Overflow (search field in upper right corner) with keywords
[algorithm] [combinations]
A Google search would lead to numerous solutions of your question, too. Try with keywords as follows:
java algorithm combinations without repetition
or
c# algorithm combinations without repetition
I tried search but many of the questions did not involve multiple values. The question I am trying to ask is given an array that represents the number of books own by a library, how can I count the number of books that begin with 'Q' and return that number.
I know that I need to use a charAt() to find the number, i'm just kind of stuck.
class Book {
String title, author; //title, author
String callNumber; // call Number, "QA567.23P54"
}
Book[] books = new books[27532];
This looks like a homework problem. I'll dodge around an exact answer and see if this amount of information helps you make progress.
for (int i = 0; i < books.length; i++) {
if (books[i].callNumber.charAt(0) == 'Q') {
System.out.println(books[i].title);
}
}
for (Book book : books) {
System.out.println(book.callNumber.charAt(0));
}
I've shown you two ways to write a loop through all the books. The first prints the title of the book if it starts with 'Q'. The second prints the first letter of every book title. What I did not do was declare a counter variable to keep track of how many 'Q's are found. See if you can make progress with this -
I'm taking a online Java course and attempting my 2nd assignment. The first assignment was not difficult but this one is just way over top. I honestly don't know where to begin. The problem is this class is online, basic instructions are to read these chapters and then write the program. There's not much guidance since my instructor is not with me physically.
I've never used scanner before or created two dimensional arrays. My instructor gives notes on what to do in each area of his skeleton program but I don't have a clue which one to start with.
Your task is to implement a similar scheme to store poynomials of any number of terms, such that the
number of terms and the components (coefficient, variable and exponent) of every term are entered from
the keyboard.
To implement the interactive input we will using the Java class Scanner, defined in the java.utils
standard package. The Scanner class can be used in Java to read data types from a file. Since the input
console (keyboard) is treated as the file called System.in, we can create a Scanner for that input stream
as new Scanner (System.in), as shown below. Once you define a Scanner object, using its method
next() you can read Strings from the file/keyboard.
The incomplete program below is your assignment. You are supposed to complete without changing the
existing code.
Your output should be the terms of the polynomial entered by the user, separated by + signs.
Additional instructions in the code below, that you will change to achieve the requested functionality.
import java.util.Scanner;
public class Polynomials {
public static void storeTerm (int coeff, String var, int exp, String poly[][], int
where){
//ENTER THE COEFFICIENT, VARIABLE AND EXPONENT INTO THE
//ARRAY POLY THAT REPRESENTS THE POLYNOMIAL, AT POSITION "where"
//THAT RANGES BETWEEN INDEX 0 AND POLY.LENGTH-1
}
public static void printTerm (String [] term) {
//PRINTS EACH TERM
//IF THE EXPONENT OF THE VARIABLE IS 1 DOE NOT PRINT THE EXPONENT
//IF THE EXPONENT IS 0, PRINT ONLY THE COEFFCIENT
//IF THE COEFFICIENT IS 1, DO NOT PRINT IT, UNLESS IT IS THE ONLY COMPONENT OF
//THE TERM
}
public static void printPolynomial(String terms[][]){
//CALL printTerm in a loop to print all terms separated by + signs
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int numberTerms = 0;
System.out.println("How many terms?");
numberTerms = sc.nextInt();
//ENTER HERE THE CODE TO CREATE THE TWO DIMENSIONAL ARRAY NEEDED TO STORE THE TERMS
//OF THE POLYNOMIAL
if (numberTerms <= 0)
System.out.println("Error: Polynomials must have at least one term");
else {
String coeff = "", variable="", exponent="";
for (int i = 1; i<= numberTerms; i++) {
System.out.println("Enter the coeffcient for term " + i);
coeff = sc.next();
System.out.println("Enter the variable name:");
variable = sc.next();
System.out.println("Enter the expoenent for this term");
exponent = sc.next();
//CALL METHOD storeTerm TO INPUT THIS NEW TERM INTO THE ARRAY WRITE THE CORRECT
//CALL TO storeTerm HERE
}
printPolynomial(terms);
}//endf if
}//end main
}//end class
Again not looking for answers. Just where to start. Then I'll post my results.
It is not completely obvious where the two-dimensional array enters, since the structure hints at a list of terms.
You will need to define a data structure, in Java as a class, to hold the information for each term.
From the description, it seems that the input are polynomials of the form 3x^2+5y^7 and not xy+3y^2z^3.