This question already has answers here:
Java: getting a value from an array from a defined location
(3 answers)
Closed 5 years ago.
Why is this happening, why isnt it giving me *ThisIsWhatItShouldBe
Code
class ArreyTable{
public static void main(String OKM[]){
System.out.println("Index\tValue");
int px[] = {144,240,360,480,720};
for(int counter=0; counter<px.length; counter++){
System.out.println(counter + "\t" + px);
}
}
}
cmd Result
Index Value
0 [I#7852e922
1 [I#7852e922
2 [I#7852e922
3 [I#7852e922
4 [I#7852e922
ThisIsWhatItShouldBe
Index Value
0 144
1 240
2 360
3 480
4 720
You're printing the entire array instead of the relevant element of it, which you can access by the [] operator:
for(int counter=0; counter<px.length; counter++){
System.out.println(counter + "\t" + px[counter]);
// Here ------------------------------^
}
In the code block
for(int counter=0; counter<px.length; counter++){
System.out.println(counter + "\t" + px);
}
You are each time converting the array px to a string, which is [I#7852e922 for internal JVM reasons.
You have to indicate the index on the array:
for(int counter=0; counter<px.length; counter++){
System.out.println(counter + "\t" + px[counter]);
}
That will give the desired result.
Additionally you could replace the println with a printf:
for(int counter=0; counter<px.length; counter++){
System.out.printf("%2d: %3d%n", counter, px[counter]);
}
just change this line :
System.out.println(counter + "\t" + px[counter]);
So it will know what value to return ;)
You were originally printing the entire px array object. What was being printed was the output of the toString() function of the array object.
Object.toString() method returns a string, composed of the name of the class, an # symbol and the hashcode of the object in hexadecimal.
when you use px[counter], it references to the element value at that index.
Correct solution would be:
for(int counter=0; counter<px.length; counter++){
System.out.println(counter + "\t" + px[counter]);
}
Related
here remember array size and values is defined by user by the help of scanner class and i am using java
task is to find sum of first and last element and 2nd and 2nd last and so on
i already try research but failed
thanks in advance
int sum = 0;
int f = 0;
System.out.println("Your Array is even");
System.out.println("Kinldy enter Your Values of Array");
for(int i = 0 ; i<array.length ; i++)
{
array[i] = s.nextInt();
for(int j = 0 ; j< array.length-i-1 ; j++)
{
sum = j + array.length+1 ;
}
}
System.out.println("Your Sum " + sum);
You could just loop over your array and use the index to find the corresponding numbers from both sides.
The first element can be found by simply doing: array[i].
The corresponding element from the other side can be found by: array[array.length - 1 - i].
The complete code could be something like this:
public static void main(String[] args) {
int[] array = {1, 3, 6, 4, 1, 8};
for(int i = 0; i < array.length / 2; i++)
{
int firstNumber = array[i];
int secondNumber = array[array.length - 1 - i];
int sum = firstNumber + secondNumber;
System.out.println(firstNumber + " + " + secondNumber + " = " + sum);
}
}
Output:
1 + 8 = 9
3 + 1 = 4
6 + 4 = 10
I made the assumption that you only want to do this for half of the array. That's why the for loop is only executed as long as i<array.length / 2. This solution assumes that the length of your array is always an even number. If your array has an uneven length, the middle element will not be considered.
In case you do want to do this for the complete array, all you have to do is remove the / 2 from the for loop statement. The output will be:
1 + 8 = 9
3 + 1 = 4
6 + 4 = 10
4 + 6 = 10
1 + 3 = 4
8 + 1 = 9
This question already has answers here:
Java Increment / Decrement Operators - How they behave, what's the functionality?
(2 answers)
Closed 7 years ago.
I've seen this question (from a multiple choice) "what is the output of the following program" :
class array_output {
public static void main(String args[])
{
int array_variable [] = new int[10];
for (int i = 0; i < 10; ++i) {
array_variable[i] = i/2;
array_variable[i]++;
System.out.print(array_variable[i] + " ");
i++;
}
}
}
The expected output is:
1 2 3 4 5
It is clear to me that the value i is incremented twice, first in the body of the loop and at the last line.
But I don't really get what the line array_variable[i]++; is doing.
Any suggestions?
Thanks in advance to answer to this newbie question!
The post-fix increment and decrement operators return the value of a variable before altering its value. Consider the following:
int anInt = 0;
System.out.println("anInt: " + anInt);
// anInt: 0
System.out.println("anInt: " + anInt++);
// anInt: 0
System.out.println("anInt: " + anInt);
// anInt: 1
System.out.println("anInt: " + ++anInt);
// anInt: 2
System.out.println("anInt: " + anInt);
// anInt: 2
So basically, anInt++ returns the value of anInt before incrementing it. ++anInt increments the value of anInt before returning the (freshly-incremented) value.
array_variable[i]++; increments the value that is stored in array_variable[i] by one.
I've been working on a few array examples. with some success along alone the way. I've been working on this code for the pass few days and just cant understand the purpose of this increment in the loop body. it usually makes since when it is isolated but this time i have no idea what it does.
Count the occurrences of integers between 1 and 10
Scanner input = new Scanner(System.in);
int[] count = new int[10];
System.out.println("Enter the integers between 1 and 10: ");
// Read all numbers
// 2 5 6 5 4 3 9 7 2 0
for (int i = 0; i < count.length; i++)
{
int number = input.nextInt();
count[number]++; //this is the one that perplexes me the most
}
//Display result
for (int i = 0; i < 10; i++)
{
if (count[i] > 0)
{
System.out.println(i + " occurs " + count[i]
+ ((count[i] == 1) ? " time" : " times"));
}
}
count[number]++; //this is the one that perplexes me the most
It increments the value in the array count at index number. Perhaps, splitting it may help understand:
int tmp = count[number];
tmp = tmp + 1;
count[number] = tmp;
i.e. The value of count[number] will be incremented after the execution of the the statement count[number]++;.
Also a note on how post-increment works.
If it were used as:
int value = count[number]++;
then value will have the old value at count[number] and the increment will be done after the execution of the statement.
I wrote a programm to print out all the prime number up to a limit. Then put those prime numbers into an ArrayList, convert this ArrayList into an array, finally print the numbers out with their index.
Note: I couldnt print out an ArrayList with a for loop, it's possible with an array only, hence the conversion.
My question is:
Is there anyway to do it without pushing the numbers into an ArrayList first, instead put them right away into an emty array of a length < given limit.
Thanks for you help!
was browsing SO in the last 2 days and couldnt find anything
import java.util.Scanner;
import java.util.ArrayList;
public class test {
public static void main(String[] args){
//get input till which prime number to be printed
System.out.print("Enter the number till which prime number to be printed: ");
int limit = new Scanner(System.in).nextInt();
System.out.print("\n");
ArrayList<Integer> myArray = new ArrayList<Integer>();
//printing primer numbers till the limit ( 1 to 10)
System.out.println("Printing prime number from 1 to " + limit + "\n");
for(int number=2; number <= limit; number++){
if(isPrime.numberPrime(number)){
myArray.add(number);
}
}
System.out.println(myArray + "\n");
//Convert ArrayList into an Array
int[] newArray = new int[myArray.size()];
for(int i = 0; i < myArray.size(); i++) {
newArray[i] = myArray.get(i);
}
System.out.println("There were " + myArray.size() + " prime numbers");
System.out.println("Index\tValue");
for(int counter = 0; counter<newArray.length; counter++){
System.out.println(counter+1 + "\t" + newArray[counter]);
}
}
here is the result:
Enter the number till which prime number to be printed: 10
Printing prime number from 1 to 10
[2, 3, 5, 7]
There were 4 prime numbers
Index Value
1 2
2 3
3 5
4 7
No need to do this
//Convert ArrayList into an Array
int[] newArray = new int[myArray.size()];
for(int i = 0; i < myArray.size(); i++) {
newArray[i] = myArray.get(i);
}
System.out.println("There were " + myArray.size() + " prime numbers");
System.out.println("Index\tValue");
for(int counter = 0; counter<newArray.length; counter++){
System.out.println(counter+1 + "\t" + newArray[counter]);
}
In place of this, simply write
System.out.println("There were " + myArray.size() + " prime numbers");
System.out.println("Index\tValue");
for(int i=0;i<myArray.size();i++)
System.out.println(i+1 + "\t" + myArray.get(i));
I am trying to count the frequency of ASCII characters from a String input that was converted to a character array.
I tried to implement the accepted answer from this thread, along with my code to print the results in a 3-column table.
package com.mypackage.mp;
import java.util.*;
public class AsciiCounter {
public static void displayAsciiOccurrence(String inputWords) {
int[] iaCount = new int[256]; //this
char[] caInputWords = inputWords.toCharArray();
int i = 0;
for(i = 0; i < caInputWords.length; i++) {
iaCount[caInputWords[i]]++;
}
// Print table
System.out.println("\nDEC\tASCII\tFREQ");
for(int ctr = 0; ctr < 256; ctr++) {
System.out.println(ctr +"\t" + (char) (ctr) + "\t" + iaCount[caInputWords[i]]); //this
}
}
public static void main(String[] args) {
String inputWords = null;
Scanner scn = new Scanner(System.in);
System.out.print("Enter words: ");
inputWords = scn.nextLine();
displayAsciiOccurrence(inputWords); //this
scn.close();
}
}
However, it is returning an ArrayIndexOutOfBoundsException. My desired output is supposed to be:
Enter words: AA bC! d
DEC ASCII FREQ
0
.. .. ..
32 2
33 ! 1
.. .. ..
65 A 2
66 B 0
67 C 1
..
98 b 1
99 c 0
100 d 1
..
255
(The .. pertains to whatever is in between and must print 0 as frequency.)
Stack Trace:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 8
at
com.mypackage.mp.AsciiCounter.displayAsciiOccurrence(AsciiCounter.java:20)
at
com.mypackage.mp.AsciiCounter.main(AsciiCounter.java:31)
The error is in your printing loop:
System.out.println(ctr +"\t" + (char) (ctr) + "\t" + iaCount[caInputWords[i]]);
Since i hasn't changed since the first loop, it is equal to caInputWords.length at this point.
I guess you just meant:
System.out.println(ctr +"\t" + (char) (ctr) + "\t" + iaCount[ctr]);
As a side note, you might not want to print all the ASCII characters themselves. Some of them don't represent printable characters or are whitespace. One simple way around this is to check that iaCount[ctr] > 0 before printing so you only print characters that were in the String to begin with.
You have a problem in your second loop:
for(int ctr = 0; ctr < 256; ctr++) {
System.out.println(ctr +"\t" + (char) (ctr) + "\t"
+ iaCount[caInputWords[i]] // HERE
);
}
You meant iaCount[ctr]! You use i which is 256 when you enter this loop, since it has been set to this value by your previous loop. And since the iaCount array is only 256 chars long, this index is out of bounds.
Also, you fail to check what happens if you enter a non ASCII character.
To avoid this kind of error, change your first for loop to:
for(int i = 0; i < 256; i++)
Doing so in your first loop would have shown that i didn't exist in the second.
the i variable has not been reset. but you don't need to use variable i at all after the frequency calculation. You need to use ctr for frequency of all the characters.
for(int ctr = 0; ctr < 256; ctr++) {
System.out.println(ctr +"\t" + (char) (ctr) + "\t" + iaCount[ctr]);
}
That line can throw exception.
System.out.println(ctr +"\t" + (char) (ctr) + "\t" + iaCount[caInputWords[i]]);
Change it to that
for(int ctr = 0; ctr < 256; ctr++) {
System.out.println(ctr +"\t" + (char) (ctr) + "\t" + iaCount[ctr]);
}