I want to pass System.out.println(); as an argument but the compiler won't allow me to return a void type as an argument. here is what I want it for.
public class Array {
public static void main(String args[]) {
a(data());
}
static void a(e) {
System.out.println(e);
}
static void data() {
...
}
}
So What is want a(data()); to look like after it is compiled is something like this.
a(data()) = System.out.println(data(){...});
Eventually I want to shorthand System.out.println().
What you are doing here is not passing System.out.println() as an argument; you are trying to pass an argument to System.out.println()
Try changing the return type of data() to String, or int, or anything other than void, and return something of that type from it.
Also change the parameter type of e in the function definition of a() to match the return type of data().
After you make these changes, calling a(data()); will actually print something out.
Example:
public static void main(String args[]) {
a(data());
}
// shorthand for System.out.println
static void a(String e) {
System.out.println(e);
}
// a method that returns some data
static String data() {
// replace this with whatever actual data you want to return
return "This is some data...";
}
If you just want to shorthand System.out.println, then have a method with return type void that accepts a string argument and inside of the method just do:
System.out.println(argument)
As mentioned by others, you don't want/need to pass System.out.println as a method argument. However, if you would like to do that (one never knows...), you could do that in Java 8 with Lambda expressions.
Create a functional interface:
#FunctionalInterface
public interface Action {
void run(String param);
}
Passing this interface to a method:
public class MyClass {
public void execute(Action action){
action.run("Hello!");
}
}
Use this class:
MyClass c = new MyClass();
c.execute(System.out::println);
Simply save your println statements to String and return it for printing
Your code:
static void data() {
int array[] = {1,5,6};
int alength = array.length;
System.out.println(" Location\tData");
for(int i=0;i<alength;i++) {
System.out.println(" " + i + "\t\t" + array[i]);
}
}
Change to:
static String data() {
int array[] = {1,5,6};
int alength = array.length;
//Note extra \n symbol for new line
String result = " Location\tData\n";
for(int i=0;i<alength;i++) {
result += " " + i + "\t\t" + array[i] + "\n";
}
return result;
}
then modify your a() method to accept String as a parameter:
static void a(String result) {System.out.println(result);}
A working example could look like this:
public class Array {
public static void main(String args[]) {
println(data());
}
// I strongly advise to use understandable naming
// a() is completely uninformative
static void println(String result) {
System.out.println(result);
}
static String data() {
int array[] = { 1, 5, 6 };
int alength = array.length;
// Note extra \n symbol for new line
String result = " Location\tData\n";
for (int i = 0; i < alength; i++) {
result += " " + i + "\t\t" + array[i] + "\n";
}
return result;
}
}
While the compiler may not allow you to pass a function pointer, it should allow you to pass blocks.
In Objective-C; a block as the following syntax:
void (^action)(NSString *s) = ^(NSString *s){ NSLog(s); }
You can then pass your "action" block around as a parameter, and call it whenever required:
action(#"Hello World");
Blocks are available in all recent variations of C, Wikipedia has a nice article on the subject at http://en.wikipedia.org/wiki/Blocks_(C_language_extension).
I want to change this code
package Array;
import java.util.Random;
public class Array {
public static void main(String args[]) {
data();
a();
random();
a();
array();
a();
rows();
a();
System.out.println("average " + average(45,15,15,48,97,45));
}
static String s() {
return "helloWorld";
}
static void a() {System.out.println();}
static void data() {
int array[] = {1,5,6};
int alength = array.length;
System.out.println(" Location\tData");
for(int i=0;i<alength;i++) {
System.out.println(" " + i + "\t\t" + array[i]);
}
}
static void random() {
Random rdm = new Random();
int freq[] = new int[7];
for(int i=1;i<1000;i++) {
++freq[1+rdm.nextInt(6)];
}
System.out.println("Face\tFrequency");
int frequence = freq.length;
for(int face=1;face<frequence;face++) {
System.out.println(face+"\t"+freq[face]);
}
}
static void array() {
String po[] = {"lala","po","tinkiwinki","disty"};
for(String lala: po) {
System.out.print(lala + " ");
}
System.out.println();
}
static void rows() {
int arrays[][]= {{1,5,78,15},{45,67},{875,15687,158,4515,23,2,2}};
for(int i=0;i<arrays.length;i++) {
for(int j=0;j<arrays[i].length;j++) {
System.out.print(arrays[i][j]+"\t");
}
System.out.println();
}
}
static int average(int...numbers) {
int total=0;
for(int x:numbers)
total += x;
return total/numbers.length;
}
}
class time {
int h, m, s;
void setTime(int hour,int minute,int second) {
h = ((hour>=0 && hour<=24) ? hour : 0);
m = ((minute>=0 && minute<=60) ? minute : 0);
s = ((second>=0 && second<=60) ? second : 0);
}
into this type of code for main.
a(data());
a(random());
a(array());
a(rows());
a("average " + average(45,15,15,48,97,45));
Related
I am new to Java so this could be a naive question. I created a Main class like below, and I would like to write some tests for the getArrays, getAverage, and bubbleSortAscending methods, just for the purpose of learning how to do unit tests.
public class Main {
private static final Scanner scanner = new Scanner(System.in);
public static void main(String [] args) {
int[] myArrays = getArrays(5);
for (int i=0; i<myArrays.length; i++) {
System.out.println("index = " + i + " value = " + myArrays[i]);
}
System.out.println("Average is " + getAverage(myArrays));
int[] sortedArray = bubbleSortAscending(myArrays);
System.out.println("Sorted: \r");
for (int i=0; i<sortedArray.length; i++) {
System.out.println(sortedArray[i]);
}
}
public static int[] getArrays(int number) {
System.out.println("Enter " + number + " integer values.\r");
int[] values = new int[number];
for (int i=0; i<values.length; i++){
values[i] = scanner.nextInt();
}
return values;
}
public static double getAverage(int[] array) {
double sum = 0;
for (int i=0; i<array.length; i++){
sum += array[i];
}
return sum / (double) array.length;
}
public static int[] bubbleSortAscending(int[] array) {
for (int i=0; i<array.length-1; i++){
for (int j=0; j<array.length - i - 1; j++){
int a = array[j];
int b = array[j+1];
if (a > b) {
int c = a;
a = b;
b = c;
}
array[j] = a;
array[j+1] = b;
}
}
return array;
}
}
And IntelliJ automatically generated these test codes for me:
public class MainTest {
#org.junit.Test
public void getArrays() {
}
#org.junit.Test
public void getAverage() {
}
#org.junit.Test
public void bubbleSortAscending() {
}
}
However, when I filled the first one with codes like this:
#org.junit.Test
public void getArrays() {
int[] expectedArray = new int[]{1,2,3,4,5};
int[] generatedArray = getArrays(5);
assertArrayEquals(expectedArray, generatedArray);
}
IntelliJ told me that something is wrong ...
So looks like it's because the getArrays() inside the MainTest is not taking any input argument? Why the getArrays() in the MainTest is not working the same as the getArrays() defined in the Main?
The issue is that you are recursively calling (by mistake) the test method itself, which happens to have the same method name as the tested method.
The test method (MainTest.getTest()), in contrary to the tested method (Main.getTest(int)) does not have any parameter - hence the error message, that you cannot pass the int to that method.
You have to call the tested static method by specifying the class:
#Test
public void getArrays() {
...
int[] generatedArray = Main.getArrays(5); // Call getArrays(int) in Main class
...
}
or change the method name, you will probably have more than one test method anyways:
#Test
public void getArraysReturnsNull() { ... }
// OR
#Test
public void testGetArrays() { ... }
...
Now you can use static import and call tested static method without clasifying the class:
import static segovia.java.learn.Main.getArrays;
#Test
public void testGetArrays() {
int[] generatedArray = getArrays(); // OK now
}
IntelliJ tip:
Hold CTRL and click on the method name.
I am writing a recursive procedure to return a permutation of a string
I get the desired output printed to the console. However, I would like to add the output to an array to be able to work on it further. How can I achieve it?
import java.util.*;
public class Permutation {
public static void main(String args[]) {
permute("A", "BCD");
}
public static void permute(String FirstElement, String Remainder) {
List<String> mylist_tobuild = new ArrayList<String>();
if (Remainder.length() <= 1) {
FirstElement = FirstElement+Remainder;
// System.out.println(FirstElement);
mylist_tobuild.add(FirstElement);
System.out.println(mylist_tobuild);
}
else
for (int i = 0; i < Remainder.length(); i++) {
try {
String newString = Remainder.substring(0, i) + Remainder.substring(i + 1);
permute(FirstElement + Remainder.charAt(i), newString);
} catch (StringIndexOutOfBoundsException exception) {
exception.printStackTrace();
}
}
}
}
I get: [ABCD] [ABDC] [ACBD] [ACDB] [ADBC] [ADCB]
I would like to have: [ABCD, ABDC, ACBD, ACDB, ADBC, ADCB,]
You can supply the List as an argument:
public static void main(String args[]) {
List<String> perms = new ArrayList<>();
permute("A", "BCD",perms);
System.out.println(perms);
}
public static void permute(String FirstElement, String Remainder, List<String> perms) {
if (Remainder.length() <= 1) {
FirstElement = FirstElement+Remainder;
perms.add(FirstElement);
} else {
for (int i = 0; i < Remainder.length(); i++) {
try {
String newString = Remainder.substring(0, i) + Remainder.substring(i + 1);
permute(FirstElement + Remainder.charAt(i), newString, perms);
} catch (StringIndexOutOfBoundsException exception) {
exception.printStackTrace();
}
}
}
}
You are creating a new list every time you go through the permute method. To fix that, you can take your list creation out of the method (e.g. create a static field), so you don't create a new list every time you go through the loop. Then add your print statement after your permutation method in your main class, so you can get the final result.
private static ArrayList<String> mylist_tobuild;
public static void main(String args[]) {
mylist_tobuild = new ArrayList<>(); //initialize list here once
permute("A", "BCD");
System.out.println(mylist_tobuild);
}
I am getting the totals of various String ArrayLists such as [1,3,4]...
by parsing them into integers and getting the total. This worked when I coded each individual one, but when I made a method by passing in the total int value and arraylist I always get a value of zero.
A method would save a lot of time.
public class Playing {
static ArrayList<String> list;
static int Vigor;
public static void main(String[] args) {
list = new ArrayList<String>();
vigoroustotal(list,Vigor);
public static void Listtotal(String par, int tt) {
for (String s : par) {
int i = Integer.parseInt(s);
tt += i;
}
}
Any changes you do to tt inside your method won't be visible anywhere else, because Java passes everything by value. Make the method return an int instead.
Your mistake her is passing the function tt and expecting it to be modified. Java doesn't modify parameters passed to functions. The corrected code would be this:
public static int ListTotal(List<String> par) {
int tt = 0;
for (String s : par) {
int i = Integer.parseInt(s);
tt += i;
}
return tt;
}
and would be used like this:
Vigor = ListTotal(list);
The changes that are made to the integer tt in the Listtotal() method will not be visible anywhere else but that method. You can make that method return an integer to solve that!
public static int Listtotal(ArrayList<String> par) {
int tt = 0;
for (String s : par) {
int i = Integer.parseInt(s);
tt += i;
}
return tt;
}
And then you need to change the main method:
public static void main(String[] args) {
list = new ArrayList<String>();
Vigor = Listtotal(list);
}
As, said, you need to return the total since java passes everything by-value, so the int tt you pass in won't hold a reference to the Vigor variable outside the method.
Therefore, when you pass in primitive types such as (int, char, boolean, byte etc.), anything you do to them inside a method won't be visible outside the method.
However, when you pass in a reference type (Objects such as ArrayList), it is still passed-by-value but that value is a copy of the reference to the Object outside the method. So, in the populateList method bellow, I can just call ArrayList.add() on the input because this input, even though it is passed-by-value, still points to the original Object that was put into this method.
public class Playing {
static ArrayList<String> list;
static int Vigor;
public static void main(String[] args) {
list = new ArrayList<String>();
populateList(list);
Vigor = getListTotal(list);
System.out.println("Total is:\t" + Vigor);
}
public static void populateList(ArrayList<String> list) {
String[] sampleData = { "4", "7", "2" };
for(int i = 0; i < sampleData.length; i++) {
list.add(sampleData[i]);
}
}
public static int getListTotal(ArrayList<String> list) {
int tt = 0;
for (String s : list) {
int i = Integer.parseInt(s);
tt += i;
}
return tt;
}
}
What you want is the... let's call it CountingList,
public class CountingList {
private List<Integer> integers = new ArrayList<Integer>();
private int sum;
public add(String s) {
int value = Integer.parseInt(s);
integers.add(value);
sum += value;
}
private void updateSum() {
sum = 0;
for (int i : integers) {
sum += i;
}
}
}
Obviously, you'll want to expose the functionality you need to use outside of the class, but this is (one) way of encapsulating the behavior you're needing.
I'm having an extremely difficult time getting a private method with arguments to be usable in my toString method but have no idea how to get the two methods to cooperate.
main class:
import static java.lang.System.*;
public class Triples
{
private int number;
public Triples()
{
//this(0);
}
public Triples(int num)
{
number = num;
}
public void setNum(int num)
{
number = num;
}
private int greatestCommonFactor(int a, int b, int c)
{
int max = number;
for(int n = 1; n <= max; n++)
{
for(a = n; a <= max; a++)
{
a = n;
for(b = a +1; b <= max; b++)
{
b =n;
for(c = b + 1; c <= max; c++)
{
c = n;
if(Math.pow(a, 2)+ Math.pow(b, 2)== Math.pow(c, 2))
{
if((a%2==1 && b%2==0)|| (a%2==0 && b%2==1))
{
if(a%2<=1 && b%2<=1 && c%2<=1)
{
String last = a + "" + b + c;
}
}
}
}
}
}
}
return 1;
}
public String toString()
{
String output="";
output = output + this.greatestCommonFactor( ) + " \n";
return output;
}
}
and for cross-referencing my runner class:
import static java.lang.System.*;
import java.util.Scanner;
public class Lab11j
{
public static void main(String args[])
{
Scanner keyboard = new Scanner(System.in);
String choice="";
do{
out.print("Enter the max number to use : ");
int big = keyboard.nextInt();
//instantiate a TriangleThree object
Triples triple = new Triples(big);
//call the toString method to print the triangle
out.println( triple );
System.out.print("Do you want to enter more data? ");
choice=keyboard.next();
}while(choice.equals("Y")||choice.equals("y"));
}
}
if you find you need clarification of this lab, here's a Google docs of the labsheet: https://docs.google.com/open?id=0B_ifaCiEZgtcX08tbW1jNThZZmM
The variables a, b & c can be used as local variables here. This would allow you to remove them from the argument list of greatestCommonFactor:
private int greatestCommonFactor() {
int a = 0;
int b = 0;
int c = 0;
...
as they are only required within the scope of the method.
Well, yeah. You're not passing anything to greatestCommonFactor. I'm not sure what you expected to happen in your toString() method when you didn't pass enough arguments to a method.
you need to pass them like
output = output + this.greatestCommonFactor(1,2,3) + " \n";
the thing is, unless you are passing parameters to toString, without this, this code seems very limited. Alternatively you need to set some fields on the class with what will be passed into your function.
I have a function that should work on int[] and on String[] now i have made the same function with a int parameter and an String parameter however if it has to go this way its a bit copy paste work and doesn't look very organized is there a way to solve this and put these 4 functions in 2?
static public void print(String s)
{
System.out.println(s);
}
static public void print(int s)
{
System.out.println(s);
}
static public void printArray(String[] s)
{
for (int i=0; i<s.length; i++)
print(s[i]);
}
static public void printArray(int[] s)
{
for (int i=0; i<s.length; i++)
print(s[i]);
}
Thanks
Matthy
With autoboxing / autounboxing, you can do this:
public static void print(Object s) {
System.out.println(s.toString());
}
public static <T> void printArray(T[] arr) {
for (T t : arr) {
print(t);
}
}
The one drawback is that the argument to printArray must be an array of a reference type, but unlike the varargs solution this will work for any reference type.
Edit: regarding the varargs solution and #matthy's question about combining the two methods into one (ie generifying it), you could also do something like this:
static public <T> void print(T... ts) {
for (T t : ts) {
System.out.print(t + " ");
}
System.out.println("");
}
However, you still cannot call it on an array of primitives:
int[] x = { 1, 2 };
print(x);
Because Java takes T to be int[] and will execute the toString method of the array rather than iterate through the contents. If you call it on an array of Integer or other reference type then it will work also.
static public void print(String...strings){
for(String str : strings){
System.out.println(str);
}
}
static public void print(int...ints){
for(int i : ints){
System.out.println(i);
}
}
Well, the Basic class java.lang.Object matches String as well as int, byte, ... (Autoboxing converts them to Integer, Byte and so on). The method String.valueOf() lets you create a string of these. (toString() is available too)
Use Generics, if applicable to your code:
static <T> void printArray(T[] s)
{
for (int i=0; i<s.length; i++)
System.out.println(s[i]);
}
Combining the previous answers yield:
public class Test {
static <T> void print(T... ts) {
for (T t : ts)
System.out.println(t);
}
public static void main(String... args) {
String[] strArr = { "one", "two" };
Integer[] intArr = { 3, 4 };
String str = "five";
int i = 6;
print(strArr);
print(intArr);
print(str);
print(i);
}
}
Output:
one
two
3
4
five
6
class MyClass {
public static void main(String[ ] args) {
String name ="David";
int age = 42;
double score =15.9;
char group = 'Z';
System.out.println(group + "\n" + name + " \n" + age + " \n" + score);
}
}