I found the solution to this problem but can't figure out how it works. Can someone please explain this?
public static void main(String[] args) {
Object[] numbers = new Object[100];
Arrays.fill(numbers, new Object() {
private int count = 0;
#Override
public String toString() {
return Integer.toString(++count);
}
});
System.out.println(Arrays.toString(numbers));
}
[I could not comment to that answer directly because I dont have enough reputation points.]
Can someone please explain this?
This code is a use of
Arrays.fill(Object[] a, Object val)
Where the Object val provided is an anonymous class with its toString() method overridden.
Arrays.toString(numbers) calls the toString() on the anonymous class for each element in the a array. As the toString() is overridden to increment the count, you get incremented values each time it is called.
However, as #Eran has pointed out, it is not without a loop.
To be accurate, Arrays.fill() use a loop in its own implementation.
In general, Arrays.fill fills an array by assigning the second parameter to every element of the first parameter (your array).
Your example has an Array of type Object and a length of 100 elements.
In Arrays.fill(...) you generate a so-called anonymous class of type Object, which reimplements the toString-method by increasing the value of a counter (int count) and printing it after that.
Now, by calling Arrays.toString the toString() method of every element inside the array is executed (which is the same instance of the anonymous class here), resulting in printing the numbers from 1-100
System.out.println(1)
System.out.println(2)
System.out.println(3)
System.out.println(4)
System.out.println(5)
System.out.println(6)
System.out.println(7)
...
System.out.println(100)
:D
To avoid the code-generator proposed by Dmitry, this can be easily done with just copy-paste
int i=0;
System.out.println(++i);
System.out.println(++i);
System.out.println(++i);
System.out.println(++i);
System.out.println(++i);
...
System.out.println(++i);
Write the System.out.println(++i) once.
Copy and paste 4 times.
Then you pick those 5 lines and copy paste them again.
You should now have 10 times that line. Select those 10 lines and copy paste another 9 times.
done!
Here is a better solution:
IntStream.rangeClosed(0, 100).forEach(System.out::println);
I think it's self explanatory
What about this:
public class NoLoopPrint {
int max;
int from;
public NoLoopPrint(int max) {
this(1, max);
}
public NoLoopPrint(int from, int max) {
this.max = max;
this.from = from;
}
public String toString() {
if (from >= max) {
return String.valueOf(max);
}
System.out.println(from++);
return this.toString();
}
public static void main(String args[]) {
System.out.println(new NoLoopPrint(100));
System.out.println(new NoLoopPrint(10, 20));
}
}
Related
I'm having trouble understanding what exactly the return statement does. What would be the difference in using:
public void run()
{
System.out.println(cube(5));
}
public int cube(int num)
{
int result = num*num*num;
System.out.println(result);
}
vs
public void run()
{
System.out.println(cube(5));
}
public int cube(int num)
{
return num*num*num;
}
Isn't it basically doing the same?
In your first example, the square function will print the cube of the provided number. However, if you wanted to do something more with it, like System.out.println(square(5) + 3), printing would not give you back 125 (did you mean to call it cube?) to add to the 3, it would only say "125" in the console. The return statement actually makes the function give back 125, so you can continue to work with it as a value.
Additionally, since you declared the square function as returning an int, if you do not have a return statement, then the program will fail to compile.
The return statement allows for more modular code with clear separation of concerns.
In your first example, your first System.out.println in the run() method calls another method that both calculates and then prints; therefore, the first System.out.println doesn't print anything itself, and could be simplified to just
public void run() {
square(5);
}
public void square(int num) {
System.out.println(num * num);
}
Which is nice and concise, but let's say you don't want to System.out.println every time you calculate a square, but only print if the result is divisible by 3. If you add the logic for that scenario to your square() method, it starts to exceed its responsibility. Additionally, your square() method is now only useful to that specific scenario. So the better practice would be something like this:
public void run() {
int result = square(5);
if (result % 3 == 0) {
System.out.println(result);
}
}
public int square(int num) {
return num * num;
}
Which now allows you to re-use the square() method for other scenarios, rather than just printing squares divisible by 3.
Unrelated to the code itself, but your square() method is actually calculating a cube (num*num*num) rather than a square (num*num)
The difference would be whether or not you want to do something with the product of the function. If you just want to print the result, you're good to go. If you want to store that value into a variable to use later, you'd want to return it, and you could then call a System.out.println on that variable too. I would say fin nailed it in his response. Hope this helped!
I'm looking for an elegant way to express this pseudo code. For my assignment, I cannot change the method signature or parameter type.
private static int smallest(int... nums)
{
return Arrays.stream(nums).min().getAsInt();
}
All I'm trying to do is take a huge varying list of ints as a parameter from the method call and return the smallest int of all the int parameters. I've tried to google and read the API to find out how to correctly implement this, but I've gotten only this far. Can someone help me syntactically correct this to compile and output correctly?
I cannot correctly post my console errors with formatting, so I'm posting it as an update to my OP. To answer #Marvin I'm getting this error in my compiler...
Methods1.java:25: error: cannot find symbol
int small = Arrays.stream(nums).min().getAsInt();
^
symbol: variable Arrays
location: class Methods1
1 error
You almost had it, it's getAsInt() instead of get():
private static int smallest(int... nums) {
return Arrays.stream(nums).min().getAsInt();
}
Complete working sample on ideone.com:
import java.util.Arrays;
class Ideone {
public static void main (String[] args) {
int[] nums = new int[] { 7, -2, 5, 12 };
System.out.println(smallest(nums));
}
private static int smallest(int... nums) {
return Arrays.stream(nums).min().getAsInt();
}
}
Prints:
-2
You could iterate over the whole array like this
private static int smallest(int[] array)
{
//check if the array is empty
if(array.length == 0)
{
//handle, whatever happens if the array is empty
return -1; //maybe you should throw an exception here
}
//storing the smallest found value, start with the first int in the array
int smallest = array[0];
//the iteration
for(int i : array)
{
//check if the current checked value is smaller than the smallest found...
if(i < smallest)
{
//...and if it is, set it as the smallest found value
smallest = i;
}
}
//finally, return the smallest value
return smallest;
}
This should solve your current problem, but in most cases i'd rather recommend to use a pre sorted array or list instead. If the data in it is already stored in ascending order, the first element would always be the lowest and the last element always the highest value.
This method takes an infinite unknown variable quantity of parameters by using varargs as it's argument. Combining all the parameters added from it's call from main into an array of the same type. This was designed to account for mutability of the original method call in main. Finally, returning the smallest integer of all the parameters.
I'm a fairly new programmer, second year into computer science, and I'm not sure if this is even useful for anyone, but I hope it helps. Thanks to everyone here for your awesome tips and error catches. My issue was I forgot to import my Array class and one of my method calls from stream class was incorrectly named.
Lastly, for any veteran programmers out there, aside from this looking snappy and elegant, does this statement execute any faster than doing a simple foreach loop and comparing the num to the last smallest one?
import java.util.Arrays;
public class Test
{
public static void main(String[] args)
{
// Enter as many as you want here, can be more or less than three
int num1 = 23;
int num2 = 89;
int num3 = 9;
// Apply each variable as an argument for the method call
int smallestNumber = smallest(num1, num2, num3);
// Print out variable value to prove it works
System.out.print(smallestNumber);
}
private static Integer smallest(int... nums)
{
// Found an elegant way to do the stubbed out block of code
// I left the code down there to show what is going on here
try
{
return Arrays.stream(nums).min().getAsInt();
}
catch (Exception e)
{
return null;
}
// The above code is essentially doing the below code
/*try
{
// Initialize Variable to start of array
int smallest = nums[0];
// For:Each Loop: go through each parameter and assign it a local variable to compare with
for(int i : nums)
{
// compare if smaller
if(i < smallest)
{
// If true, set as smallest
smallest = i;
}
}
return smallest;
}
catch (Exception e)
{
return null;
}*/
}
}
I'll preface my question with the statement that I am very new to Java, so I apologise if my code is totally disgusting to read.
What I'm trying to do: I'm writing a program that takes two integers from the user, a low value and a high value, and sends both integers to two different methods. Method #1 has a simple for loop and should print out all of the numbers between the lowest number and the highest number that are multiples of 3 or 5, and Method #2 does the same except for numbers that are multiples of 3 or 5 it also checks if that number is also a multiple of 6 and, if so, it prints the number and an asterisk next to it.
What I'm having trouble with: I'm pretty stumped on what I need to return from my methods & how to return anything at all. This is the first time I've worked on a method properly (just moved up from "Hello World) and from what I can see I don't really need to return anything at all. All the code that I've put in my methods pretty much complete the program, so I thought maybe returning the integers I sent would be enough, apparently it's not. So, without further ado, here's my code.
The Error:
javac BonusQ.java
.\MethodOne.java:19: error: illegal start of type
return(int lowestRange, int highestRange);
^
.\MethodTwo.java:36: error: illegal start of type
return(int lowestRange, int highestRange);
^
The Main:
import java.util.Scanner;
public class BonusQ
{
public static void main(String [] args)
{
Scanner scan = new Scanner(System.in);
int lowestRange = 0;
int highestRange = 0;
System.out.println("Enter the lowest integer in your range");
lowestRange = scan.nextInt();
System.out.println("Enter the highest integer in your range");
highestRange = scan.nextInt();
MethodOne.NoAsterisk(lowestRange, highestRange);
MethodTwo.Asterisk(lowestRange, highestRange);
}
}
MethodOne:
public class MethodOne
{
public static int NoAsterisk(int lowestRange, int highestRange)
{
for(int i = lowestRange; i <= highestRange; i++)
{
if (i%5 == 0)
{
System.out.println(i);
}
else if (i%3 == 0)
{
System.out.println(i);
}
}
}
return(int lowestRange, int highestRange);
}
MethodTwo:
public class MethodTwo
{
public static int Asterisk(int lowestRange, int highestRange)
{
for(int i = lowestRange; i <= highestRange; i++)
{
if (i%5 == 0)
{
if (i%5 == 0 && i%6 == 0)
{
System.out.println(i + "*");
}
else
{
System.out.println(i);
}
}
else if (i%3 == 0)
{
if (i%3 == 0 && i%6 == 0)
{
System.out.println(i + "*");
}
else
{
System.out.println(i);
}
}
}
}
return(int lowestRange, int highestRange);
}
Sorry if the post is a bit beefy to read, I just find that adding my thoughts on the code might help you explain to me what's going wrong, seeing as you may not know the extent of my incompetence :)
Thanks in advance.
Ok, Classes have members.
Members are either some variables or arrays of variables
and the methods of a class.
So you got
public class MyMethod
{
public static int Asterisk(int loRange, int hiRange)
{
// Do magic let's make a sum for this example
// You enter loRange and hiRange (you defined it above)
return loRange + hiRange // Here the method returns a result
}
}
// So then....
public static void main(String [] args)
{
// WHATEVER IS IN HERE RUNS ALWAYS FIRST.
z = Asterisk(1,2); // 1 and 2 is lo and hi range values ;)
// Z has a value of 3 now because Asterisk(1,2) returns 1 + 2
}
See how this works?
Now this works because you use the static definition (meaning there must not be an instance of MyMethod created first to use the method. It's not wrong, but if you can make a program do things with class instances, you better do it that way.
You make an instance of a class, this is called an object, using a special method. This method has the exact name of the Class and constructs an instance of it.
You should study now about constructors, abstract classes etc etc.
I can't say you do it wrong or right either. It is about what the program is all about and you should study the scope for variables and methods, and the encapsulation concept of Object Oriented Programming.
Using only static methods, goes against encapsulation principle, it is possibly wrong but I can't tell for sure.
I hope this helped you and gave you a good direction to go on with your study.
PS:
To return multiple results, you should return an array of variables, not just a variable.
You can also return nothing and just have it do the job to a needed array. This FORCES you though to make this array public. (Not a good practice)
Finally if multiple value returns are needed to just print them on the console... well, just do it in the method, no need to return anything really.
You don't need to return anything, being that the methods are printing out all the values.
You can change them into void methods, for example:
public static void asterisk(int lowest, int highest) {
//loops and if statements
//no return statement!
}
The code in the methods will run and voila, you are done!
EDIT: That being said, there's a lot more than can be done to make this code more Java-like, but for now this will work.
mmmmm...you can return types, and (int lowestRange, int highestRange) its not a type. Look at the method definition
public static int Asterisk(int lowestRange, int highestRange)
the return type is declared as int, so you should return an int value. You can do something like
return lowestRange;
return 1;
with that in consideration, the error should dissapear. The question is, why do you need to return a value? From what i've read, your methods are supose to print stuff, not to return stuff...
The return statements are out of the method. You have to put them before the close method brackets.
public class MyClass{
public int sum (int a, int b){
return a + b;
} // The return have to be before this brackets
}
Okay I have tried to write a simple Java code in BlueJ, that finds and prints the product of all the entries in data such as if data is {1,2,3,4} then the result will be 24.
And my code is below:
public class Product {
public static int[] product(int[] a) {
int [] s = new int[a.length];
for (int i =0; i< a.length; i++)
s[i] = a[i]*a[i];
return s; //the definition of your method...
}
public static void main(String[] args) {
//calling the method to seek if compiles
int[] results = Product.product(new int[] { 1,2,3,4 });
//printing the results
System.out.println(java.util.Arrays.toString(results));
}
}
The above code is giving me the square of each number, which is not what I want to have, somehow I have modify the code that the result will be 24 but I couldn't figure it out, anyone knows how to do it?
First of all, if you are first writing Java it is important to know that variable, function and class names are quite important. Please note that having Product.product() is not a good idea, since the function name is almost the same as the class name. Anyway, regarding your code. Your code is indeed returning the square of your input, what you would want is the following:
public class Product {
public static int getProduct(int[] input) {
int total = 1;
for (int v : input) {
total *= v;
}
return total;
}
}
This will return an integer value with the product of your input array. This also uses a for-each loop instead of a regular for-loop for readability. Also you don't need the index in this case. Good luck with it!
First, your product method needs to return an int rather than an int [].
You need to maintain the product as a variable. You can set it to 1 initially, and then multiply it by each element of the a array in turn; then you just return this value.
My professor gave me a code for the methods to be used in sorting an array of names lexicographically, but I have no idea how what to write inside the main class to show that the program works. I am very new to java, so please if you know how to do this could you write it as simple as possible for me to understand it. Thanks in advance.
This is are the classes
public class quicksort_class {
int[] array1 = new int[11];
public quicksort_class(int[] w)
{
array1 = w;
}
private static void sort(String[] string, int leftlimit, int rightlimit) {
if (rightlimit > leftlimit)
{
int midpoint = partitionstep(string, leftlimit, rightlimit);
sort(string, leftlimit, midpoint - 1);
sort(string, midpoint, rightlimit);
}
}
public static int partitionstep(String[] string, int leftlimit, int rightlimit)
{
String midpoint = string[rightlimit];
int lpointer = leftlimit;
int rpointer = rightlimit;
String temp = "";
while(string[lpointer].compareTo(midpoint) <= 0)
{
lpointer = lpointer ++;
}
while(string[rpointer].compareTo(midpoint) > 0)
{
rpointer = rpointer --;
}
if(lpointer > rpointer)
{
temp = string[lpointer];
string[lpointer] = string[rightlimit];
string[rpointer] = temp;
System.out.println(string);
}
while(lpointer < rpointer)
{
temp = string[lpointer];
string[lpointer] = string[rightlimit];
string[rightlimit] = temp;
}
return lpointer;
}
}
This is the main class (as you can see I have no idea what to write)
package quicksort;
public class Quicksort {
public static void main(String[] args) {
}
}
Write something that sets up an array of strings and calls sort against it, then prints out the results or checks them against a known good result.
Ideally, write something which does this repeatedly, with particular emphasis on checking unusual combinations (already sorted or sorted in reverse, null in the array, same value appearing several times or all values being identical...)
If you want to go beyond that, you need to dig into the code to understand its edge cases and specifically test those, and/or do a "code coverage" analysis (there are tools to help with that) to make sure all parts of the code have been exercised.
Assume the algorithm of sort method is correct:
1. If the main method is within the body of quicksort_class, you can directly call the sort method as sort(arrayToBeSorted, 0 , arrayToBeSorted.length-1). And the arrayToBeSorted should ordered lexicographically after your call. You can check that to confirm.
2. If the main method is in other class, as your main method currently, you need to at least change the private prefix of sort method to public, and call quicksort_class.sort(arrayToBeSorted, 0 , arrayToBeSorted.length-1).
Some tips:
1. Private prefix of method definition means this method can only be called inside current class body.
2. Static prefix of method definition means you should call this method via class name directly, instead of via a instance of class.
By the way, can you provide what the array1 attribute stands for? I don't get why it's there.