Java return (value) error - java

I tried different things in my code, but I always get errors.
The instructions for the program is that I need to have a function (besides from main) that receives arguments for an array of integer values and a second argument telling the desire value to look in the array by the user.
It must also return how many times the desire value is repeated on the array.
The errors are related to the counter and also some are in the main function.
I think I am not returning the counter value correctly.
This is my current code:
import java.util.Scanner;
import java.util.Arrays;
public class ArregloBusqueda2
{
static int findRepetition(int listOfValues[], int targetValue, int counter)
{
int i;
boolean found = false;
for(i=0; i<listOfValues.length; i++)
{
while((counter < listOfValues.length))
{
if(listOfValues[i] == targetValue)
{
counter = counter + 1;
}
}
}
return counter;
}
public static int main(String[] args)
{
Scanner input = new Scanner (System.in);
int targetValue;
int listOfValues[] = {1,6,3,8,5,8,3,4,8,3};
System.out.println("Please enter the desire number to look for: ");
targetValue=input.nextInt();
findRepetition(targetValue, counter);
if(counter != 0)
{
System.out.println("The frequency of the number " + targetValue + " is: " + counter);
}
else
{
System.out.println ("The number " + targetValue + " is not contained in the array list");
}
}
}

Multiple issues in your code.
public static int main(String[] args) should be public static
void main(String[] args)
findRepetition takes three arguments,
but you are passing two agruments
counter variable is not declared
Logical flaw, while((counter < listOfValues.length)) will keep on executing if counter value is less than listOfValues.
static int findRepetition(int listOfValues[], int targetValue) {
int i;
int counter = 0;
for (i = 0; i < listOfValues.length; i++) {
if (listOfValues[i] == targetValue) {
counter = counter + 1;
}
}
return counter;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int targetValue;
int listOfValues[] = { 1, 6, 3, 8, 5, 8, 3, 4, 8, 3 };
System.out.println("Please enter the desire number to look for: ");
targetValue = input.nextInt();
int counter = findRepetition(listOfValues, targetValue);
if (counter != 0) {
System.out.println("The frequency of the number " + targetValue + " is: " + counter);
} else {
System.out.println("The number " + targetValue + " is not contained in the array list");
}
}

You made your method accept three parameters.
static int findRepetition(int listOfValues[], int targetValue, int counter)
Ask yourself - do you want to "pass in a counter", or only return it? The instructions say the latter.
When you call this method, you are not providing the correct inputs.
findRepetition(targetValue, counter);
What about the listOfValues? You want to findReptition on listOfValues for targetValue, right? So provide the correct parameters into that method call.
Again, you likely do not need the counter passed-in. Because Java is always pass-by-value
Rather, you want to return counter, as you have written. You are looking for this.
int counter = findRepetition(listOfValues, targetValue);
Fixing the remainder of the code is a learning exercise.

You are not calling findRepetition() with required parameters, findRepetition method takes 3 arguments, but you are passing only 2 arguments.

Related

How do I display all multiples of the starting value for as many multiples as the 2nd parameter states?

I am having trouble getting the right output. I am trying to get my program to do the following: display all multiples of the starting value for as many multiples as the 2nd parameter states.
I don't understand why I am not getting the correct answers when I compile the program. Can someone explain what I did wrong and how to correct?
import java.util.Scanner;
public class Proj3
{
public static void main(String[] args)
{
int iNumMultiples; //holds input by user
int iStartingValue; //holds input by user
int iVal; //holds the multiples
System.out.print("\nEnter integer for multiples and the number of multiples: ");
iStartingValue = kb.nextInt();
iNumMultiples = kb.nextInt();
System.out.print("\nThe first " + iNumMultiples + " multiples of " + iStartingValue + " are: " + iVal);
}
}
public class MyMath
{
//+displayMultiples(startingValue:int, numMultiples:int):void
public static void displayMultiples(int startingValue, int numMultiples)
{
int Val = 0;
for (int i=0; i<=numMultiples; i++)
{
Val += startingValue;
System.out.print("\n" + Val);
}
}
}
Not sure what kb is, you haven't defined it. You actually have to call your displayMultiples method. Not sure why you are breaking this into multiple classes.
public class MyProj {
public static void main(String[] args)
{
int iNumMultiples; //holds input by user
int iStartingValue; //holds input by user
int iVal; //holds the multiples
//System.out.println("Enter integer for multiples and the number of multiples: ");
iStartingValue = 5;
iNumMultiples = 5;
System.out.println("The first " + iNumMultiples + " multiples of " + iStartingValue);
displayMultiples(iStartingValue, iNumMultiples);
}
//+displayMultiples(startingValue:int, numMultiples:int):void
public static void displayMultiples(int startingValue, int numMultiples)
{
int val = 0;
for (int i=0; i<=numMultiples; i++)
{
val += startingValue;
System.out.println(val);
}
}
}

Counting occurrences of integers in an array program java

I am trying to find the occurrences of all integers submitted by the user into the program and so far here's what I got. It works but I don't think it's a legit way to do it, is there any way I can try to do this without using the list[10]=9999;? Because if I don't do it, it'll show out of boundary error.
import java.util.*;
public class OccurrencesCount
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int[] list = new int[11];
//Accepting input.
System.out.print("Enter 10 integers between 1 and 100: ");
for(int i = 0;i<10;i++){
list[i] = scan.nextInt();
list[10] = 9999;
}
//Sort out the array.
Arrays.sort(list);
int count = 1;
for(int i = 1;i<11;i++){
if(list[i-1]==list[i]){
count++;
}
else{
if(count<=1){
System.out.println(list[i-1] + " occurs 1 time.");
}
else{
System.out.println(list[i-1] + " occurrs " + count + " times.");
count = 1;
}
}
}
}
}
Personally, I think this is a perfectly good solution. It means that you can deal with the last group in the same way as all others. The only change I would make is putting the line list[10] = 9999; outside the for loop (there's no reason to do it 10 times).
However, if you want to use an array of length 10, you can change the line
if(list[i-1]==list[i])
to
if(i < 10 && list[i-1]==list[i])
If you do this, you won't get an ArrayIndexOutOfBoundsException from list[i] because the expression after the && is not evaluated when i == 10.
import java.util.*;
class OccurrencesCount {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int[] list = new int[101];
System.out.print("Enter 10 integers between 1 and 100: ");
for(int i = 0;i<10;i++) {
int x = scan.nextInt();
list[x]++;
}
for(int i = 1; i <= 100; i++)
if(list[i] != 0)
System.out.println(i + " occurs " + list[i] + " times ");
}
}
To store count of numbers from 1 to 100 you need to use a list of 100 integers each one storing the number of occurrences of itself. Better approach would be to use a Map.
I have made use of ArrayList and Collections package instead of regular arrays as a different flavor if it interests you check it out.
import java.util.*;
public class OccurrencesCount {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
List<Integer> list = new ArrayList<>();
//Accepting input.
System.out.print("Enter 10 integers between 1 and 100: ");
for (int i = 0; i < 10; i++) {
list.add(scan.nextInt());
}
Collections.sort(list);
Integer prevNumber = null;
for (int number : list) {
if (prevNumber == null || prevNumber != number) {
int count = Collections.frequency(list, number);
System.out.println(number + " occurs " + count + (count > 1 ? " times." : " time."));
}
prevNumber = number;
}
}
}
I got it figured out guys, only changed a couple of small things inside the conditions and everything went smoothly! Thanks for the help! Now I just need to find a way to restrict the inputs from going above 100.
import java.util.*;
public class CountOccurrences
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int[] list = new int[10];
//Accepting input.
System.out.print("Enter 10 integers between 1 and 100: ");
for(int i = 0;i<=9;i++){
list[i] = scan.nextInt();
}
//Sort out the array.
Arrays.sort(list);
int count = 1;
for(int i = 1;i<=10;i++){
if(i<=9 && list[i-1]==list[i]){
count++;
}
else{
if(count<=1){
System.out.println(list[i-1] + " occurs 1 time.");
}
else{
System.out.println(list[i-1] + " occurrs " + count + " times.");
count = 1;
}
}
}
}
}

check if random number is equal to a specific number. java

Building a program that can check if a random number is = to a specific number. Here is what I have so far. I am generating a random number 10 times. And I want it to print out "The number (int var) was found (How ever many times it generated) times.". I keep running into problems such as trying to pull static variable from non-static variable. I'm not sure how to check if the integer is = to the random number.
import java.util.Random;
public class Driver{
public static void main(String[] args)
{
Loop.loop4(4);
}
public class Loop
{
public static void loop4(int val)
{
for(int iteration = 1; iteration <=10; iteration ++)
{
Random number = new Random();
number.nextInt(10);
}
System.out.println("The number " + val +" was found " (Dont know how to do this part);
}
}
You should try something like:
int count = 0;
for(int iteration = 1; iteration <=10; iteration ++) {
Random number = new Random();
int n = number.nextInt(10);
if(n == val) count++;
}
System.out.println("The number " + val +" was found " + count + " number of times");
Just compare val with the random number generated and see if they are equal in the if() {...}, keep a counter to keep track of how many times the random number was equal to val.
#thegauravmahawar 's answer seems decent and interesting.
Nonetheless, here's a suggestion on how to enhance your code:
(Don't mind if it's got any minor errors; I wrote it all on nano)
package loop;
import java.util.Random;
public class Loop {
public static void main(String[] args){
int number = 100, range = 100 // Type in any ints
if looper(number, range) { System.out.println("Number %i found!", number) }
else { System.out.println("Number not found!" ) }
}
public bool looper(int numberToBeFound, int range){
guard numberToBeFound<=range else { System.out.println("number to be found is
greater than range!") }
for (int i = 1; i<=range; i++) {
Random randomNumber = new Random();
randomNumber.nextInt(range)
if randomNumber == NumberToBeFound { break; return true } // Unsure if this'll work
}
return false
}
}

local Variable may not have been initialized and a loop

I have a program that originally took two numbers passed the values to a method and returned the higher number. I got that so I decided to expand to the program and want the program to ask the user for the 2 numbers. I have 2 problems that I can not figure out. The first is that it is saying that my variables i and j are not initialized. The second is that the program loops 3 times. can someone offer me any assistance. I am coming from c# Thanks.
package javabook;
import java.util.Scanner;
public class Chapter5 {
public static void main(String[] args)
{
int i;
int j;
int k = max(num1(i),num2(j));
//Scanner input = new Scanner(System.in);
num1(i);
num2(j);
System.out.print("The maximum between " + num1(i) + " and " + num2(j) + " is " +k);
}
//Return the max between two numbers
public static int max(int num1, int num2)
{
int result;
if (num1>num2)
result = num1;
else
result = num2;
return result;
}//End Max Method
public static int num1(int i)
{
Scanner input = new Scanner(System.in);
System.out.print("Please enter the first number: ");
input.nextInt();
input.close();
return i;
}//End num1 method
public static int num2(int j)
{
Scanner input = new Scanner(System.in);
System.out.print("Please enter the second number: ");
input.nextInt();
input.close();
return j;
}//end num2 method
}
Local variable don't have same values as globally declared variable's thus you have to assign some value to use them. Global variable int has value 0 by default.
int i = 0;
int j = 0;
or
this.i = 0;
this.j = 0;
here:
int i;
int j; <---creates the var, but doesn't initialize it
int k = max(num1(i),num2(j));
^---using the var, without having initialized it
even a simple
j = 0;
would help.

Passing integer from one method to another

Trying to write a program with two methods. First one takes an integer and prints its divisors as well as the sum of its divisors, the second is a boolean function that returns if the given integer is equal to the sum of its divisors (a perfect number).
I have the first method done fine but I want to take the integer sum from it and use it in the second method, is this even possible? Iv spent about quite a while trying to research it with no success.
As usual any and all advice appreciated. Code so far is below.
import java.util.Scanner;
import java.io.*;
class arrayTest {
public static int sumFacs(int n) {
int sumDiv[] = new int[50];
int c = 0;
int sum=0;
if(n<0){
System.out.println("Sorry I dont do negatives!");
}
else {
for(int i=1; i<=n; i++){
int j = n%i;
if(j==0){
System.out.println( i + " is a divisor of " + n + "\n");
sumDiv[c] = i;
c++;
}
}
for (int i=0; i<sumDiv.length; i++){
sum += sumDiv[i];}
System.out.println("The sum of the divisors of " + n + " is: " + sum);
}
return sum;
}
public static boolean isPerfect(int n, int sum) {
boolean b = (n == sum);
if(b){
System.out.println( n + " is a perfect number.");
}
else {
System.out.println( n + " is not a perfect number.");
}
}
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter a positive integer.");
int n = scanner.nextInt();
sumFacs(n);
int sumDivisors = sumFacs(n);
System.out.println(isDivisors(sumFacs(n), n));
isPerfect(n, sum);
}
}
Your sumFacs returns an integer, so you can definitely use whatever it yields in your isPerfect method. As you are doing it now, you are passing the same number to the methods. To do what you want, you will need to do something like so:
int sumFacsResult = sumFacs(n); //Take whatever value sumFacs yields, store it in sumFacsResult
System.out.println(isPerfect(sumFacsResult, n); //Take the result of sumFacs and pass it to the isPerfect method
or shorthand:
System.out.println(isPerfect(sumFacs(n), n)); //It is usually recommended to use the other approach, for readability purposed.
And your isPerfect method should be something like so:
public static boolean isPerfect(int sum, int number)
{
return sum == number;
}
your sumFacs(int n) has a return type of int and you are returning sum but where you call that method you are not setting it to anything so what you want to do is:
int foo = sumFacs(n);
isPerfect(n,foo);
and make your isperfect class
public static void isPerfect(int n, int foo)
{
if((n==foo)
{
System.out.println( n + " is a perfect number.");
}else{
System.out.println( n + " is not a perfect number.");
}
}
However this would all be easier in one class not two

Categories