printing method class randTest (int n) - java

I am having trouble printing out the method randTest (int n) as errors keep appearing. I want to print this method in the main as i want to print the results in a clear tabular form. The method must stay static void. This is my code below:
public class RandNumGenerator {
public static int RandInt(){
double n = Math.random()*10;
return (int) n;
}
public static void randTest(int n){
int [] counts = new int [10];
for(int i=0;i<n;i++){
counts[i] = RandInt();
System.out.println(counts[i]);
}
}
public static void main(String[] args) {
System.out.println(RandInt());
System.out.println(randTest());
}
}

Just call the method randTest() instead of printing it. The work of printing is already done inside the method. And randTest takes in an argument of the type int. So, you need to save the return of RandInt and then pass it into the method.
public static void main(String[] args) {
int randInt = RandInt();
System.out.println(randInt);
randTest(randInt);
}

Related

Passing array to a function and using that array in an Enhanced for loop

When I pass the array "bucky" to the change function and in the change function if I use an enhanced for loop, the variable counter gives the error "The value of the local variable counter is not used"
But if I put the body of the for loop in an System.out.println(counter+=5) the error does not appear
class apples{
public static void main(String[] args) {
int bucky[]={3,4,5,6,7};
change(bucky);
}
public static void change(int x[]){
for(int counter: x){
counter+=5;
}
}
}
Why does this code give the error I mentioned above since I'm using the counter variable in the enhanced for loop?
Edit - my objective is to change values of the array inside the "change" function and return it back to main.
Question is about updating original array values, then you have to use normal for loop so that each index values can be updated:
class apples{
public static void main(String[] args) {
int bucky[]={3,4,5,6,7};
bucky = change(bucky);
for(int b:bucky) {
System.out.println(b);
}
}
public static void change(int x[]){
for (int i = 0; i < x.length; i++) {
x[i]=x[i]+5;
}
return x;
}
}

How to call java method on main class

I'm a beginner in Java and I have a very simple problem. I'm trying to finish an activity and I forgot how to call a method on the main class.
I keep getting an error whenever I try ways to call the computeSum method on the main class.
Error: Error: Main method not found in class array.Array, please define the main method as: public static void main(String[] args)
public class Array{
public static void main(String[] args ){
//Dont know what to put here to call computeSum
}
public int computeSum(int[] nums){
int sum = 0;
for (int i=0; i<nums.length; i++){
sum= sum+nums[i];
}
return sum;
}
}
Suppose if your class is there in com.arr package. you can specify the qualified name of the class at the time of creating object. Because Array class is already available in java.util package. It is better to create object to your Array class along with package name.
public static void main(String[] args){
com.arr.Array a1 = new com.arr.Array();
int[] numberArray = {1,7,9,0,45,2,89,47,3,-1,90,10,100};
a1.computeSum(numberArray);
}
computeSum() it's an instance method. we have to create Object to your class for calling the instance methods.
You can try this
public class Array{
public static void main(String[] args ){
//Dont know what to put here to call computeSum
int[] nums = {1,2,3,4,5};
int sum=computeSum(nums);
System.out.println(sum);
}
public static int computeSum(int[] nums){
int sum = 0;
for (int i=0; i<nums.length; i++){
sum= sum+nums[i];
}
return sum;
}
}
You need to create an instance to invoke member method of a class.
public static void main(String[] args ){
Array myArray = new Array();
int[] values = new int[] {1,2,3,4};
myArray.computeSum(values);
}
You can read about instance methods and static methods.
computeSum() is an instance method, which means it would need an object of Class Array to be called, example:
public static void main(String[] args){
Array array = new Array();
int[] nums = {1,2,3};
array.computeSum(nums);
}
Alternatively, you could make it a static method to use it without making an object, which is not recommended, but incase you want, this is how you can do it:
public class Array{
public static void main(String[] args ){
int[] nums = {1,2,3};
int sum = computeSum(nums);
}
public static int computeSum(int[] nums){
int sum = 0;
for (int i=0; i<nums.length; i++){
sum= sum+nums[i];
}
return sum;
}
}
First you need to understand the difference between static classes/members and instance classes/members.
Your main method is static - as is standard for the entry method of a program - meaning it is available immediately without any binding to an instance of the Array object.
Your computeSum method is an instance method. Meaning that you need an instance of the object Array, to use it, and it will execute in that object's context.
Your choices:
1)
Make computeSum static:
public static void main(String[] args) {
computeSum({1,2,3}); // or Array.computeSum() outside of Array
}
public static int computeSum (int[] nums) {
int sum = 0;
for (int i=0; i<nums.length; i++){
sum= sum+nums[i];
}
return sum;
}
2)
Make an instance of the Array object:
public static void main(String[] args){
Array myArray = new Array();
myArray().computeSum({1,2,3});
}
public static int computeSum (int[] nums) {
int sum = 0;
for (int i=0; i<nums.length; i++){
sum= sum+nums[i];
}
return sum;
}
Static code - not ran in the context of an object's instance - can not reference members that are not static, this makes sense as, how would it know what object instance of that member you are referencing (myArray1.computeSum()? or myArray2.computeSum()? It doesn't even know these two instances of the myArray object exist).
Hope this helps. :)
Or you could use reflection just for a change ;)
https://docs.oracle.com/javase/tutorial/reflect/
Firstly your method have an attribute which is "int[] nums " to call the method you need to set a value to your attribute .
NOTE that you don't have to give the same name to your attribute while calling.
for example : 1 - int[] Myattribute = {1,2,3};
int sum = computeSum(Myattribute );
put this line incide your Main it ill work

Method to get the sum of an ArrayList

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.

why does it stop half way through my code?

So the first part creates a vector and adds a digit to the 10 slots. Then after this nothing happens, i have no errors in my code but it just stops.. why?
package ovn7;
import java.util.Scanner;
public class ovn7a {
int []vektor;
Scanner scan = new Scanner(System.in);
public static void main(String []args) {
int []vektor = new int[10];
for(int k=1; k<10; k++){
vektor[k]=0+k;
System.out.println(k);
}
}
public int find(int tal) {
System.out.println("tal");
tal = scan.nextInt();
int i = 0;
while(i<10 && vektor[i] != tal) {
i++;
}
return (i <10) ? i : -1;
}
}
This is your main method:
public static void main(String []args) {
int []vektor = new int[10];
for(int k=1; k<10; k++){
vektor[k]=0+k;
System.out.println(k);
}
}
That's all your program does - when it hits the closing right brace of the main method, execution ends. If you want it to execute public int find(int tal) as well, you need to include a method call to your main method:
int index = find(5); //for example
Remember, the main method is the only one that is called automatically when executing the program! You'll have to call find yourself inside main.
EDIT: per request, an example of main with the method call included:
public static void main(String []args) {
int []vektor = new int[10];
for(int k=1; k<10; k++){
vektor[k]=0+k;
System.out.println(k);
}
int index = find(5); // <-- this find(5) here is a method call for find!
System.out.println("The method returned a value of " + index + ".");
}
You can replace that "5" with any integer, as the method find accepts an integer as an argument. (as a side note, it doesn't matter which integer you pass to find - it overwrites the argument with a new value anyway)

How to use main array in method?

I want to take user input for merge sorting so i'm using the array ar[] in the method but it gives error "cannot find symbol " for ar[]..
import java.util.*;
import java.io.*;
class Test
{
int Merge()
{
int q,p,r,i,l,m,j,t,k,w,x,s,u;
w=q-p+1;
x=r-q;
int[] L=new int [w+1];
int b=1;
for(s=1;s<=w+1;s++)
{
L[b]=s;
b++;
}
int[] R=new int [x+1];
int c=1;
for(t=1;u<=x+1;u++)
{
R[c]=u;
c++;
}
for(i=1;i<=w;i++)
{
L[i]=ar[p+i-1];
}
for(j=1;j<=x;j++)
{
R[j]=ar[q+j];
}
L[w+1]=1000;
R[x+1]=1001;
i=1;
j=1;
for(k=p;k<=r;k++)
{
if(L[i]<=R[j])
{
ar[k]=L[i];
i=i+1;
}
else
{
ar[k]=R[j];
j=j+1;
}
}
System.out.println("sorted array"+ar[k]);
}
public static void main(String ar[])
{
int a0=Integer.parseInt (ar[0]);
int a1=Integer.parseInt (ar[1]);
int a2=Integer.parseInt (ar[2]);
int a3=Integer.parseInt (ar[3]);
int a4=Integer.parseInt (ar[4]);
int a5=Integer.parseInt (ar[5]);
int a6=Integer.parseInt (ar[6]);
int a7=Integer.parseInt (ar[7]);
int a8=Integer.parseInt (ar[8]);
int a9=Integer.parseInt (ar[9]);
int p=a0,r=a9,q;
if(p<r)
q=(p+r)/2;
Test T=new Test();
T.Merge();
}
}
ar is visible only in the scope of main method, it's unknown in other methods. In order to see it in other methods, you need to have a class member that will hold its value.
You have an ar local variable in the main method, but you don't have it in the Merge method. Local variables, and method parameter is just another kind of local variable, are... well, local to the method where they are declared. That means that such a variable is undefined in another method.
For example, you can have
class Test {
final int[] ar;
Test(int[] ar) { this.ar = ar; }
public static void main(String[] ar) {
....
final Test t = new Test(ar);
t.Merge();
}
}
ar is will be visible in main method only, you need to create a new array in main method. Copy values read into new array and pass this array as input to merge method.

Categories