public class ArrayPrac {
public static void main(String[] args) {
int[] arrayOne = {2, 3, 4, 5, 6};
System.out.println(findMin(arrayOne));
}
public static void findMin(int[] list) {
int minValue = list[0];
int i = 1;
for( i = 1; 1 < list.length; i++);
if(list[i] < minValue) {
minValue = list[i];
}
}
}
In the System.out.print part in line 6 it wont run and gives me the compiler error:
The method println(boolean) in the type PrintStream is not applicable for the arguments (void)
I seem to have searched for an answer all day, so now I post my specific case.
Cheers.
Fix this, at the end of your findMin() method you must return the minimum value that was found:
return minValue;
And consequently, the method signature must be changed, too:
public static int findMin(int[] list)
It makes sense: if the findMin() method does all that hard work to find the minimum value, the end result must not be left as a local variable, it won't be useful outside if you don't return it after the method invocation ends.
There's another hard-to-find bug lurking, by the way. Remove the ; at the end of the line with the for, and put the contents of the loop inside a pair of {}. Currently, the loop is empty, and the lines after the for lie outside the loop. And the loop condition is wrong, too! here's how the method should look after all the problems are fixed:
public static int findMin(int[] list) {
int minValue = list[0];
for (int i = 1; i < list.length; i++) {
if (list[i] < minValue) {
minValue = list[i];
}
}
return minValue;
}
System.out.println takes a String input but you are passing a void. As your method findMin returns void. This is causing the compiler error.
Now speaking about the logical problem, you may want to display the output of findMin method but the method does not return anything. So returning minValue may make sense here.
Once you return the int value from minValue method then you can display the result by concatenating it to a an empty string. Something like this:
System.out.println("" + findMin(arrayOne));
The method findMin() is declared as returning type void: Either declare it to return something (and return something),
public static int findMin(int[] list) {
int minValue = list[0];
int i = 1;
for( i = 1; 1 < list.length; i++)
if(list[i] < minValue) {
minValue = list[i];
}
return minValue;
}
Note fixing bug: removing semicolon from after for()
Related
I've created a method to count the number of occurrences in an array, but I can't compile and run it.
Compiler gives the error:
The method occurence(int[]) in the type countOfOccurence is not applicable for the arguments (int)
public class countOfOccurence {
public static void main(String[] args) {
int[] number = {15,16,14};
System.out.print(occurence(number[15]));
}
public static int occurence(int[] number) {
int count = 0;
for(int i = 0 ; i < number.length; i++) {
for(int k = 0 ; i < number.length; i++) {
if(number[k] == number[i]) {
count++;
}
}
}
return count;
}
}
Your occurrence method is expecting an array, but you are just passing an int to it (the 15th element from your array, which will also cause a runtime error as there are only 3 elements in your array).
But I also think your logic is off here, your current method (given that it would compile) will count all occurrences of all duplicate numbers in your array, not just the number you would want.
First off all, your occurrence method would need 2 arguments, the actual array and the number you want to count the occurrences of. You don't need an inner loop, just keep your outer loop and check inside whether the array element equals your desired number.
public static void main(String[] args) {
int[] number = {15,16,14};
System.out.print(occurence(number, 15));
}
public static int occurence(int[] numberArray, int number) {
int count = 0;
for(int i = 0 ; i < numberArray.length; i++) {
if(numberArray[i] == number) {
count++;
}
}
return count;
}
Of course there are better / cleaner ways to count occurrences of elements in an array, for example using the Streams api, if you would want to optimize.
occurence(int[] number) function accepts the integer array parameter. And, you are calling the function with occurence(number[15]). By number[15], it means 15th-index position from number array, which is also not valid in your code.
For your scenario to work, occurence function should be changed to accept two parameters like public static int occurence(int[] numbers, int number). And, call it by occurence(number, 15).
I want to calculate the factorial of a number with a get method (I must solve a bigger problem). Here's what I tried and it returns 1:
public Sigma() {
n = -1;
}
public Sigma(int n) {
n = n;
}
private int Facto(int n) {
for (int i = 1; i <= n; i++) {
result = result * i;
}
return result;
}
public int getFacto() {
return Facto(n);
}
The problem is that, in your constructor, you type n = n rather than this.n = n. The problem with this is that the local variable inside the constructor is assigned, rather than your class's field. this.n refers to the field n and is what you want.
You are receiving an output of 1 because the default value of all primitive number fields is 0. Using your code, 0! = 1 (which is correct), so that's your output no matter what you pass into the constructor, as the constructor ignores its parameter.
On an unrelated note, please use camelCase rather than UpperCase for method names (and field names). UpperCase should only be used for classes/interfaces/enums/annotations. Also, result = result * n may be simplified to the (almost) equivalent statement result *= n.
For the factorial you need to initialize result in the facto function, like this
private int Facto(int n)
{
int result = 1;
for (int i = 1; i <= n; i++)
{
result = result * i;
}
return result;
}
Every source I've looked at I either don't understand, doesn't seem to apply, or uses something like an Array list. I'm not familiar with those. So I'd like to use a basic toString method that prints out the index of the array as well as the number held when compared to the variable 'length' -- num.length could be different as that's the physical size of the underlying array. The for loop at the bottom has the gist of it. I'm trying to print out the index (0-infinite) with int's that are held in the resizeable array. The variable 'length' is not the actual size of the array but a working size that contains 0 until another cell is added. The 'strang' variable is just something I've tried. I don't think it will work, but anything else I doesn't seem to help as I'm stuck.
public class XArray
{
private int[] nums;
private int length;
public XArray()
{
nums = new int[10];
length = 0;
}
public void add(int value)
{
if (length == nums.length)
{
int[] nums2 = new int[(int)(nums.length * 1.2)];
for ( int i = length - 1; i >= 0; i-- )
{
nums2[i] = nums[i];
}
nums = nums2;
}
nums[length] = value;
length++;
}
public void set(int index, int value)
{
if (index < length)
{
nums[index] = value;
}
}
public int get(int index)
{
return nums[index];
}
public int size()
{
return length;
}
public void remove()
{
nums[length - 1] = 0;
length--;
}
public String toString(int[] nums)
{
String strang = "l";
for ( int i = 0 ; i < length; i++ )
{
strang = "Index: " + i + " Number: " + nums[i] + ", ";
}
return strang;
}
}
You need to concatenate the values on each iteration of the loop...something like...
public String toString(int[] nums)
{
StringBuilder strang = new StringBuilder(length);
for ( int i = 0 ; i < length; i++ )
{
strang.append("Index: ").append(i).append(" Number: ").append(nums[i]).append(", ");
}
return strang.toString();
}
Generally speaking, toString should't take parameters, there would a difference between nums and length which could cause issues
#Override
public String toString() {...
This way, you will be printing the contents of the objects num array, which is contextually associated with length
You probably meant to use += instead of = in that method (though many people will tell you to use a StringBuilder because successive concatenations, if not optimized by a compiler` will generate a lot of garbage).
Also, don't pass in nums! You want to use the field nums; passing in an argument will use the argument. The real toString has no parameters (and should have an #Override annotation).
First off, my program is not compiling. Any ideas? I have no idea why and my Eclipse program isn't working...
Also, how do I get my "isLucky" method to loop through my array?
And did I print out my results correctly in the main method?
import java.util.Scanner;
public class FunArrays {
public static void main(String[] args) {
luckyNumber1 = 7;
luckyNumber2 = 13;
luckyNumber3 = 18;
int[] a=new int[10];
Scanner sc=new Scanner(System.in);
System.out.println("Please enter numbers...");
for(int j = 0; j < a.length; j++)
a[j] = sc.nextInt();
boolean b = isLucky(a);
int result;
if(b)
result = sum(a);
System.out.println(sum(a))
else
result = sumOfEvens(a);
System.out.println(sumOfEvens(a))
}
public static int sum(int [ ] value)
{
int i, total = 0;
for(i=0; i<10; i++)
{
total = total + value[ i ];
}
return (total);
}
static int sumOfEvens(int array[])
{
int sum = 0;
for(int i = 0; i < array.length; i++) {
if(array[i] % 2 == 0)
sum += array[i];
}
return sum;
}
public static boolean isLucky (int[] array)
{
if ( array[i] == 7 || array[i] == 13 || array[i] == 18 )
return true;
else
return false;
}
// write the static methods isLucky, sum, and sumOfEvens
}
Your compiler error, 'else' without 'if' is because you have something like this:
if(isOkay)
doSomething();
andThenDoSomethingElse();
else
doAnotherThing();
andEvenSomethingElse();
And you must put each block in curly braces, like this:
if(isOkay) {
doSomething();
andThenDoSomethingElse();
} else {
doAnotherThing();
andEvenSomethingElse();
}
I strongly recommend using curly braces in all ifs (and whiles and fors and everything else), even when there's only a single statement.
More information can be found at this question: Else without if
Honestly there is no regulation that says we have to use code blocks. Syntax typically says that after we read the if we are looking for only one statement if your condition contains multiple statements then we do have to block that code up, another thing is try to keep that indentation whenever you enter methods conditions and then statements. Id love to write the easy route to get the output you desire. Think about this why are you sending these methods arrays? What is stopping you from simply looping in your main method and passing each iteration to these methods sum lucky, even...Your variables should usually be initialized at top or at the beginning of a method to have those around the life of a methods execution.Below is clearly not compile ready code, however this will edge you in the right place to understand this problem more than use brackets.
boolean isLucky;
int[] IntegerArray;
Scanner scan;
//Final for constant values Typically these would be in all uppercase to indicate to
//other that this is a final anywhere
//in this class those will stick out.
final int luckyOne = 7;
final int luckyTwo = 13;
final int luckyThree = 18;
for(int i=0;i<IntegerArray.length;i++){
//snag me Boolean value for this number
isLucky();
if(isLucky)//example of completely legal if statement adding a system.out statement
//means yes i have to block this
sum(i);
else
even(i);
}
public class negativeTest {
public static int Negativenum (int[] array) {
int negative = 0;
for (int i = 0; i < array.length; i++){
if(array[i] < 0){
negative = negative + 1;
}
System.out.println(negative);
}
}
}
I am trying to count how many elements in array are negative. This is what i have so far. My question is: eclipse is telling me that i should return a void instead of static int? How can i do this without using void?
I'd want to use
public static int negativenum(int[] array){
Only way i can get this working is create an array with positive and negative numbers and count them, but i want to be able to have method that does that without creating array of numbers. Can you help me?
Try giving a return statement , your method is expecting a int as a return parameter.
Therefore it will give compiler error.
public class negativeTest {
public static int Negativenum (int[] array) {
int negative = 0;
for (int i = 0; i < array.length; i++){
if(array[i] < 0){
negative = negative + 1;
}
System.out.println(negative);
}
return negative;
}
}
Ther error you are getting is because you have not declared the main function inside the class.
You have to call Negativenum from the main function.
you can do it like this :
public static void main (String args[])
{
negativeTest nt = new negativeTest();
int [] array = new int[]{ 100,200 };
int count = nt.Negativenum(array);
System.out.println(count); // It will print **2**
}
Regarding your doubts you have asked in comments.
You have to return anything from function only when you want to use that use that return value from the calling function.
Otherwise if you want to just print that value on console or log that value , you can easily do it in the negativeTest function and you can change the return type of this function to void.
FYI , you should not begin your classname with the lower case character.
The error is because you are not returning anything from the function which is expected to return an int.
If you want the function to count the number of negative numbers and return the count so that the caller of the function gets the count, you can add an
return negative;
before the end of the function.
Alternatively if you don't want to return anything from the function and want to just print the count as part of the function call, you can change the return type of the function from int to void:
public static void Negativenum (int[] array) {
Your function signature suggest a return type of int, but you aren't returning anything from the function. I suspect this is why Eclipse is suggesting you change the function signature to return void.
If you add return negative; it should avoid the notice from Eclipse.
If your intention is to simply print the count, then you should change the return type.
if you dont want to return anything, set your method signature to void, but add an out variable, like so:
public static void NegativeNum(int[] array, out int negative)
{
negative = 0;
foreach(int i in array) { if (i < 0) negative++;
}
then you just declare negative wherever this method is called from, and pass it in as an out variable:
int negative = 0;
NegativeNum(array, out negative);
After that call, negative will contain the count of negative numbers determined by the method.