print either int or double with selfmade print method in java - java

I have a programm that creates 2D arrays of ints and double (some are int, some are double). I wrote a method to print those arrays as a map to the console. But instead of having two methods for int and double each, i wondered if its possible to accept both int and double as a parameter.
This is my print function:
private void printMap(int map[][]){
for (int i=0; i<map.length;i++){
for (int j=0; j<map[i].length;j++){
if(map[i][j]<1000)System.out.print(" ");
if(map[i][j]<100)System.out.print(" ");
if(map[i][j]<10)System.out.print(" ");
System.out.print(imap[i][j]+" ");
}
System.out.println("");
}
}
Right now i have 2 times the same except for the params, like:
private void print_intMap(int map[][]){..}
private void print_doubleMap(double map[][]){..}
and I want it to be like
private void printMap(/*either int or double*/){..}
Any ideas?
thx in advance

You could use the Number type as your array type. It is extended by both Integer and Double. This type can be created from either double or int primitive types via Autoboxing which will do this conversion for you automatically.
Number doubleNumber = 1.0;
Number intNumber = 1;
Then your code would look like:
private void printMap(Number map[][]) {
for (int i = 0; i < map.length; i++) {
for (int j = 0; j < map[i].length; j++) {
if(map[i][j].intValue() < 1000) System.out.print(" ");
if(map[i][j].intValue() < 100) System.out.print(" ");
if(map[i][j].intValue() < 10) System.out.print(" ");
System.out.print(imap[i][j].intValue() + " ");
}
System.out.println("");
}
}

I believe your best option here would be to use polymorphism. Essentially, you create two methods with the same name. The only difference will be the parameters- one will take an int, and the other will take a double. For example
private void printMap(int map[][])
private void printMap(double map[][])
This would allow you to call printMap with your array without needing a check on the type.

What you want to do is called "Method Overloading": http://en.wikipedia.org/wiki/Method_overloading
Here is a great example fiting with what you want to do! :
public class MainClass {
// method printArray to print Integer array
public static void printArray(Integer[] inputArray) {
// display array elements
for (Integer element : inputArray)
System.out.printf("%s ", element);
System.out.println();
}
// method printArray to print Double array
public static void printArray(Double[] inputArray) {
// display array elements
for (Double element : inputArray)
System.out.printf("%s ", element);
System.out.println();
}
// method printArray to print Character array
public static void printArray(Character[] inputArray) {
// display array elements
for (Character element : inputArray)
System.out.printf("%s ", element);
System.out.println();
}
public static void main(String args[]) {
// create arrays of Integer, Double and Character
Integer[] integerArray = { 1, 2, 3, 4, 5, 6 };
Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7 };
Character[] characterArray = { 'H', 'E', 'L', 'L', 'O' };
System.out.println("Array integerArray contains:");
printArray(integerArray); // pass an Integer array
System.out.println("\nArray doubleArray contains:");
printArray(doubleArray); // pass a Double array
System.out.println("\nArray characterArray contains:");
printArray(characterArray); // pass a Character array
}
}
Taken from this website: http://www.java2s.com/Tutorial/Java/0100__Class-Definition/Usingoverloadedmethodstoprintarrayofdifferenttypes.htm

This is impossible. A few things you can do are:
Method overloading. You can make methods with the same name, as long as they have different parameters. E.g.:
private void printMap(int map[][]) {...}
private void printMap(double map[][]) {...}
You can then call printMap with either and int[][] or a double[][] as the argument, and it will execute the corresponding method.
Make it accept a Number[][]:
private void printMap(Number map[][]) {...}

You can keep the method taking as parameter the double and make a cast when calling the method with an 'int'
printMap((double)map[][])

I suggest converting the int variable into double variable, and then use it in your class (i believe it is the simplest solution):
int x=7;
double y=(double)x;
print_doubleMap(y);
//or
print_doubleMap((double)x);

You can use reflection but it is ugly
public static void print(int[][] ints) {
printMatrix(ints);
}
public static void print(double[][]] doubles) {
printMatrix(doubles);
}
public static void printMatrix(Object o) {
int len1 = Array.getLength(o);
for(int i = 0; i < len1; i++) {
Object o2 = Array.get(o, i);
int len2 = Array.getLength(o2);
for(int j = 0; j < len2; j++)
System.out.printf("%4s ", Array.get(o2, j);
System.out.println();
}
}
I don't know if this is any cleaner than just copying a method.
public static void print(int[][] ints) {
for(int[] is : ints) {
for(int i : is)
System.out.printf("%4d ", i);
System.out.println(i);
}
}

Related

Create new array from method that takes two parameters java

I am new to programming and trying to learn Java and I am trying to do some Java questions that I find quite tough for a beginner. The question asks to write a method that takes a double c and and array v of type double as it's parameters. The method should return a new array of double formed by multiplying all the elements of array v by c.
I really have no idea to do this and if anyone could help on this I'd appreciate it.
I have written some code but I don't understand what I am supposed to do exactly.
public static double times( double c, double [] v)
int i =0;
for( i =0; i < v .length; i++){
myArray =(c * v[i]);
i++;
}
}
public class Main {
public static void main(String[] args) {
double [] v={5.1,5.2,3.0,4.0};
double c= 4.1;
System.out.println(times(v,c));
It’s a good start but your method should return an array of doubles: double[].
public static double[] times( double c, double [] v)
double[] myArray = new double[v.length]; // this is a new array
int i =0;
for( i =0; i < v .length; i++){
myArray[i] =(c * v[i]); // assign new values to your array
// i++; << don’t need this line as your for loop is already incrementing i
}
return myArray;
}
The answer mentioned above is correct but you could do the same in the same array i.e double[] v, instead of creating a new array, just for optimization scenario
Read carefully your problem.
I added comments to the code so you understand what you did wrongly:
// Return a double[] instead of double
public static double[] times( double c, double [] v)
// Create a new double array
double[] myArray = new double[v.length];
for (int i = 0; i < v.length; i++) {
// Set each element of the new array equals to the old array element in
// The same position multiplied by c
myArray[i] = c * v[i]; // Parenthesis are not needed here
// i++ is not needed because you already add 1 to i in the for instruction
}
// Return the new array
return myArray;
}
Also be careful what you print. I believe you want to print the new values not the array reference.
public static void main(String[] args) {
double[] v = {5.1, 5.2, 3.0, 4.0};
double c = 4.1;
double[] newV = times(c, v);
System.out.print("Array address: ");
System.out.println(newV);
System.out.print("Array as string: ");
System.out.println(Arrays.toString(newV));
System.out.print("Array values for: ");
for (int index = 0; index < newV.length; ++index) {
System.out.println(newV[index]);
}
System.out.print("Array values foreach: ");
for (double value : newV) {
System.out.println(value);
}
}

Java for loop where values jump

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));
}
}

Finding the occurrence of values within an array

My question is how do I find the frequency of the numbers "8" and "88" in this array, using a method. It seems as what I put in the assessor method does not appear to work. For example, if "8" occurs three times in the array the output would be "3" and the same for "88".
If I am wrong please point me to the right direction. Any help with my question is greatly appreciate.
import java.util.Random;
public class ArrayPractice {
private int[] arr;
private final int MAX_ARRAY_SIZE = 300;
private final int MAX_VALUE = 100;
public ArrayPractice() {
// initialize array
arr = new int[MAX_ARRAY_SIZE];
// randomly fill array with numbers
Random rand = new Random(1234567890);
for (int i = 0; i < MAX_ARRAY_SIZE; ++i) {
arr[i] = rand.nextInt(MAX_VALUE) + 1;
}
}
public void printArray() {
for (int i = 0; i < MAX_ARRAY_SIZE; ++i)
System.out.println(arr[i]);
}
public int countFrequency(int value) {
for (int i: MAX_VALUE) {
if (i == 8)
i++;
}
public static void main(String[] args) {
ArrayPractice ap = new ArrayPractice();
System.out.println("The contents of my array are: ");
ap.printArray();
System.out.println("");
System.out.println("The frequency of 8 is: " + ap.countFrequency(8));
System.out.println("The frequency of 88 is: " + ap.countFrequency(88));
}
}
}
You need to iterate over arr and increment a variable when an element matches value.
public int countFrequency(int value) {
int count = 0;
for (int num : arr) {
if (num == value) {
count++;
}
}
return count;
}
You have a hard-coded seed, so your random values won't be random on different runs. You are also hard-coding your frequency count against 8 (instead of value). But honestly, I suggest you revisit this code with lambdas (as of Java 8), they make it possible to write the array generation, the print and the count routines in much less code. Like,
public class ArrayPractice {
private int[] arr;
private final int MAX_ARRAY_SIZE = 300;
private final int MAX_VALUE = 100;
public ArrayPractice() {
// randomly fill array with numbers
Random rand = new Random();
arr = IntStream.generate(() -> rand.nextInt(MAX_VALUE) + 1)
.limit(MAX_ARRAY_SIZE).toArray();
}
public void printArray() {
IntStream.of(arr).forEachOrdered(System.out::println);
}
public int countFrequency(int value) {
return (int) IntStream.of(arr).filter(i -> i == value).count();
}
}
You need to iterate over the array and increment a counter variable when an element matches i
what you are doing is increment i instead of a counter:
if (i == 8)
i++;
} // if i is 8 then i becomes 9
A working example:
public int countFrequency(int i) {
int count = 0;
for (int num : arr) {
if (num == i) {
count++;
}
}
return count;
}
Solution:
public int countFrequency(int value) {
int counter = 0; // here you will store counter of occurences of value passed as argument
for (int i : arr) { // for each int from arr (here was one of your errors)
if (i == value) // check if currently iterated int is equal to value passed as argument
counter++; // if it is equal, increment the counter value
}
return counter; // return the result value stored in counter
}
Explanation:
Main problem in your code was countFrequency() method, there are few bugs that you need to change if you want to make it work correctly:
You passed value as argument and you didn't even use it in the body of method.
for (int i : MAX_VALUE ) - you meant to iterate over elements of arr array, (You can read it then as: For each int from arr array do the following: {...}.
if (i == 8) i++ - here you said something like this: Check if the current element from array (assuming that you meant MAX_VALUE is an array) is equal to 8, and if it is - increment this value by 1 (so if it were 8, now it's 9). Your intention here was to increment counter that counts occurences of 8.
You might want to consider making these improvements to countFrequency() method, to make it work properly.

list of integer arrays is changed java

I am using a list of integer arrays, which is a class variable, to hold the answers. The integer arrays are added to the list in a method, and the results are fine (has 1s). But when I fetch it in main method, the value in it is all 0s! I do not understand, where is the list changed?
public class test {
private static int sum=0;
static ArrayList<Integer[]> res = new ArrayList<Integer[]>();
private static double max=0;
public static void main(String[] args) {
int n = 6;
double B = 23.6;
double[] menu = { 1.2, 2, 2.5, 3.5, 3.2, 6.2, 7.8, 4.0, 5.6, 10, 6.5 };
Integer[] solution = new Integer[menu.length];
combinate(menu, 0, n,0, res, solution);
for(int i=0;i<res.size();i++) {
//not getting the element!!!!!!!!!!!!
//Integer[] sol = res.get(i);
System.out.println(i+" "+res.get(i));
System.out.println("Arraylist contains:"+Arrays.toString( res.get( i ) ) );
double sums = 0.0;
for (int j = 0; j < res.get(i).length; j++) {
if(res.get(i)[j]!=null)
sums += menu[j] * res.get(i)[j];
}
if (max < sums && sums < B) {
max = sums;
}
}
System.out.println(max + " max");
}
public static void combinate(double[] left, int n, int k,int sum,
ArrayList<Integer[]> res, Integer[] holder) {
if (n == left.length) {
if (sum == k) {
res.add(holder);
System.out.println(res.size()+" "+Arrays.toString(res.get(res.size()-1)));
}
sum = 0;
return;
}
{
holder[n] = 1;
sum++;
combinate(left, n + 1, k, sum,res, holder);
holder[n] = 0;
sum--;
combinate(left, n + 1, k, sum,res, holder);
}
}
}
}
The answers looks like this:
when print in method combinate, the list elements looks like [1111100000]
while in main method, there are all [000000000000]
what goes wrong here?
if (sum == k)
{
res.add(holder.clone()); // take copy of holder at that moment
System.out.println(res.size()+" "+Arrays.toString(res.get(res.size()-1)));
}
Will Help.
[See Experiment : http://rextester.com/DNNZ68674 ]
Have your method "combinate" return new res like public static ArrayList<Integer[]> combinate(double[] left, int n, int k,int sum,
ArrayList<Integer[]> res, Integer[] holder)
then in your main : res = combinate(...);
You have only a single Integer[] instance that you add to your result (res.add(holder)) and overwrite while unwinding the recursion.
You should add a clone of your array to the result:
res.add(holder.clone());
In the original code you're passing the "holder"-variable as a parameter. In Java parameters are passed by value.
This means, you can change the value inside of the combinate-function, but this will never be reflected back to the calling main-function - that's the nature of call by value.

Computing the sum of values that came from a split String in an array in Java

Basically I am wondering how I could make a method that takes a String that has a series of decimal numbers separated by spaces and then (after splitting the string according to separate numbers) returns a double. Then using the doubles returned, returning the sum of all the decimal numbers rounded to the nearest whole number.
Example: Like let's say I input String “42.5 7.2 1.2” and I want to make it return the sum of all the decimal numbers rounded to the nearest whole number, which here would be 51.0.
Here is my attempt so far.
String s = text1;
String[] ls;
ls = s.split(" ");
for(int i = 0; i<= s.length(); i++){
double a = Double.parseDouble(ls[i]);
Start with String.split, this will return an array of Strings
Create an array of double set to the same size as the String array
Iterate this array of Strings and parse each value to a double, adding them to the double array
Return this double array.
Iterate the double array, adding each value to sum value of type double.
Use Math.round to round the result
Take a look at Arrays and Control Flow Statements, in particular The for Statement
...Create an array of double...
String[] ls = s.split(" ");
double[] doubles = new double[ls.length];
...Iterate this array of Strings and parse each value to a double...
for (int index = 0; index < ls.length; index++) {
doubles[index] = Double.parseDouble(ls[index]);
}
You need something like this (if I understand your question):
public static double roundedSum(String s) {
String[] ls = s.split(" ");
double sum = 0;
for(int i = 0; i < ls.length; i++){
sum += Double.parseDouble(ls[i]);
}
return Math.round(sum);
}
And then to test it:
public static void main(String[] args) {
String s = "42.5 7.2 1.2";
System.out.println ( roundedSum(s) ); // prints 51.0
}
As a note, your for loop was wrong:
for(int i = 0; i<= s.length(); i++){
First of all, you can never go until <= the length (unless you subtract 1). Indexes start at 0, so the last position of the string is the length - 1.
Also, you were using the length of the string; you need to be using the length of the array as the bound.
public float rnd (String st) {
String[] v = st.split(" ");
float sum = 0.0f;
for (String s : v) {
sum += Float.valueOf(s);
}
return(Math.round(sum));
}
or replacing the float return by an int return (the question in not very clear on this).
Something like this?
public double getSum(String dec)
{
String[] nums = dec.split(" ");
double total = 0;
for(String a : nums)
total += Double.parseDouble(a);
return Math.round(total);
}
To read input just do
public void read()
{
Scanner scan = new Scanner(System.in);
//declare variable
variableHere = scan.nextLine() scan.nextInt() or w.e. you want
}
Here this works
package Split;
public class Split {
public Split(){
addEm("42.5 7.2 1.2");
}//constructor
private void addEm(String st) {
int i =0;
int len = st.length();
double sum =0 ;
String s = "";
st.charAt(0);
for(int j =0; j< len;j++ ){
s = s+st.charAt(j);
if(st.charAt(j)==' ' || j==len-1){
sum = sum + Double.parseDouble(s);
s = "";
}
}
System.out.print(sum);
}
public static void main (String args[]){
new Split();
}
}
the output will look like this
50.900000000000006...
Just round up the value to an int before output
If I want to avoid all rounding problems, but don't care about using arrays or using doubles, I might do it like this.
public double splitAndSum(String input) {
BigDecimal sum = BigDecimal.ZERO;
for (String number : input.split("\\s+")) {
sum = sum.add(new BigDecimal(number));
}
return sum.round(new MathContext(0)).doubleValue();
}

Categories

Resources