While I was attempting to make a method that runs calculations and returns the binary value for a small project I'm working on; I was trying to have the method parameters include all of the values to add together, but when doing so I realized I don't know how to do so without using an array of some sort.
Is it possible to have the parameters in the following method addBinary change based on the amount I wish to add?
public int addBinary() // I want these parameters to have all integers I wish to add
{
// Calculations go here //
}
Essentially, if I wish to run the program and add 5 values the first time and 25 the next; how would I get all of the values into the method without creating an array?
You can use variable number of arguments in the method definiton(using ellipses i.e ... ) like this:
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static int add(int ...arr)
{
int sum=0;
for(int i=0;i<arr.length;i++)
sum+=arr[i];
return sum;
}
public static void main (String[] args) throws java.lang.Exception
{
System.out.println(add(1, 2, 3, 4));
System.out.println(add(1, 2, 3));
}
}
Output:
10
6
https://ideone.com/PHL8Lb
I don't know why you are not thinking of using arrays here. Just pass an array as a parameter and do the calculations you want to do.
public int addBinary(int a[])
{
for(int i=0;i<a.length;i++)
sum+=a[i];
return sum;
}
Or by using an arraylist
public int addBinary(ArrayList m)
{
int sum = 0;
for(i = 1; i < m.size(); i++)
sum += m.get(i);
return sum;
}
Link for the code Ideone
You can use varargs for this
void testapp(String ...studentsName){
for (int i = 0; i < studentsName.length; i++) {
System.out.println(studentsName[i]);
}
}
Related
If I have three variables and I want a value in a for loop to jump from one to the next, how would I do that? You can assume the first variable is the smallest and the third is the biggest, and that the variables are not equal to one another(although if there is a way to do it where they are equal that would be good).
I have an example for if it was only two values.
int val1 = 5;
int val2 = 9;
for(int i = val1; i <= val2; i=i+(val2-val1) {
}
In this case i would first be 5, and then 9. Also, is there any way to do it with a different amount of variables?
I'm not 100% certain I understand your question, but you could do
for(int i = val1; i <= val2; i = (i == val1) ? val2 : val2+1) {
// ...
}
If you need more values, I would put them in an array and use a for-each loop over that
int[] vals = {5,9,17};
for (int i : vals) {
// ...
}
you can place those in an array and access to it by index
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
int[] myArray = {4, 6 , 9};
for(int x : myArray)
{
System.out.println(x);
}
//or....
for(int x =0; x<3; x++)
{
System.out.println(myArray[x]);
}
}
}
As #Gonen I said, you can handle this using stream. If you want '...the first variable is the smallest and the third is the biggest...' you should use stream.sorted() to get sorted values.
x corresponds to each one element of the vals list while traversing. So you can do whatever you want in the forEach block with using x
List<Integer> vals = Arrays.asList(5,9,17);
vals.stream().sorted().forEach(x -> {
System.out.println(x);
});
If we are already being a bit silly, this will do the trick for as many values as you want, and inside a for loop. But I would never actually write code like this because its completely unreadable:
package package1;
public class SillySkip {
public static void main(String[] args) {
for( int data[] = {5,10,-4}, i, j=0; j < data.length && (i = data[j]) % 1 == 0 ; ++j )
{
System.out.println(i);
}
}
}
From Java 8 and up you can use Stream.of to iterate arbitrary values like this:
package package1;
import java.util.stream.Stream;
public class IterateSomeValues {
public static void main(String[] args) {
Stream.of(5,10,-4).forEach(e->System.out.println(e));
}
}
I am running this code:
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
class Ideone
{
public static int solution(int X, int[] A) {
int[] myNumbers = new int[X];
for (int i = 0; i < A.length; i++){
myNumbers[A[i]] = A[i];
}
return -1;
}
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
int[] A = {1,3,1,4,2,3,5,4};
System.out.println(solution(5,A));
}
}
However, I get a run-time error. I don't know why. I need to store the value of the array in A in another array with that value as an index. I.e myNumbers[4] = 4.
myNumber indexes goes from 0 to 4, at some point you are trying to access the index 5 which does not exist
So either pass 6 to solution or use myNumber[A[i]-1] (so myNumber[0] = 1)
I'm making a histogram program in which I have one array that generates a random number, another that makes them into an array, and a last one that attempts to use that array and tell how many characters are in each [] of the array. My problem is that I cannot find a way to count how many characters are in each array element and outprint it. I'm trying to use the .length function but it doesn't seem to be working. Is there another way that I could do this?
Here is my code. My problem is with my last method, before my main method.
package arrayhistogram;
/**
*
* #author Dominique
*/
public class ArrayHistogram {
public static int randomInt(int low, int high){
double x =Math.random ()* (high - low)+low;
int x1=(int)x;
return x1;
}
public static int[] randomIntArray(int n){
int[] a = new int[n];
for (int i=0; i<n; i++) {
a[i] = randomInt(-5, 15);
}
return a;
}
public static int[] arrayHist () {
int[] x=randomIntArray(30);
for (int i = 0; i < x.length; i++) {
System.out.println(x[i].length);
}
return x;
}
public static void main(String[] args) {
arrayHist();
}
}
Replace
System.out.println(x[i].length);
with
System.out.println(Integer.toString(x[i]).length());
There is no length property on an int. You can use this to get the number of digits in the int.
String.valueOf(x[i]).length()
This first transforms the int into a String and then returns the length of that String. E.g 123 => "123", whose length is 3.
I'm a beginner with Java and I'm trying to make two different programs but I'm having issues with transferring the data from one to the other.
The first program is like a random number generator. It looks like this (simplified, but same idea):
public class Tester{
public static double num;
public static void main(String[] args){
double n;
n = Math.random() * 100;
System.out.println(n);
num = n;
}
public static double gen(){
return num;
}
}
Then, I'm trying to call that function and print n random numbers and put them all into a list. That program looks like this:
public class lister{
public static void main(String[] args){
//declare
int n,counter;
double[] list;
double num;
//initialize
n = Integer.parseInt(args[0]);
list = new double[n];
counter = 0;
double num = Tester.gen();
//add all generated numbers to a list, print them
while (counter < n){
num = Tester.gen();
list[counter] = num;
System.out.println(num);
++counter;
}
}
}
But num just ends up being 0.0 every time. I've tried to not make it static, but that comes with it's own host of issues and, as I understand it, static doesn't mean not changeable.
How do I fix this to make num a new number each time the while loop is run? Is that even possible?
Here is the Suggested Answer:
public class Tester {
public static double gen(){
double n;
n = Math.random() * 100;
return num;
}
}
public class lister{
public static void main(String[] args){
//declare
int n,counter;
double[] list;
double num;
//initialize
n = Integer.parseInt(args[0]);
list = new double[n];
counter = 0;
double num = Tester.gen();
//add all generated numbers to a list, print them
while (counter < n){
num = Tester.gen();
list[counter] = num;
System.out.println(num);
++counter;
}
}
}
If you run the list class main(), then the main() method of Tester class isnt invoked, so the Math.random() never runs. try this :
public class Tester{
public static double gen(){
return Math.random() * 100;
}
}
The thing is that you never call Tester.main() in the lister.main() (you just call Tester.gen() method), therefore since an instance variable double like Tester.num is always initialized to 0.0 value, unless you assign it a different value, you are always getting this value in lister.main()each time you use it.
Your code should work by tweaking Tester.gen() a bit so it is the one which actually returns a random number as follows:
public static double gen(){
return Math.random() * 100;
}
After this, your code should work fine.
Aside from that, the Tester.main() is quite useless since you are already using/running the lister one, and you can use only one main() as entry point for a Java SE application.
This code supposedly checks an array of integers for 9's and returns it's frequency but the method is not being recognized. Any help please to make this code work.
public static int arrayCount9(int[] nums) {
int count = 0;
for (int i=0; i<nums.length; i++) {
if (nums[i] == 9) {
count++;
}
}
return count;
};
public static void main(String[]args){
System.out.println(arrayCount9({1,2,9}));
}
Change your method call to the following:
System.out.println(arrayCount9(new int[]{1,2,9}));
Alternatively:
int[] a = {1,2,9};
System.out.println(arrayCount9(a));
The shortcut syntax {1,2,9} can only be used when initializing an array type. If you pass this notation to a method, it will not be interpreted it as an array by the compiler.