Hi i am trying to do the addition with the help of "varags" and" enhanced for loop".But i am getting this marker "This method must return a result of type int".
class Hello1 {
int pluss(int...v){
int plus=0;
for(int x :v){
plus=plus+x;
System.out.println(plus);
return plus;
}
}}
public class Addition{
public static void main(String args[]) {
Hello1 h1=new Hello1();
h1.pluss(3,7,9,10);
}}
You are re-declaring plus every loop, which is useless. Declare it before the loop and accumulate the total. Consider also returning it:
static int pluss(int...v){
int plus=0;
for(int x :v){
plus += x;
}
System.out.println(plus);
return plus;
}
Also note how the method can be static, because it doesn't use any instance fields.
Hello1 hl=new Hello1();
h1.pluss(3,7,9,10);
Just a typo, use better fonts...
h1 versus hl.
Related
I have an algorithm in my textbook written in pseudocode which is then supposed to be "implemented to a Java method". It goes like this:
read min;
while not eoln do
read x
if x < min then
min <- x
end if
end while
print min;
Then I'm given this code:
import java.util.Scanner;
int min() {
Scanner input = new Scanner(System.in);
System.out.println("x=? (999 to end)");
int x = input.nextInt();
int min = x;
while (x!=999) {
System.out.println("x=? (999 to end)");
x = input.nextInt();
if (x < min) {
min = x;
}
}
return min;
}
I put everything below import.Scanner inside of the main method and inside of a class like this:
public class MyAlgorithm {
public static void main(String[] args) {
// code here
}
}
But then I get this error message in Terminal:
MyAlgorithm.java:7: error: ';' expected
int min() {
^
1 error
Am I missing something? If I put the semicolon there, the whole thing just won't work.
It seems like you put your min method inside of main, this is defining methods from within other methods which will not work properly and cannot compile. The main method is the commands you want to run as soon as you start your program, any other functions in the class should be declared outside of it, and if you want them to run in main you do a method call.
it should look something like this:
import java.util.Scanner;
public class MyAlgorithm {
int min() {
//(min code)
}
public static void main(String[] args) {
// code here
//corrected according to Uli's comment
MyAlgorithm m = new MyAlgorithm();
int result = m.min();
}
}
I suggest reading up on how java programs are structured. Here's an article on methods.
Don't put your method min() inside the main() method. In Java, you can not define a method inside a method. In Java, you need an object to call its methods (Except you make the methods static). So your final Code looks something like this.
import java.util.Scanner;
public class MyAlgorithm {
public static void main(String[] args) {
MyAlgorithm m = new MyAlgorithm ();
m.min();
}
int min(){
//Your min code goes here
return min_value;
// min_value is the same as your min variable. It has another name to
// prevent name collisions
}
}
If you are allowed to use static methods, (which I don't think) you can use the following alternative:
static int min(){
//Your min code goes here
return min_value;
// min_value is the same as your min variable. It has another name to
// prevent name collisions
}
public static void main(String[] args) {
int result = MyAlgorithm.min();
}
Ok so in my cs class we have an assignment that requires us to return a value and then set it to zero. I can't figure out how to do this without using a secondary variable(which would break requirements) so I would appreciate some help. here are the exact requirements.
"Has a use() method that returns the value contained in the points field. It also resets the points field to zero. You’re going to have to think about the order of operations here to make this work correctly."
package Game;
import java.util.Random;
public class HealthPotion
{
private int points;
boolean Haspotion;
HealthPotion()
{
Random num1 = new Random();
int num = num1.nextInt(10)+1;
points=num*10;
}
public int Use()
{
return points;
}
public int getPoints()
{
return points;
}
}
That's not really possible without abusing a finally block, i.e.
try {
return points;
} finally {
points = 0;
}
However it's really hard to believe that would be what's wanted, since it's not a good idea to write code like that.
Include a setter method like this.
public void setValue(){
this.points=0;
}
Call this method after you get the value.
How about this?
public int Use()
{
int tmp = points;
points = 0;
return tmp;
}
It has limitations, especially if points can be changed by a different thread while this method executes. But if you are working in a single-threaded environment this should be ok.
This should work
int points = 5;
public void test(){
System.out.println(use() +" " + points);
}
private int use(){
return points - (points = 0);
}
returning 5 0
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));
}
}
Im new with programming and have been trying to solve this problem for a while, been looking at similar questions but im not understanding whats wrong with my code.
So the assignment is to write a method that takes an array that has three doubles in it. Then return the average of the three doubles. Then write a main that should call and then type the method.
Thanks!
Main
public class Tenta131031upg1main {
public static void main (String[]args){
double []arr ={3.15, 4.41, 7.64};
Tenta131031upg1.genomsnitt(double arr[]);
System.out.println(Tenta131031upg1.genomsnitt(arr));
}
}
Class
public class Tenta131031upg1 {
static int i =0;
static double sammanlagd=0;
static double genomsnitt=0;
public static double genomsnitt(double[]arr){
while(i<arr[].length()){
sammanlagd = sammanlagd + arr[i];
i++;
}
genomsnitt = sammanlagd/arr[].length();
return genomsnitt;
}
}
PS. they are two different classes with 1 main and 1 class they are not in the same file!
The error:
Syntax error on token "double", new expected
Variable must provide either dimension expressions or an array initializer
arr cannot be resolved to a type
at Tenta131031upg1main.main(Tenta131031upg1main.java:7)
Please correct the two lines in the first file like this:
double[] arr ={3.15, 4.41, 7.64};
Tenta131031upg1.genomsnitt(arr);
You were creating a new, empty array in the second line.
Try this:
Main
public class Tenta131031upg1main {
public static void main (String[]args){
double[] arr ={3.15, 4.41, 7.64};
System.out.println(Tenta131031upg1.genomsnitt(arr));
}
}
Class
public class Tenta131031upg1 {
static int i =0;
static double sammanlagd=0;
static double genomsnitt=0;
public static double genomsnitt(double[] arr){
while(i<arr.length){
sammanlagd = sammanlagd + arr[i];
i++;
}
genomsnitt = sammanlagd/arr.length;
return genomsnitt;
}
}
Changes are:
change in method call
arr.length instead of arr[].length()
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
}