I want to create a print statement that displays three values. 1) Counter variable which shows number of iterations. 2) Array recorder which records the values of the elements and 3) the value of these elements + 5.
There is a change method which takes all of the values in the array and adds 5 to them. I just can't understand how to print this value in line with the counter variable and Array Element counter. Is this possible to do?
int sam[] = {1,2,4,5,6,4,3,67};
change(sam);
for (int y:sam) {
for(int counter =0; counter<sam.length;counter++) {
//this is where I wish to print out the 3 elements
System.out.println(counter+ "\t\t" + sam[counter]+y);
}
}
public static void change(int x []) {
for(int counter=0; counter<x.length;counter++)
x[counter]+=5;
}
Everything is fine except that sam[counter] + y is evaluated as integer value because both arguments are integers. You need string concatenation instead:
System.out.println(counter + " " + sam[counter] + " " + y);
Or something like this (using formatter):
System.out.printf("counter = %d, sam[counter] = %d, y = %d\n", counter, sam[counter], y);
%d is a decimal argument, \n is a new line.
EDIT: Regarding your code. If you want to ouput the following row format for each element in the array
counter sam[counter] sam[counter] + 5
then just use
int sam[] = {1,2,4,5,6,4,3,67};
for (int counter = 0; counter < sam.length; counter++) {
System.out.println(counter + "\t\t" + sam[counter] + "\t\t" + (sam[counter] + 5));
}
This will print values in needed format.
0 1 6
1 2 7
2 4 9
...
Or, if you want to change array, but be able to print old values, try this:
int sam[] = {1,2,4,5,6,4,3,67};
for (int counter = 0; counter < sam.length; counter++) {
System.out.println(counter + "\t\t" + sam[counter] + "\t\t" + (sam[counter] += 5));
}
Here (sam[counter] += 5) will increment each elemnent by 5 and return the new value.
Get rid of this outer loop for (int y:sam)
This should work:
for(int counter =0; counter<sam.length;counter++) {
System.out.println(counter+ "\t\t" + sam[counter]+ "\t\t" + counter + sam[counter] + 5);
}
Your question was a little hard to interpret, but just drop the outer loop, and don’t “+y”
Scratch that. What do you think the change routine did for you? Did you want an array with the original value and another array with the changed value, and then have access to both of those arrays?
Related
public class Main {
public static void main(String[] args) throws IOException {
int i;
int sum=0;
for(i=1;i<=5;sum+=i++)
System.out.println(sum);
}
...
}
Actual Output:15
I don't know how it did the math?
The syntax for the for loop is:
for ( [ForInit] ; [Expression] ; [ForUpdate] ) Statement
and is basically equivalent with the following while loop:
[ForInit]
while (Expression) {
Statement
[ForUpdate]
}
That mean that all the following are the same:
for(i=1;i<=5;sum+=i++);
i = 1;
while (i <= 5) {
sum += i++;
}
i = 1;
while (i <= 5) {
sum += i;
i++;
}
for (i = 1; i <= 5; i++)
sum += i;
So it is calculating 1 + 2 + 3 + 4 + 5 = 15
What confuses you is the part
sum += i++
In this statement, first sum=sum+i gets calculated. Once sum has been calculated, value of i is incremented by 1.
Since the loop runs five times, previous value of sum gets added to current value of i, which keeps increases by 1.
Try printing out each iteration through the loop to help you visualise what is going on. Swap your for loop for this.
for(i=1;i<=5;sum+=i++)
{
System.out.println("sum = " + sum);
System.out.println("i = " + i);
}
In this code, the statement sum+ = i++ means sum = sum + i++ In this statement, every sum printed in the loop adds to one increment of i and when the loop ends it will display 15.
So it is calculating 0 + 1 + 2 + 3 + 4 + 5 = 15
I'm a high school student learning to program, and I can't get around this problem right now. I'm trying to print the averages outside of the loop, but I don't know how.
for (int index = 0; index < temperature.length; index++) {
double tempSum = 0;
tempSum += temperature[index];
double averageTemp = tempSum / temperature.length;
double rainSum = 0;
rainSum += precipitation[index];
}
//Output: display table of weather data including average and total
System.out.println();
System.out.println(" Weather Data");
System.out.println(" Location: " + city + ", " + state);
System.out.println("Month Temperature (" + tempLabel + ") Precipitation (" + precipLabel + ")");
System.out.println();
System.out.println("***************************************************");
for (int index = 0; index < precipitation.length; index++) {
System.out.println(month[index] + " " + temperature[index] + " " + precipitation[index]);
}
System.out.println("Average Temperature: " + averageTemp + " Total Rainfall: " + rainSum);
The comments provide the right idea. Variables in Java have block scope, which means that they are unavailable outside the block in which they are declared. JavaScript has "hoisting," which means that, no matter where the var keyword is used, the variable will be defined.
Move your variable declarations outside of the "for" blocks. Then they will be available when the loop is done. You can also do that for the "index" variable if you need to know the its last value. Typically, that is not necessary.
In your code the variable averageTemp is only existing/ accessible within the for-loop.
To have it accessible outside of the loop, you need to the declare outside, in your case before the loop. Kind of
double averageTemperature;
for (....) {
In the for-loop you could sum up the temperatures to tempSum and after the loop is finished divide tempSumby the number of items you iterated over in the loop. If you would like to do so, keep in mind that also tempSum has to be declared before entering the loop.
Running a simple multiplication table but it's not giving me a desired output. I want each multiplication to be on different column separated with a little space. for example let 1 multiply numbers ranging from 1 to 12 should be on single column , 2 multiply numbers ranging from 1 to 12 on another column. I don't want all to be on just one column.
public class multiplicationTable{
public static void main(String[] args){
for(int i=1; i<=12;i++){
System.out.println(i);
for(int j=1; j<=12; j++){
int mult=i*j;
System.out.println(i + "*"9 + j +" = " + mult +" \t");
}
}
}
}
You should use System.out.print() method instead of System.out.println() method if you want to print stuff on the same line. Your program should look like this:
public class multiplicationTable
{
public static void main(String[] args){
for(int i=1; i<=12;i++){
System.out.println(i);
for(int j=1; j<=12; j++){
int mult=i*j;
System.out.print(i + "*"9 + j +" = " + mult +" \t");
}
System.out.println();
}
}
}
Whenever you call System.out.println(), it moves to the next line. So if you want to print all of the numbers times x on one line, you will have do something like this:
public static void main(String[] args){
// Print the headers
for (int i = 1; i <= 12; i++) {
// Two tabs because the calculations take up room on the console
System.out.print(i + "\t\t");
}
// Start at the next line
System.out.println();
// Let's define each multiplication as x * j
// For each j...
for (int i = 1; i <= 12; i++) {
// ...print all of the x's and their products
for (int j = 1; j <= 12; j++) {
System.out.print(j + " * " + i + " = " + j * i + "\t");
}
// Move to the next line for the next row of j's
System.out.println();
}
}
In this table:
1 * 1 = 1 2 * 1 = 2 3 * 1 = 3
What is changing? The first operand. Therefore, you need to nest the for loops
as the for loop for the first operand nested in the loop for the second operand to get the desired results.
Think about it this way: for each of the second operand, print all of the calculations for the first operands in a row. This way, you get the desired columns.
If this is not what you meant, please let me know in the comments.
Hope this helps.
I have written a simple program in java to find the factorial, which works fine. I am now trying to refine the output, but I'm not sure how to do it.
My Program:
import java.util.Scanner;
public class UserInput {
public static void main(String[] args) {
int fact = 1;
Scanner number = new Scanner(System.in);
System.out.println("Enter the number : ");
int n = number.nextInt();
if (n < 0) {
System.out.println("Enter positive number");
} else {
System.out.print("Factorial Sequence is :");
for (int i = n; i >= 1; i--) {
fact = fact * i;
System.out.print(i + "*");
}
System.out.println("Factorial of number " + n + " is :" + fact);
}
}
}
Output shown is in this format (a single line, * after the 1):
Factorial Sequence is :5*4*3*2*1*Factorial of number 5 is :120
I want output in this format:
Factorial Sequence is :5*4*3*2*1
Factorial of number 5 is :120
Since 1 is not going to modify the factorial result your code can be rewriten as:
for (int i = n; i >= 2; i--) {
fact = fact * i;
System.out.print(i + "*");
}
System.out.println("1");
Another option is to use string concatenation during your for loop:
String s = "Factorial Sequence is :";
for (int i = n; i >= 1; i--) {
fact = fact * i;
s += i + (i > 1 ? "*" : "");
}
System.out.println(s);
Only 'benefit' this has over the other options is it saves calling System.out.print each iteration, at the expense of a string concatenation operation. Probably no performance difference at all, and certainly not significant here, but it is an alternate means to the same end.
EDIT: Use #demostene's excellent suggestion to avoid the final '*' after the final '1' - it avoids the conditional expression within the for loop, which is really nice as your factorial becomes larger.
To make the gap, you can add an \n literal to represent a newline.
System.out.println("\nFactorial of number " + n + " is :" + fact);
And for the last *, you can either remove it at the end or not add it if i is 1..
System.out.print(i + (i > 1?"*":""));
This says if i is greater than 1, return a *, otherwise return an empty string.
Just add a print line statement:
System.out.println(); // add this line
System.out.println("Factorial of number " + n + " is :" + fact);
I am trying to convert an integer to a binary number using an integer array. The first conversion is toBinaryString where I get the proper conversion "11111111" then the next step to convert to an array. This is where it goes wrong and I think its the getChar line.
int x = 255;
string=(Integer.toBinaryString(x));
int[] array = new int[string.length()];
for (int i=0; i< string.length(); i++){
array[i] = string.getChar(i);
Log.d("TAG", " Data " + array[1] "," + array[2] + "," + array[3]);
Log displays ( Data 0,0,0 ) the results I am looking for is ( Data 1,1,1 )
Here is the final code and it works.
// NEW
int x = 128;
string=(Integer.toBinaryString(x));
int[] array = new int[string.length()];
for (int i=0; i < string.length(); i++) {
array[i] = Integer.parseInt(string.substring(i,i+1));
}
Log.d("TAG", "Data " + array[0] + "" + array[1]+ "" + array[2] + "" + array[3]+ " " + array[4]+ "" + array[5] + "" + array[6] + "" + array[7]);
// Take your input integer
int x = 255;
// make an array of integers the size of Integers (in bits)
int[] digits = new Integer[Integer.SIZE];
// Iterate SIZE times through that array
for (int j = 0; j < Integer.SIZE; ++j) {
// mask of the lowest bit and assign it to the next-to-last
// Don't forget to subtract one to get indicies 0..(SIZE-1)
digits[Integer.SIZE-j-1] = x & 0x1;
// Shift off that bit moving the next bit into place
x >>= 1;
}
how about :
array[i] = Integer.parseInt(string.substring(i,i+1));
First of all, an array starts from the index of 0 instead of 1, so change the following line of code:
Log.d("TAG", " Data " + array[1] "," + array[2] + "," + array[3]);
To:
Log.d("TAG", " Data " + array[0] "," + array[1] + "," + array[2]);
Next, the following line of code:
array[i] = string.getChar(i);
You are trying to get a character value to an Integer array, you may want to try the following instead and parse the value into an Integer (also, the "getChar" function does not exist):
array[i] = Integer.parseInt(String.valueOf(string.charAt(i)));
I hope I've helped.
P.S - Thanks to Hyrum Hammon for pointing out about the String.valueOf.