Trying to properly print an array in Java - java

I am new to Programming so bear with me if I do not properly present my issue. I have an assignment to create a program to assign integer values 1-25 to a 25 element integer array. I need to print the array as five separate lines with each line containing 5 elements separated by commas. The last element does not have a comma following it. The final output should be as follows:
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
The code that I came up with comes close, but it's not quite right. The code that I came up with is:
public class Test2 {
/**
* #param args
* the command line arguments
*/
public static void main(String[] args) {
int[] numbers = new int[25];
for (int i = 0; i < numbers.length; i++) {
numbers[i] = i + 1;
System.out.print(numbers[i] + ",");
if (i % 5 == 0 && i > 0)
System.out.println();
}
}
}
The printout that I get from my code is as follows:
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,
I am not sure why I am getting 1-6 on the first line as well as how to remove the comma at the end of each line. Any help pointing out my errors would be appreciated.

The error is that you are checking if int i is divisible by 5 (i % 5), not numbers[i] (numbers[i] % 5). This way, your code prints:
number 1 when i = 0,
number 2 when i = 1,
number 3 when i = 2,
number 4 when i = 3,
number 5 when i = 4,
number 6 when i = 5
and finally prints line break.
The correct code is:
int[] numbers = new int[25];
for (int i = 0; i < numbers.length; i++) {
numbers[i]=i+1;
System.out.print(numbers[i]);
if (numbers[i] % 5 == 0 && i > 0) {
System.out.println();
} else {
System.out.print(",");
}
}
The above code will print (as intended):
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

You're getting 6 numbers on the first line, because you start counting at i=0, and only print the newline once i=5; at which point the number you've just printed is 6, not 5 - you're printing i+1 in each iteration.
If you made your logic such that it printed EITHER a comma OR a newline but not both, you'd get rid of the commas at the ends of the lines.

You're close. Very close.
Consider what your condition is checking - you want to inspect a value i, and want to stop when that particular value is divisible by 5 but is nonzero.
The problem is that you have the wrong value - i isn't what you want, but numbers[i]. The reason: each number in numbers[i] is offset of i by 1.
What you want to do is check if numbers[i] is divisible by 5. You still need to check for a nonzero i, though.
if(numbers[i] % 5 == 0 && i > 0) {
System.out.println(numbers[i]);
} else {
System.out.print(numbers[i] + ",");
}

Replace
if (i % 5 == 0 && i > 0)
with
if (i % 5 == 4)

Related

Counting numbers of even numbers and odd numbers in java array

I have a program that reads a list of integers, and then display the number of even numbers and odd numbers. We assume that the input ends with 0. Here is the sample run of the program.
Input numbers: 1 2 3 4 5 6 7 8 9 0
Odd: 5 Even: 4
However, my result is
Odd: 5 and Even: 5.
The problem is that 0 is counted as an even number. This is my code
public class Q75 {
public static void main(String[] args){
java.util.Scanner input = new java.util.Scanner (System.in);
double [] numbers = new double[10];
System.out.print("Enter numbers: ");
for(int i = 0;i<numbers.length;i++){
numbers[i] = input.nextDouble();
}
int Evens = 0;
int Odd = 0;
for(int i = 0;i<numbers.length;i++){
if(numbers[i]%2 == 0){
Evens++;
}else{
Odd++;
}
}
System.out.println("The number of odd numbers: " + Odd);
System.out.println("The number of even numbers: " + Evens);
}
}
There are two options
A) Adding another branch in your if statements i.e.
if(number[i] > 0) {
if(number[i] % 2 >0)
Odd++;
else
Evens++;
}
NB: changing the else branch to else if(number[i] >0), you can do without the outer if condition.
B) Since the list of number ends with 0 you can put this as a condition in your for loop i.e.
for(int i =0; i < numbers.length && numbers[i] > 0 ; i++)
Also as a rule of thumb variable names in java start with a small letter
Just don't check the last element: Use i < numbers.length - 1
for(int i = 0;i < numbers.length - 1; i++) {
//
}

Show a number line based on the given string

I am stuck in my project where we have to show a string of line in the number line scale so later we can delete or add characters to that string. I am not sure how to print out the scale in 5s based on the length of the string.
Ex:
0 5 10 15 20
|----+----|----+----|-
This is the first line
Then, the user will choose the characters they want to delete from the string using from position and to position. It will show what position the user chose from the string and delete.
Ex:
from position: 12
to position: 18
0 5 10 15 20
|----+----|----+----|-
This is the first line
^^^^^^^ --> // this will be deleted
y/n: y
0 5 10 15
|----+----|----+
This is the ine
I was able to delete the characters but I do not know how to show the number line based on a string. Here is my code so far:
public void showNumberLine(String line)
{
int lineCount = line.length(); // getting the length of the string being passed in
String numberLine = "";
for(int i = 0; i <= lineCount; i++) //
{
numberLine = "" + i;
System.out.println("|----+----|----+----|-");
}
}
public void deleteSubString()
{
Scanner keyboard = new Scanner(System.in);
showNumberLine(textOfLine); // this will print out then number line and the line
System.out.print("from position: ");
int fromIndex = keyboard.nextInt();
System.out.print("to position: ");
int toIndex = keyboard.nextInt();
if(fromIndex < 0 || fromIndex > numOfChar || toIndex < 0 || toIndex > numOfChar)
{
System.out.println("Cannot delete at the given index: Index Out of Bounds");
}
/*
* Create a new number line where it shows what is going to be deleted
*/
String newLineOfString = textOfLine.substring(fromIndex, toIndex);
textOfLine = textOfLine.replace(newLineOfString, "");
System.out.println(newLineOfString);
}
I would recommend you to implement a method printScale or something like that which takes a String or an int as argument and prints these two lines for you.
You sad you already can remove the characters so if you have a String with the value "This is the ine" as you showed in your example you could call the method like this:
printScale(myNewString.length());
This method could look something like this (not perfect but works):
public void printLine(int amountOfCharacters) {
StringBuilder lineNumber = new StringBuilder();
StringBuilder lineScaleSymbols = new StringBuilder();
for (int i = 0; i < amountOfCharacters; i++) {
if (i % 10 == 0) {
if (i < 10) {
lineNumber.append(i);
} else {
lineNumber.insert(i -1, i);
}
lineScaleSymbols.append('|');
} else if (i % 5 == 0) {
if (i < 10) {
lineNumber.append(i);
} else {
lineNumber.insert(i -1, i);
}
lineScaleSymbols.append('+');
} else {
lineNumber.append(' ');
lineScaleSymbols.append('-');
}
}
System.out.println(lineNumber.toString());
System.out.println(lineScaleSymbols.toString());
}
Hope this helps.
You're on the right track with your showNumberLine method.
Let's outline exactly what you need to do:
determine the length of the string
generate a number line of the same length as the string
every character ending with 0 will be the special character |
every character ending in 5 will be the special character +
every other character will be -
You could make your loop like this, using the modulus operator to determine which character to write:
for(int i = 0; i < line.length(); i++) {
if(i % 10 == 0) {
// the number is divisible by 10 (ends in zero)
System.out.print("|");
} else if(i % 5 == 0 && i % 10 != 0) {
// the number is divisible by 5 and not divisible by 10 (ends in 5)
System.out.print("+");
} else {
System.out.print("-");
}
System.out.println();
}
Output:
|----+----|----+----|----+----|----+----|---
The quick brown fox jumped over the lazy dog
You'll need some more code to write out the digits (0, 5, 10, 15) above the number line, I'll leave that to you. It will be similar logic but there are subtle issues to consider as the length of the numbers is 1 character, then 2 characters, then 3 characters as they increase (0, 5, 10, 15, ... 100, 105). At some point you'll have to stop as the numbers won't fit in the space.

How to display all numbers between a range, but every 3rd number is changed to an asterisk

Just wondering how I do this, here is my code so far, but I can't seem to get it working, it shows all the numbers between 1-12 and adds the asterisk before the 3rd number, while still showing the 3rd number.
public class Help {
public static void main(String[] args) {
int i = 1;
while(i < 12){
System.out.println(i);
i = i + 1;
if(i % 3 == 0){
System.out.println("*");
}
}
}
}
If you want every third number to be count from the lower boundary of the range to display, then you cannot just use number % 3 == 0, because the "third" number changes depending on the lower boundary value, e.g. range 2-8 can be:
2 * 4 5 * 7 8 // Using number % 3 == 0
2 3 * 5 6 * 8 // Counting from lower boundary
Here is a method for counting from lower boundary:
private static void printRangeMask3(int from, int to) {
for (int i = 0; i <= to - from; i++)
System.out.println(i % 3 == 2 ? "*" : String.valueOf(from + i));
}
Output IDEONE
// printRangeMask3(1, 12)
1
2
*
4
5
*
7
8
*
10
11
*
// printRangeMask3(2, 8)
2
3
*
5
6
*
8
for(int hj=1;hj<12;hj++)
{
if(hj%3==0)
{
System.out.println("*");
}
else
System.out.println(hj);
}
hope my help works happy coding
In your code above, the System.out.println("*"); statement will be executed along with your System.out.println("i"); statement. You only want ONE of these lines to run, so you should use an else statement like this:
while(i < 12){
if(i % 3 == 0){
System.out.println("*");
} else {
System.out.println(i);
}
i += 1; //same as i = i + 1;
}
This way, only one of these lines run, and every third number is replaced with an asterisk.
You have a logic error in your code:
The test is carried out after the instruction is executed therefore you get an unexpected result.
If you are a beginner I would suggest you try and trace the code step by step to find out what's wrong or use a debugger.

How to create an array of integers that equal a certain value?

Hello i am having a tough time trying to write a function that can create an array that holds integers, that equal my simple math problem.
my problem is not adding integers into the array but finding the correct integers that could add up to a math problem.
for example i have a simple math problem like: 10 + 10 = ? we know it equals 20
so i want my array to hold up to ten integers, that when added all together equal 20.
this is what i have been trying in code but not getting the results i want.
while (totalCount != answer
&& count < setCount) {
randomNumber = rand.nextInt((int) answer / 2) + 1;
if(count < setCount) {
sumOfBalloons.add(randomNumber);
totalCount += randomNumber;
count++;
}
if(totalCount > answer) {
count = 0;
totalCount = 0;
sumOfBalloons.clear();
}
}
i am trying to find random numbers that add up to the math problems answer so i can draw them on balloons. problem is i can never get ten numbers to equal the answer in my while loop.
does anyone know some way of doing something like this?
need array to hold 3 - 10 integers that equals my math problems answer.
** update on code thanks to the advice i received i managed to fix my while loop now it looks like this
had to post like this cause my rep is very low. sorry.
while (totalCount != answer) {
randomNumber = rand.nextInt((int) answer / 2) + 1;
if(totalCount + randomNumber > answer) {
randomNumber = rand.nextInt((int) answer - totalCount) + 1;
}
if(count + 1 == setCount) {
randomNumber = answer - totalCount;
}
if(count < setCount) {
sumOfBalloons.add(randomNumber);
totalCount += randomNumber;
count++;
}
if(totalCount > answer
|| totalCount == answer
&& count < setCount
|| totalCount != answer
&& count == setCount) {
count = 0;
totalCount = 0;
sumOfBalloons.clear();
}
}
this is what i got in my console from this code
Total count = 10
Total totalCount = 20
sumOfBalloons 0 = 2
sumOfBalloons 1 = 3
sumOfBalloons 2 = 3
sumOfBalloons 3 = 2
sumOfBalloons 4 = 1
sumOfBalloons 5 = 4
sumOfBalloons 6 = 2
sumOfBalloons 7 = 1
sumOfBalloons 8 = 1
sumOfBalloons 9 = 1
I think there are a few options here re: generating random numbers that sum to 20.
Here's one possible solution:
Create an array of length 4, for example.
Generate random number between 1 and 6 for each of the first 3 indices of your array.
At this point you'll have an array of the form: { 4, 5, 2, _ } (where our 4th element hasn't been chosen yet).
Sum our first 3 elements: 4 + 5 + 2 = 11. Determine 4th element by calculating 20 - current_total (11) = 9.
Set myArray[3] = 9;
A few things to note:
You may need to modify the range of possible random numbers ( 1-6 ) I've given. Consider what happens if the array we generate turns out to be { 2, 1, 2, _ }...then there's no digit that will ensure the elements sum to 20.
Another option is to use an arrayList instead of an array. The benefit to this is that you can keep adding elements to your arrayList until you either hit 20 (then you're done) or go over (in which case you delete the most recent element and begin adding again). You also won't need (or be able) to know the length of your arrayList in advance.

Java: Multi Dimensional array output confusion?

public class VarNoOfCols {
public static void main(String[] args) {
int a[][] = new int[3][];
a[0]=new int[3];
a[1]=new int[2];
a[2]=new int[1];
int temp=3;
for(int i =0; i<3;i++) {
for(int k=0;k<temp;k++) {
a[i][k]= k*10;
temp-- ;
}
}
}
}
--- output that I assumed ---- is below ---But this is incorrect.
(0 0) 0 (0 1) 10
(1 0) 0 (1 1) 10
(2 0) 0 (2,1) 10
I know this is incorrect. (My question is - on completing second iteration, "k" is greater than "temp" and when conditon fails it will stop the inner statments and do the next job (what ever it suppose to be).Why am i getting (0,2) = 20 and why i dont see (2,1) = 10 ?
You can see the correct output:
(0 0) 0 (0 1) 10 (0 2) 20
(1 0) 0 (1 1) 10
(2 0) 0
I am a learner and i really appreciate someone's help here. thank you
Change the code like that:
for(int i =0; i<3;i++)
{
for(int k=0;k<3;k++)
a[i][k]= k*10;
}
If you wanted a square output, why do you use the control variable temp that will change the number of outputted entries on each iteration over i?
this is because the temp and the k
in your program first i=0
k=0,temp=3 then (0 0) so output 0*10 = 0
k=1,temp=2 then (0 1) so output 1*10 = 10
k=2,temp=1 condition false in for loop (there the condition in the outer for loop(having i) is correct but in the inner for loop the condation k
i=1
k=0,temp=3 then (1 0) so output 0*10 = 0
k=1,temp=2 then (1 1) so output 1*10 = 10
i=2
k=0,temp=3 then (2 0) so output 0*10 = 0
k=1,temp=2 then (2 1) so output 1*10 = 10
there is no need of temp. to get correct output use this
for(int i =0; i<3;i++)
{
for(int k=0;k<3;k++)
a[i][k]= k*10;
}
Actually with your last edit (with temp-- in the second for) you obtain neither the first nor the second output.
Why?
Because you never reassign temp and after 3 time be decremented the second loop will not be executed anymore. So you got a value for (0;0) (0;1) and (1;0) only.
Why you can't obtain output 1 (square one)?
a[2] have a size of 1 so you can't have something in (2;1)
How to obtain the second output?
Don't put the temp-- in the second loop but after the second loop (at the end of the first loop).
public class VarNoOfCols {
public static void main(String[] args) {
int a[][] = new int[3][];
a[0]=new int[3];
a[1]=new int[2];
a[2]=new int[1];
int temp=3;
for(int i =0; i<3;i++)
{
for(int k=0;k<temp;k++)
//the inner for lopp doesn't have curly "{" braces.
//temp will be 3 for 1st loop and when k becomes 3 it exit inner loop.
a[i][k]= k*10;
temp--;
}
//temp--;
//System.out.println("temp : " +temp + " \n " );
}
}
Thank you guys. I figuered out the logic behind. it is not logic, it is just that { that should be watched. I will get following output if I don't use braces { in inner loop:
(0 0 ) 0 (0 1 ) 10 (0 2 ) 20
(1 0 ) 0 (1 1 ) 10
(2 0 ) 0
If the braces { and } present in inner loop with temp variable inside inner loop then I will get the following output:
(0 0 ) 0 (0 1 ) 10
(1 0 ) 0

Categories

Resources