Problems with two 2D arrays, not iterating correctly - java

i have two 2D arrays for a class called quiz. My logic of manipulating these arrays is not correct as i'm not getting the corrected output i expected. I would appreciate if someone can check my logic and help me figure out what i'm doing wrong:
Here are my arrays:
public String [][] questions ={
{"L1Q1","L1Q2","L1Q3"},
{"L2Q1","L2Q2","L2Q3"},
{"L3Q1","L3Q2","L3Q3"},
{"L4Q1","L4Q2","L4Q3"},
{"L5Q1","L5Q2","L5Q3"}};
public String [][] answers = {
{"A1Q1","A1Q2","A1Q3"},
{"A2Q1","A2Q2","A2Q3"},
{"A3Q1","A3Q2","A3Q3"},
{"A4Q1","A4Q2","A4Q3"},
{"A5Q1","A5Q2","A5Q3"}};
I also have two variables, one called numQuestion, and numQuiz. and I'm passing these two as indexes to the questions array. I'm also using these two indexes to in the answers array. I want to compare if the answer at the specific cell of the 2d array corresponds to the correct answer of the question. Here is a snipped of my code that i wrote to do that:
public void review(String answer) {
int y = questionNum;
int x = quizVal;
if( answer.equals(answers[x][y])){
currentQuestionCorrect = true;
} else {
currentQuestionCorrect= false;
}
}//end of review
my program is running and it's working, but the review method keeps saying that my answers are wrong when they are correct. can someone please help me

Have you checked that when you click on first line you set x to 0 and not to 1 ? Idem for column.

Related

Arrays.toString returning odd result (Appear to be memory addresses) [duplicate]

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 7 years ago.
I'm trying to create this two dimensional array in java and print the output, but when it outputs I am not getting the numbers or a two-dimensional structure. Java appears to be giving me what looks like memory addresses for each array result.
My code
public static int[][] generateSampleTable(int smallest, int largest, int sampleSize)
{
int sampleTable[][] = new int[sampleSize][2];
for (int i = 0; i < sampleSize; i++)
{
sampleTable[i][0] = 5150;
sampleTable[i][1] = 2738;
}
return sampleTable;
}
public static void main(String[] args){
System.out.println(Arrays.toString(generateSampleTable(1,1,10)));
}
My output appears like this:
[[I#803816, [I#22b4b7, [I#1079ed1, [I#231c5d, [I#178cf47, [I#d65c13, [I#1fca60e, [I#1f99518, [I#fa7e97, [I#90925f]
Ignore the smallest and largest arguments in that method as I haven't implemented the calculations for them yet and am not using them right now.
Other than what you see here, I guess I should tell you that yes, I imported java.util.Arrays
Not sure what is going on. Any help would be appreciated.
Thanks
Arrays.toString() knows how to print 1 dimensional arrays. For 2-dimensional arrays you should use Arrays.deepToString().

Generate multiple draws (calls) of a given method in java (simulated lottery)

I received the task of simulating a lottery draw in java. The program skeleton yields the method generateOneDraw, which creates 6 random numbers between 1 and 49
static int[] generateOneDraw() {
int numbers[] = new int[NUMBER_OF_ELEMENT_PER_DRAW];
for(int i=0; i<numbers.length; ++i) {
int nextNumber;
do {
nextNumber = generateNextRandomNumber();
} while(numberIsInArray(nextNumber, numbers));
numbers[i] = nextNumber;
}
return numbers;
}
We are then required to implement a function that simulates the lottery draw over 5 weeks and stores them in the variable draws. I believe this should be done over a two-dimensional array. Am I right in this way of thinking? Any pointers on implementing it would be greatly appreciated.
static void generateAllDraws()
Thanks in advance.
EDIT: Nevermind, I did it with a simple two dimensional array and it worked.
Since this seems like home work, I will not go into much detail but you can either:
Create a 2 dimensional list, as per your initial reasoning;
Create a Draw class which represents a lotto draw, and create multiple instances of this class. Each Draw class could have a Date which would denote when did the draw take place.
Both approaches should work, the second approach is a little more object oriented.

Deleting and Inserting Elements in Array [duplicate]

This question already has answers here:
How to remove specific element from an array [duplicate]
(6 answers)
Closed 8 years ago.
public class Example {
public static void main(String [] args) {
String [] wombology;
wombology = new String[3];
wombology[0] = "History of Wombology";
wombology[1] = "Why Wombology";
wombology[2] = "Wombology and Me";
Random book = new Random(System.currentTimeMillis());
Scanner choice = new Scanner(System.in);
String yourChoice;
do {
System.out.println("Press enter for random book");
yourChoice = choice.nextLine();
if(yourChoice.equals("")) {
System.out.println(wombology[randomizer.nextInt(3)]);
System.out.println();
}
if(yourChoice == "EXIT") {
break;
}
} while(!yourChoice.equals("EXIT"));
}
}
How could I take out a "book" from the array once chosen randomly?
How could I put back in said "book" later back into the array?
Example: "History of Wombology" is randomly chosen and is taken out.
The next random selection should NOT include "History of Wombology" until it is put back in.
Meaning only "Why Wombology" and "Wombology and Me" should be the only possible choices.
I'm assuming that this is homework and an ArrayList is not possible. And I don't want to give a full, detailed answer.
One option might be to create a parallel array, boolean isCheckedOut[], and track your books there.
You need to manage the array yourself. That means you need to know the real size of the array and the filled size. This is because once the array is created the size cannot change.
If you delete an object from the array you need to shift the adjacent elements towards that position.
For example, your array looks like this:
[A|B|C|D|E|F]
allocatedArraySize = 6
currentSize = 6
If you delete C which is at position 2 then you must shift D, E, F to the left. You could also make the last position null.
[A|B|D|E|F|null]
allocatedArraySize = 6
currentSize = 5
To insert, simply use this:
// Check Array is not full.
if(currentSize != allocatedArraySize)
{
// Then add your object to the last position in the array.
array[currentSize] = obj;
// Increment the index.
currentSize++;
}
else
{
// Don't allow insertion.
// Or create a new-bigger-array;
// then copy all elements of the full array into it.
}
You have to "define" an action for "taking out a book" on the technical level. I can image two possibilities for this
setting the array content at the specific position to null
setting the array content at the specific position to an empty string
As the title of most books consists of one or more letters, the empty string-proposal seems also to be valid.
The second task (putting a book back into the array) can be handled in a similar way. Here you have to find an empty place (an array position with an empty string/null as content) and assign the name of the book to it.
Concerning the randomizer and not allowing already removed books: you can use the aforementioned condition to rerun the randomizer, i.e until an non-empty string/not-null element is found in the array. If you found one, it is a valid choice. But beware, if you removed all books, the randomizer would never stop running (because it finds only invalid choices and hence never returns). Here you can use an additional check condition: if the array only consists of empty strings/ null values, it is not required to run the randomizer.
Hope that helps...

Array in for loop

I'm new to stack overflow so sorry for anything that might consider me a newbie.
I understand java to a certain degree, however, i am stuck on one thing i hope you guys can help me on.
I am in the process of making a floating point simulator and i am struggling on this section of the code.
I need the next part of the array [1] to reach the total length of the mantissa my knowledge with arrays in java are not exactly the best so any help would be much appreciated.
Thanks
public float toDecimal()
{
/**
* Convert Exponent and find shift
*/
char[] mantissaCharArray = mantissa.toCharArray();
int mantissaLength = mantissaCharArray.length;
float[] mantissaMultiplierArray = new float[mantissaLength];
mantissaMultiplierArray[0]= 1;
for (mantissaMultiplierArray[1];mantissaCharArray;mantissaMultiplierArray++)
{
//for loop to cover array from [1] to the lengthmantissa
}
//each one multiply current
}
Try this,
for (int i=(int)mantissaMultiplierArray[0];i< mantissaCharArray.length;i++)
{
//
}
mantissaMultiplierArray[0] will return float value.
So you want to run through each element of an array? You are right with the for loop, just wrote it wrong. It should go something like this;
for(int i = (int)mantissaMultiplierArray[0]; i < mantissaCharArray.length; i++)
{
System.out.println(mantissaMultiplierArray[i]);
}
Let me explain the setup of this for loop a bit more;
You are setting an integer value i to the first value of mantissaMultiplierArray. You are also parsing it as an int because it is a float, hence the (int)
You give i a limitation - the total size of the mantissaCharArray
increment i
In the for loop I have it set to print out the values of the mantissaMultiplierArray for each value of i, but yu can do whatever you want inside of it.

why is this method returning null? (calling a set of strings from an array)

I'm working on (what is to a beginner) a rather complex assignment. I think I've got the jist of it down, but I'm having trouble with it printing "null" after Monday-Sunday are entered into the dialog box. Also, the goal of the assignment is, later, for the user to enter a number 0-6 and then the corresponding weekday (from the String[] weekArray set in the method) is printed. I'm not really sure how to do this and my book doesn't seem to be showing me the way, but am I even going to be able to do that the way my code is set up? Thanks and best regards. Here's the code.
EDIT - there's an example in my book under returning an array from a method. I'm not sure if it's applicable to my assignment as they seem to have different goals, but here it is..
EDIT#2 - instructions for reference to what I'm doing.
EDIT#3 - my interpretation of the example for passing methods to arrays.
EDIT #4 - solved the issue. I was going about it the wrong way for much. The book's example wasn't much help. Thanks to those of you who replied. I deleted the homework assignment description in consideration of the professor (who probably wouldn't like his assignments on the internet next semester)
Excerpt of the code below... I was making this way more complicated than it was
public static String[] getWeek() {
String[] weekArray = new String[7];
for (int i = 0; i < weekArray.length; i++) {
weekArray[0] = JOptionPane.showInputDialog("Enter 'Monday'. ");
if (weekArray[0].compareTo("Monday") > 0) {
weekArray[0] = JOptionPane.showInputDialog("Enter 'Monday'. ");
Your branches have unreachable statements -
weekArray[5] = ...
while(weekArray[5].equalsIgnoreCase(null)) {
// Cannot reach this point as equalsIgnoreCase(null) always returns false.
}
From String#equalsIgnoreCase:
true if the argument is not null and the Strings are equal, ignoring case; false otherwise.
Emphasis mine.
EDIT: From your edit above you appear to be having trouble with populating an array. The rough idea is:
public static void main(String[] args) {
// Just an example
int[] values = new int[5];
System.out.println(Arrays.toString(values));
populateArray(values);
System.out.println(Arrays.toString(values));
}
private static void populateArray(int[] toBePopulated) {
toBePopulated[0] = 42;
toBePopulated[1] = 11;
// Etc. Again, just an example.
}
This will print:
[0, 0, 0, 0, 0]
[42, 11, 0, 0, 0]
The idea is that what is passed to the method populateArray is a reference to the location of the array in memory. That means that you can manipulate the contents of the array, and the change will be reflected in values afterwards.
I don't know if i got it right , but from a cursory look , seems you're mistaking the sunday part , guess it should be sth like :
if (weekArray[5].equalsIgnoreCase("Sunday")) // Note the "5"
Your cheek for string being null is probably not what you want. If you indent the code it would be easier to see.
After formatting this is what you have
while (weekArray[0].equalsIgnoreCase(null)) {
if (weekArray[0].equalsIgnoreCase("Monday"))
return weekArray[0];
}
So, if weekArray[0] is null, then you check if null equalsIgnoreCase("Monday"). This logic is not what you want.
After asking and checking all days you return null (at the end of the method). This si the null being printed.

Categories