I'm new to coding and have been set a challenge of creating an method that prints out a multiplication array.
My code is as follows...
public class TimesTableArray
{
public static void main(String[] args)
{
int size = 12;
int number = 3;
}
private static int [] getTimesTable(int size, int number)
{
int[] timesTable = new int[size];
for (int i = 0; i < size; i++)
{
timesTable[i] = number * (i +1);
}
return timesTable;
}
}
I get the following output...
3
6
9
12
15
18
21
24
27
30
33
0
I need the 12th item to read 36, not 0. I know it's to do with the index reads from 0 to 11, but I don't know how to amend my code to make this so.
Please could someone guide me on how to do this?
You have a classic "off by one" error.
If you start at 1, then you INCLUDE the size, and have to subtract one to get the Index:
for (int i = 1; i <= size; i++)
{
timesTable[i - 1] = number * i;
}
If you start at 0, then you EXCLUDE the size, and have to add one when you multiply:
for (int i = 0; i < size; i++)
{
timesTable[i] = number * (i + 1);
}
You're going to have people swear up and down that one is correct and the other is wrong. This is down to preference. Do what "makes sense" to you.
In the population loop, you are iterating from 1 rather than 0 but you do not offset the terminal condition. I would rewrite you loop to follow the standard pattern rather than trying to bake in the offset. So...
for (int index = 0 ; index < size ; ++index) { ... }
This will allow the index to line up naturally in the assignment. Apply the offset in the calcuation.
timesTable[index] = number * (index + 1);
So you get...
private static int[] getTimesTable(int size, int number) {
int[] timesTable = new int[size];
for (int i = 0; i < size; i++) {
timesTable[i] = number * (i+1);
}
return timesTable;
}
You are having an off-by-one error. Since you want to have an array of 12 answers, starting with 1, your loop range has to be from 1 to 12 inclusive. Therefore:
private static int [] getTimesTable(int size, int number)
{
int[] timesTable = new int[size];
for (int i = 1; i <= (size); i++)
{
timesTable[i-1] = number * i;
}
return timesTable;
}
The reason why your last index was zero, is because numeric array indexes are initialized to zero after instantiation (new int[size]).
Related
I am pretty new to java and am just learning 2D arrays. I am trying to get the top 5 numbers to display from a random list. I think this could work but am not sure why I am getting an error. One other thing is that I cannot use the sort function.
Code here:
public static void main(String[] args) {
//Random Number stuff
Random rand = new Random();
int[] large = new int [5];
int max = 0, index;
int[][] arrSize = new int [4][5];
for (int i = 0; i < arrSize.length; i++) {
for (int j=0; j< arrSize[i].length; j++) {
arrSize[i][j] = rand.nextInt(89) + 10;
System.out.print(arrSize[i][j] + " ");
}
System.out.println();
}
// Top 5
for (int p = 0; p < 5; p++) {
max = arrSize [0][0];
index = 0;
for (int i = 0; i < arrSize.length; i++) {
for (int j = 0; j < arrSize[i].length; j++) {
if (max < arrSize[i][j]) {
max = arrSize[i][j];
index = i;
}
}
}
large[p] = max;
arrSize[index] = Integer.MIN_VALUE; //Error here
System.out.println("Highest Number: " + large[p]);
}
}
}
Error text:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Type mismatch: cannot convert from int to int[]
at secondAssignment.BiggestNumbersRectangular.main(BiggestNumbersRectangular.java:47)
I am not sure why I am getting an error, any help would appreciated. If anyone else has any answers for how I could get the top 5 in a different way that would also be appreciated.
You declare your arrSize here
int[][] arrSize = new int [4][5];
and try to set it's value here
arrSize[index] = Integer.MIN_VALUE;
The Object at arrSize[index] is an array.
Remember that a 2D array basically looks like this:
arrSize
- arrSize[0]
- arrSize[0][0]
- arrSize[0][1]
- arrSize[1]
- arrSize[1][0]
- arrSize[1][1]
- arrSize[2]
- arrSize[2][0]
- arrSize[2][1]
- arrSize[3]
- arrSize[3][0]
- arrSize[3][1]
Because index is a single int, you are assentially calling arrSize[0], which contains arrSize[0][0] and arrSize[0][1].
The Integer.MIN_VALUE is not an array of integers. It is an int. You cannot assign int to int[].
As you can see in other parts of the code, to access values in 2D array arrSize, you need 2 indexes in your case (and usually) i and j.
You need to save both i and j after you find the highest number.
if (max < arrSize[i][j]) {
max = arrSize[i][j];
indexI = i;
indexJ = j;
}
and then
arrSize[indexI][indexJ] = Integer.MIN_VALUE;
As to why you got the error, arrSize[i] gets you a 1D array. It's still an array and you cannot set an array to an integer (Integer.MIN_VALUE). in Java represented as int[] in the error message.
The algorithm could be improved, instead of using a single integer max for saving the highest value, you could use a maxArr of the same size as the number of highest numbers you want (in your case 5) and check against all of the numbers in maxArr using a for in place of
if (max < arrSize[i][j]) {
max = arrSize[i][j];
index = i;
}
That would mean you could remove the index (or indexI and indexJ) and topmost for cycle (for (int p = 0; p < 5; p++)). But that's another topic, and one you should learn yourself.
I would like to create a new array, based on minimum and maximum values in constant intervals. For example, suppose my min = 5 and max = 50 and steps = 5, how can I create a new array that starts at min and goes to max increments of steps?
So that my array can look like this : [5, 10, 15, 20...., 50]
I tried the following but it does not seem to work:
int myArr[] = {};
myArr[0] = min;
for(int i = min, i <= max; i++){
myArr[i] = min + step;
}
Any help or advice will be highly appreciated.
You didn't specify the size of the array. You should do as follows:
public class SOTest {
public static void main(String[] args) {
int min = 5; // use whatever you prefer
int max = 50; // use whatever you prefer
int step = 5; // use whatever you prefer
// now, determine size
// its a simple calculation, that
// determines how many elements would there be from min to
// max if we jump by step
int size = (max + step - min) / step;
int[] myArr = new int[size]; // while creating array you need to specify
// the size of the array, i.e. how many elements the array could hold
int val = min;
for(int i = 0; i <size; i++){
myArr[i] = val;
val = val + step;
}
for(int i=0; i<size; i++) {
System.out.print(myArr[i] + " ");
}
System.out.println();
}
}
And the output is:
5 10 15 20 25 30 35 40 45 50
[P.S.]: If anything is unclear, just ask me in the comment section...
I am very new to Java and am currently learning about arrays. Our homework this week is to
"Write a program that declares an array "alpha" of 50 elements of type "double". Initialize the array so that the first 25 elements are equal to the square of the index variable and the last 25 elements are equal to three times the index variable"
My question is this. Is the value in the element at an index position considered the index variable. For example if alpha[2] = 3 would 3 be the index variable, and in reading the assignment I would then square 3.
The other thought that I would have is that I have to square the index number [0],[1],[2]...
Thank you for any input, and I apologize if this is in the wrong area.
Thank you for the input so far. What I am trying to get to is what exactly is an "Index Variable"
Here is what I did
// Import various packages to be used in the program
import java.util.*;
import java.lang.*;
public class module5
{
static Scanner console = new Scanner(System.in);
public static void main (String[] args)
{
// Declare an array called alpha with 50 pre-defined elements
double []alpha = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50};
// Process the first 25 elements
for (int i = 0; i < 25; i++) {
// Square the first 25 elements
alpha[i] = Math.pow(alpha[i], 2);
}
// Process the second set of 25
for (int i = 25; i >= 25 && i < 50; i++) {
// Multiply by 3
alpha[i] = alpha[i] * 3;
}
for (int i = 0; i < alpha.length; ++i) {
System.out.print(alpha[i]);
if (i % 10 == 9) {
System.out.println();
} else {
System.out.print(" ");
}
}
}
}
No. In alpha[2] = 3 2 is the index variable, and 3 is the value being indexed. The other thought that I would have is that I have to square the index number [0],[1],[2] Correct.
alpha[0] = 0 * 0;
alpha[1] = 1 * 1;
alpha[2] = 2 * 2;
// ...
alpha[25] = 3 * 25;
// ...
alpha[49] = 3 * 49;
You are expected (I think) to use a loop with a conditional (but you might also use two separate loops with different initial and terminal conditions) to do these assignments.
You are dealing with int(s), so use an int[]. Something like,
int[] alpha = new int[50];
Then you might use a single for loop like,
for (int index = 0; index < alpha.length; index++) {
if (index < 25) {
alpha[index] = index * index;
} else {
alpha[index] = index * 3;
}
}
or two loops like
for (int index = 0; index < 25; index++) {
alpha[index] = index * index;
}
for (int index = 25; index < alpha.length; index++) {
alpha[index] = 3 * index;
}
or using a ternary (conditional operator ? :) and a loop like
for (int index = 0; index < alpha.length; index++) {
alpha[index] = index * ((index < 25) ? index : 3);
}
The index of an array element is the number in the brackets, [].
In the example, alpha[2] = 3, 2 is the index and 3 is the variable stored at index 2.
Also remember that for arrays, index 2 means that it is the third position in the array because the first index is position 0.
For this exercise, you would declare an index variable, i, and iterate through the array such that alpha[0] = 0, alpha[1] = 1, alpha[2] = 4, ... alpha[i] = i*i
Problem H (Longest Natural Successors):
Two consecutive integers are natural successors if the second is the successor of the first in the sequence of natural numbers (1 and 2 are natural successors). Write a program that reads a number N followed by N integers, and then prints the length of the longest sequence of consecutive natural successors.
Example:
Input 7 2 3 5 6 7 9 10 Output 3 this is my code so far and i have no idea why it does not work
import java.util.Scanner;
public class Conse {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int x = scan.nextInt();
int[] array = new int[x];
for (int i = 0; i < array.length; i++) {
array[i] = scan.nextInt();
}
System.out.println(array(array));
}
public static int array(int[] array) {
int count = 0, temp = 0;
for (int i = 0; i < array.length; i++) {
count = 0;
for (int j = i, k = i + 1; j < array.length - 1; j++, k++) {
if (Math.abs(array[j] - array[k]) == 1) {
count++;
} else {
if (temp <= count) {
temp = count;
}
break;
}
}
}
return temp + 1;
}
}
Why two loops? What about
public static int array(final int[] array) {
int lastNo = -100;
int maxConsecutiveNumbers = 0;
int currentConsecutiveNumbers = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] == lastNo + 1) {
currentConsecutiveNumbers++;
maxConsecutiveNumbers = Math.max(maxConsecutiveNumbers,
currentConsecutiveNumbers);
} else {
currentConsecutiveNumbers = 1;
}
lastNo = array[i];
}
return Math.max(maxConsecutiveNumbers, currentConsecutiveNumbers);
}
This seems to work:
public static int longestConsecutive(int[] array) {
int longest = 0;
// For each possible start
for (int i = 0; i < array.length; i++) {
// Count consecutive.
for (int j = i + 1; j < array.length; j++) {
// This one consecutive to last?
if (Math.abs(array[j] - array[j - 1]) == 1) {
// Is it longer?
if (j - i > longest) {
// Yup! Remember it.
longest = j - i;
}
} else {
// Start again.
break;
}
}
}
return longest + 1;
}
public void test() {
int[] a = new int[]{7, 2, 3, 5, 6, 7, 9, 10};
System.out.println("Longest: " + Arrays.toString(a) + "=" + longestConsecutive(a));
}
prints
Longest: [7, 2, 3, 5, 6, 7, 9, 10]=3
Since your question has "Problem H" associated with it, I'm assuming you are just learning. Simpler is always better, so it usually pays to break it down into "what has to be done" before starting on a particular road by writing code that approaches the problem with "how can this be done."
In this case, you may be over-complicating things with arrays. A number is a natural successor if it is one greater than the previous number. If this is true, increment the count of the current sequence. If not, we're starting a new sequence. If the current sequence length is greater than the maximum sequence length we've seen, set the max sequence length to the current sequence length. No arrays needed - you only need to compare two numbers (current and last numbers read).
For example:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int N = scan.nextInt();
int maxSequenceLen = 0; // longest sequence ever
int curSequenceLen = 0; // when starting new sequence, reset to 1 (count the reset #)
int last = 0;
for(int i = 0; i < N; i++) {
int cur = scan.nextInt();
if ((last+1) == cur){
++curSequenceLen;
}
else{
curSequenceLen = 1;
}
if (curSequenceLen > maxSequenceLen){
maxSequenceLen = curSequenceLen;
}
last = cur;
}
System.out.println(maxSequenceLen);
Caveat: I'm answering this on a computer that does not have my Java development environment on it, so the code is untested.
I'm not sure I understand this question correctly. The answer's written here assumes that the the natural successors occur contiguously. But if this is not the same then the solution here might not give the correct answer.
Suppose instead of [7 2 3 5 6 7 9 10] the input was [7 2 6 3 7 5 6 9 10] then the answer becomes 2 while the natural successor [5 6 7] is present in the array.
If the input is not sorted we'll have to use a different approach. Like using HashSet
Load the entire array into a HashSet which removes duplicates.
Pick the first value from the HashSet and assigned it to start and end and remove it from the set.
Now decrements start and check if it is present in the HashSet and continue till a particular value for start is not present int the HashSetwhile removing the value being searched from the set.
Do the same for end except that you will have to increase the value of end for each iteration.
We now have to continuous range from start to end present in the set and whose range is current_Max = end - start + 1
In each iteration we keep track of this current_Max to arrive at the longest natural successor for the entire array.
And since HashSet supports Add, Remove, Update in O(1) time. This algorithm will run in O(n) time, where n is the length of the input array.
The code for this approach in C# can be found here
This program simply is supposed to eliminate duplicates from an array. However, the second for loop in the eliminate method was throwing an out of bounds exception. I was looking and couldnt see how that could be, so I figured I would increase the array size by 1 so that I would get it to work with the only downside being an extra 0 tacked onto the end.
To my surprise, when I increased tracker[]'s size from 10 to 11, the program prints out every number from 0 to 9 even if I dont imput most of those numbers. Where do those numbers come from, and why am I having this problem?
import java.util.*;
class nodupes
{
public static void main(String[] args)
{
int[] dataset = new int[10];
//getting the numbers
for (int i = 0; i <= 9 ; i++)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter a one digit number");
dataset[i] = input.nextInt();
}
int[] answer = (eliminateduplicates(dataset));
System.out.println(Arrays.toString(answer));
}
public static int[] eliminateduplicates(int[] numbers)
{
boolean[] tracker = new boolean[11];
int arraysize = 1;
for(int k = 0; k <= 9; k++)
{
if(tracker[numbers[k]] == false)
{
arraysize++;
tracker[numbers[k]] = true;
}
}
int[] singles = new int[arraysize];
for(int l = 0; l <= arraysize; l++)
{
if(tracker[l] == true)
{
singles[l] = l;
}
}
return singles;
}
}
The exception was occuring at this part
if(tracker[l] == true)
but only when trackers size was 10. At 11 it just prints [0,1,2,3,4,5,6,7,8,9]
EDIT: The arraysize = 1 was a hold over from debugging, originally it was at 0
EDIT: Fixed it up, but now there is a 0 at the end, even though the array should be getting completely filled.
public static int[] eliminateduplicates(int[] numbers)
{
boolean[] tracker = new boolean[10];
int arraysize = 0;
for(int k = 0; k < numbers.length; k++)
{
if(tracker[numbers[k]] == false)
{
arraysize++;
tracker[numbers[k]] = true;
}
}
int[] singles = new int[arraysize];
int counter = 0;
for(int l = 0; l < arraysize; l++)
{
if(tracker[l] == true)
{
singles[counter] = l;
counter++;
}
}
return singles;
}
Since arrays start at 0, your arraysize will be one larger than the number of unique numbers, so your final loop goes through one too many times. In other words "l" (letter l -- try using a different variable name) will get to 11 if you have 10 unique numbers and tracker only has item 0-10, thus an out of bounds exception. Try changing the declaration to
int arraysize = 0;
Once again defeated by <=
for(int l = 0; l <= arraysize; l++)
An array size of 10 means 0-9, this loop will go 0-10
For where the numbers are coming from,
singles[l] = l;
is assigning the count values into singles fields, so singles[1] is assigned 1, etc.
Edit like 20 because I should really be asleep. Realizing I probably just did your homework for you so I removed the code.
arraySize should start at 0, because you start with no numbers and begin to add to this size as you find duplicates. Assuming there was only 1 number repeated ten times, you would've created an array of size 2 to store 1 number. int arraysize = 0;
Your first for loop should loop through numbers, so it makes sense to use the length of numbers in the loop constraint. for( int i = 0; i < numbers.length; i ++)
For the second for loop: you need to traverse the entire tracker array, so might as well use the length for that (tracker.length). Fewer magic numbers is always a good thing. You also need another variables to keep track of your place in the singles array. If numbers was an array of 10 9s, then only tracker[9] would be true, but this should be placed in singles[0]. Again, bad job from me of explaining but it's hard without diagrams.
Derp derp, I feel like being nice/going to bed, so voila, the code I used (it worked the one time I tried to test it):
public static int[] eliminateduplicates(int[] numbers)
{
boolean[] tracker = new boolean[10];
int arraysize = 0;
for(int k = 0; k < numbers.length; k++)
{
if(tracker[numbers[k]] == false)
{
arraysize++;
tracker[numbers[k]] = true;
}
}
int[] singles = new int[arraysize];
for(int l = 0, count = 0; l < tracker.length; l++)
{
if(tracker[l] == true)
{
singles[count++] = l;
}
}
return singles;
}
I feel you are doing too much of processing for getting a no duplicate, if you dont have the restriction of not using Collections then you can try this
public class NoDupes {
public static void main(String[] args) {
Integer[] dataset = new Integer[10];
for (int i = 0; i < 10; i++) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a one digit number");
dataset[i] = input.nextInt();
}
Integer[] arr = eliminateduplicates(dataset);
for (Integer integer : arr) {
System.out.println(integer);
}
}
public static Integer[] eliminateduplicates(Integer[] numbers) {
return new HashSet<Integer>(Arrays.asList(numbers)).toArray(new Integer[]{});
}
}
To answer your question your final loop is going one index more than the size.
The range of valid indexes in an array in Java is [0, SIZE), ie. from 0 up to arraysize-1.
The reason you're getting the exception is because in your loop you're iterating from 0 to arraysize inclusively, 1 index too far:
for(int l = 0; l <= arraysize; l++)
Therefore when you get to if(tracker[l] == true) in the last iteration, l will equal arraysize and tracker[l] will be outside the bounds of the array. You can easily fix this by changing <= to < in your for loop condition.
The reason that the problem goes away when the size of your array is changed from 10 to 11 has to do with arraysize being incremented up to 10 in the for loop above the one causing the problems. This time, singles[10] is a valid element in the array since the range of indexes in your array is now [0, 11).
EDIT: Actually arraysize has the potential to be incremented to 11, I thought it was initialised to 0 in which case it would only get to 10. Either way the above is still valid; the last index you try and access in your array must be 1 less than the length of your array in order to avoid the exception you're getting, since arrays are zero-based. So yeah, long story short, <= should be <.