Array is printing more numbers than intended? - java

I'm supposed to create and initialize a 100-element array, then make the 7th element the number "7", and finally print the array, starting a new line every 20 elements. I've been trying to figure this out for a long time and I can't.
My code right now is:
public class Array {
public static void main(String args[]) {
int [] array = new int[100];
for (int a = 0; a < array.length; a++) {
if (array[a] == 6) {
array[a]=7;
array[a] = a + 1;
}
printArray(array);
}
}
public static void printArray(int[] array){
for (int a=0; a < array.length; a++) {
System.out.print(" " + array[a]);
if ((a - 1) % 20 == 0) {
System.out.println("");
}
}
}
}
When I run this my output is a lot of zeros, far more than 100. They are separated every 20 characters as intended, but the seventh element is not 7. I think it has to do with the association between int "a" and my array, but I can't figure it out. I know the solution must be simple but I just cannot see it. Thank you all!

Proper indentation of your code, in particular the main method, reveals what is going on. You are calling printArray from within the for loop, so you are printing the array contents 100 times.
for (int a = 0; a < array.length; a++) {
if (array[a] == 6) {
array[a]=7;
array[a] = a + 1;
}
printArray(array);
}
Move the call to printArray after the } ending brace for the for loop.
Now you'll get 100 0s.
Also, I think you meant to have array[a] = a + 1; executed if the index was not 6, e.g.
if (array[a] == 6) {
array[a] = 7;
} else {
array[a] = a + 1;
}
Additionally, you will want to print a newline after 20 numbers, e.g. after indexes 19, 39, etc., so add 1 to a before calculating the remainder, instead of subtracting 1, so that 19 + 1 = 20, whose remainder is 0.

There are many things wrong. However, to answer your question, you are printing the array 100 times since printArray is inside your first loop.

You misplaced an end parenthesis in your main method. The properly formatted method looks like this:
public static void main(String args[]) {
int [] array = new int[100];
for (int a = 0; a < array.length; a++) {
if (array[a] == 6) {
array[a]=7;
}
array[a] = a + 1;
}
printArray(array);
}

First of all your code is organized very badly so it's very easy for u to miss what went where. You have 2 major mistakes, first of all you called printArray()
Inside your for loop and therefore printed it 100 times.
Second, you kept checking if the value inside the array in index a is 6.
You need to check if a is 6 since it is your index like this:
if(a == 6)
array[a] = 7;

Well, I ran your code, and there are a few places that can be corrected.
As for your problem of the many things being printed, that's because you've placed your printarray() inside the for loop, so it's printing the array 100 times.
As for printing it out, i find this code to be more concise:
public static void printArray(int[] array){
int counter = 0;
for(int i = 0; i < array.length; i++){
System.out.print(array[i] + " ");
counter++;
if(counter == 20){
counter = 0;
System.out.print("\n");
}
}
}
Also, I'm not really sure why you're using a for loop to just change the 7th element. You could use this:
array[6] = 7;
I'm not really sure what you're doing in the for loop.
I hope this helped! Good luck!

Related

My first code question! Learning Java and need help performing basic stats on an array

This project is all about methods and arrays and breaks down into 3 parts. Firstly, create an array. Second, fill said array with random ints. Lastly, create a method that displays whether each int is even or odd as well as provides the average of the random ints.
Java is my first programming language that i'm being introduced to in my curriculum and I've worked in this issue for about 4-5 hours now but hit a wall. I can't seem to get my statsDisplay method to perform the necessary stats on my created arrays. It appears that since it always results with alternating "even/odd", it's just creating its own array from 1-20 and analyzing that instead of the previous Math.random() array.
Is anyone able to see what might be going wrong here?
Also, this is my first ever post on here so I'm sorry if it's not formatted correctly or asked in an odd way...
public class Practicestuff {
public static void main(String[] args) {
int[] vals = new int[20];
fill(vals);
statsDisplay(vals);
print(vals);
}
public static void print(int[] array) {
for(int i = 0; i < array.length; i++) {
System.out.println(array[i] + " ");
}
System.out.println();
}
public static void fill(int[] array) {
for(int i = 0; i < array.length; i++) {
array[i] = (int) (Math.random() *100);
public static void statsDisplay(int[] array) {
for(double i = 0; i < array.length; i++) {
if(i % 2 == 0) {
System.out.println("Number is even");
if(i % 2 != 0)
System.out.println("Number is odd");
}
}
}
In your statsDisplay() method, the i in the for loop is the index (1, 2, 3, 4...). The if statements are checking if i is odd or even. You want to be checking if array[i] is odd or even, so you should replace the i in the if statements with array[i].

Why does this for-loop only run once?

The goal of my code: To be able to write a program where I can enter in any number int as a command-line argument and displays how many digits in the integer number are 7s.
My problem is that I don't understand why my code only runs through the for-loop once. I inserted the system.out.println(sevens); to see how many times this loop works when I compile with a random number like 456789.
I could only think of a for-loop to use for this one and fixed some simple mistakes in the beginning. I also checked my brackets
public class TestingSevens {
public static void main(String[] args) {
int sevens = Integer.parseInt(args[0]);
int count = 0;
for (int i = 0; i < args.length; i++) {
if (sevens%10 == 7) {
count += 1;
}
sevens = sevens/10;
System.out.println(sevens);
}
System.out.println(count);
}
}
The result of inputting a number like 456789 is "45678" for the first print and the second print is "0." I know the number for some reason only runs through the loop once since it cuts off the last number before jumping out of the loop to print the count...any advice?
I presume you want to iterate over each digit of sevens. Since sevens initialized from args[0], the loop limit should match and look at args[0].length() rather than args.length.
for (int i = 0; i < args[0].length(); i++)
An alternate way to write the loop is to iterate until sevens reaches 0. That lines up better with the loop body; both use the same variable.
while (sevens > 0) {
if (sevens%10 == 7) {
count += 1;
}
sevens /= 10;
System.out.println(sevens);
}
Your code has logic errors, so to check if the iterated number is number 7 you need to turn the number into a string and check if the character is the desired character using: numberString.charAt(index)
Below is the corrected code:
public static void main(String[] args) {
int sevens = Integer.parseInt(args[0]);
String numberString = String.valueOf(sevens);
int count = 0;
for (int i = 0; i < numberString.length(); i++) {
char c = numberString.charAt(i);
if (c == '7') {
count += 1;
}
System.out.println("Input number: " + sevens);
}
System.out.println("Count of 7 numbers: " + count);
}

nested for loops integers missing from array

Beginner here. I'm having problems running this series of for loops to find which integers are missing from an array.
public class FunWithArrays{
public static void main(String[] args){
String nString = args[0];
int n = Integer.parseInt(nString);
int inputArray [] = {1,2,4};
System.out.println(" The missing numbers are " );
findMissingNum(n, inputArray);
}
public static void findMissingNum(int n, int[] inputArray){
for (int i = 1; i <= inputArray.length; i++){
int count = 0;
for( int j = 0; j < n; j++){
if(inputArray[j] == i){
count ++;
}
if (count == 0){
System.out.println(i);
}
}
}
}
}
I get the answer I want, namely 3, however it doesn't print but rather shows up in a runtime error:
java.lang.ArrayIndexOutOfBoundsException: 3
at FunWithArrays.findMissingNum(FunWithArrays.java:17)
at FunWithArrays.main(FunWithArrays.java:9)
the method should take an input n from the user (when the program is run) as the largest value of the array and print all the ones missing
The logic is the outer for loop should traverse the array for numbers 1-n, and the inner loop should add to the count variable each time it finds a certain number. At the end of iteration it should print any numbers with a final "count" of 0. THIS IS LITERALLY DRIVING ME CRAZY!!! thanks in advance :)
First of all, you should traverse from 0 to (inputArray.length-1) index of inputArray. This will get rid of the ArrayIndexOutOfBoundsException, because java array indexing starts from 0 not 1.
And for inner loop, run from 0 to n, since n is the max number.
And Thirdly, it should be inputArray[i] == j, not inputArray[j] == i, same for printing the value. In you case I believe you have n>=4, so it was trying to access inputArray[3] via inputArray[j] call. That's why you are getting this out of bound error.
I think your code means like this: nest loop always run through inner loop first before run the outer loop.
public static void findMissingNum(int n, int[] inputArray){
for (int i = 1; i <= n; i++){
int count = 0;
for( int j = 0; j < inputArray.length; j++){
if(inputArray[j] == i){
count ++;
}
if (count == 0){
System.out.println(i);
}
}
}
}
I will just use a while loop instead:
int num =1;
while(num<=n){
for(int i = 0;i<inputArray.length;i++){
if(inputArray[i]!=num){
System.out.println(num);
}
}
num++;
}
The i incrementing to <= ipnutArray.length is not causing the error because i is never used as the index. What is causing the error is when n > length.
Also, you should not be checking n elements starting from the beginning because n is the max value, not the number of elements.

Adding integers of array upto some number (java)

I have a java question.
I have two int[] arrays: cdn and cmn.
cdn is {1,1,1,1,1,1,2,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}
cmn is {8,8,16}
I need a program that adds the consecutive integers of cdn[] upto cmn[init] and returns the number of integers used in the addition. Then it continues adding from the next integer of cdn[] upto cmn[init+1] and return the number of integers. For the arrays above this is done 3 times: the first time the return value is 7, the second time it is 7, and the third time it is 16. The number of integers can be collected in and int[] which is {7,7,16}. The code I have is:
int numofints = 0;
int init = 0;
int plus = 0;
while(init < m2){
for(int j = 0; j < cdn.length; j++){
plus += cdn[j];
numofints++;
if(plus == cmn[init]){
init++;
}
}
}
System.out.print(numofints);
in which m2 is the size of cmn, which is 3 in this case. Note that my program starts to loop from the beginning of cdn over and over again, because j = 0. I want it to start where it ended the previous time!
I hope you have a solution for me.
Bjorn
just pull j out of the outer loop, and use a while, instead of for, for the inner loop
and you also need to put plus = 0 into the loop
public class T {
public static void main(String[] args) {
int[] cdn = {1,1,1,1,1,1,2,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1};
int[] cmn = {8,8,16};
int numofints = 0;
int init = 0;
int m2 = 3;
int j = 0;
while(init < m2){
int plus = 0;
while(j < cdn.length){
plus += cdn[j];
j++;
numofints++;
if(plus == cmn[init]){
init++;
System.out.println(j);
break;
}
}
if (j == cdn.length) break;
}
}
}
Shoudln't if(plus == cmn[init]){ be if(plus >= cmn[init])? If you change cdn at all and "plus" happens to go over "cmn[init]", your code is going to break.

I can't figure out how to reset a loop (see example)

I need to write a method that accepts two ints as arguments, a min and a max. On the first line i need to print all numbers in that range (inclusive). On the next line I start with min+1, print all numbers up to max, and then go back to the front of the range and print min. Next line I start with min+2, and so on until I have repeated this starting with each number in the range.Very hard to explain, here's two examples: Say I pass 1 and 5 as the min and max arguments. I want the method to print this:
12345
23451
34512
45123
51234
Or if 3 and 9 were passed, I would expect this:
3456789
4567893
5678934
6789345
7893456
8934567
9345678
I've tried all kinds of things, I'm sure there is an easy way to do this that I am not realizing. I'm supposed to do this without arrays or arrayLists. I think I have a good base to work with, but I just can't figure out where to go from here. My base code prints this:
12345
2345
345
45
5
And this:
3456789
456789
56789
6789
789
89
9
I'm stumped. Here's my code:
public void printSquare(int min, int max){
for (int i=min; i<=max; i++){
for (int j=i; j<=max; j++){
System.out.print(j);
}
System.out.println();
}
}
You should think about how many values you want on each row, and then determine what those values should be. Its hard to make it any clearer without giving you the solution.
Let us know how you go.
Peter is right, and IMO is answering a homework question in the right manner. You know how many elements you want on each line, so you need an outer loop that gives you that many elements, this will stop you from getting the cascading behavior you're seeing now.
At that point you need to think about your inner loop(s), and you'll probably find this easiest using the modulus operator (%). This will allow you to iterate without ever going over your target.
You should be able to figure it out from there, and you're much better off figuring out the algorithm yourself than copying it from someone else, at least at this level of development. Good Luck!
Think about a way to print the missing numbers. The answer is below, if you cannot come up with it you can check it.
This should also print the missing parts:
public void printSquare(int min, int max){
for (int i=min; i<=max; i++){
for (int j=i; j<=max; j++){
System.out.print(j);
}
for (int k=0; k<i-min; k++){
System.out.print(min+k);
}
System.out.println();
}
}
I didn't run this one but it might work:
public void printSquare(int min, int max){
int dif = max - min;
for (int i=min; i<=max; i++){
for (int j=i; j <= i+dif ; j++){
int temp = j;
if ( temp > max ) temp = temp - max;
System.out.print(temp);
}
System.out.println();
}
}
try and just shift an array like so:
static void Main(string[] args)
{
// this will work equally well with numbers letters or other types of characters
int[] nums = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
String a = "hello";
for (int i = 0; i < nums.Length; i++)
{
int j = 5;
int num = i;
while (j-- > 0)
{
if (num >= nums.Length)
{
num = 0;
}
// shift the loop
Console.Write(nums[num++]);
}
Console.WriteLine();
}
}
public class Test1{
public void printSquare(int min, int max){
for (int i=min; i<=max; i++){
for (int j=i; j<=max; j++){
System.out.print(j);
}
for(int k= min; k<i; k++){
System.out.print(k);
}
//System.out.print(i-1);
System.out.println();
}
}
public static void main(String[] args){
Test1 t = new Test1();
t.printSquare(1,5);
}
}
This is a very simple implementation. Hope this helps!
int n = max-min+1;
for (int i=0 ; i<n; i++){
for (int j=0; j<n; j++)
cout<<min + (i+j)%n;
cout<<"\n";
}
Output:
min = 3 | max = 9
3456789
4567893
5678934
6789345
7893456
8934567
9345678
Here's the code..
for i = 0 to max-min
for j = 0 to max-min
print min + (i+j)%n

Categories