I want to calculate the number of occurences of a specific number I decide in my main method. Here is what I have to do :
• A function that fills the array with random numbers.
• A function that calculates the number of occurrences,this function may not do any input or output.
• The main function that asks the user for the number and present the result on the screen.
Here is my code in java :
import java.util.Random;
import java.util.Scanner;
public class Code {
public void calculate(int value) {
Code c = new Code();
int count=0;
for (int n=0; n<array.length; n++) { // the code does not recognize array
if (array[n]==value) { // the code does not recognize array
count++;
}
}
System.out.println(count);
}
public void addToArray() {
int k =0;
int [] array = new int[10];
int min=0;
int max=10;
int diff = max-min;
while (k<10) {
Random r = new Random();
int x = r.nextInt(diff);
array[k]=x;
k=k+1;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("give your number");
Code c = new Code();
Scanner s = new Scanner(System.in);
int value = s.nextInt();
c.addToArray();
c.calculate(value);
}
}
The only thing I need help with is the calculate method ,, eclipse does not recognize array in the calculate method above ..
How to correct the calculate method to make it recognize array ?
thank you
Your array is limited to the scope of the method addToArray(). So, it will not be visible to other methods. You need to make it global. Then it will work.
Instead of declaring array in the method addToArray, declare it in your class, like:
public class Code {
int [] array = new int[10];
...
if using Java 8 you could update your calculate methode like this :
public void calculate(int value) {
System.out.println(Arrays.stream(array)
.filter(i -> i == value)
.count());
}
By adding this imports to your class :
import java.util.Arrays;
And like mentionned HackerDarshi declaring the attribut array as a member of your class
Related
I am practising dynamic coding so I want to create a list for class. I hereby Initialized a list for class and want to create an array with different length for each iteration in list. But It doesnt initialize it like I expected instead its length says 0.
import java.io.*;
import java.util.*;
class testcase
{
int N;
int play []= new int [N];
int villain[]=new int [N];
String status;
}
public class Main {
public static void main(String args[] ) throws Exception {
List<testcase> caseno=new ArrayList<testcase>();
Scanner sc=new Scanner(System.in);
int n1=1;
//int n1=sc.nextInt();
int i,j;
testcase t;
for(i=0;i<n1;i++)
{
int n=6;
//int n=sc.nextInt();
t=new testcase();
t.N=n;
System.out.println(t.N+" "+t.play.length);
}
}
}
The array length should print 6 instead it shows 0
You have to create a parametrized constructor in which you'll pass the value of N and then initilaze the arrays. Like
class testcase // Name should be in PASCAL
{
int N;
int [] play;
int [] villain;
String status;
public testcase (int n) { // Constructor
this.N=n;
play = new int [N];
villain=new int [N];
}
}
And in the main methos you create object like this
int n= . . .;//taking input from user
testcase t=new testcase(n);
You need to write a constructor which does these assignment based on the value passed.
// Implement your constructor something like this
public Testcase(int value) {
this.N = value;
play = new int [value];
// Some more assignment based on the need
}
And after that, you need to create the object instance
int N = 6;
Testcase newTestcase = Testcase(N);
NOTE: Clase name should always start with a capital letter.
Try declaring these variable like N, status, play e.t.c as private. After that assign and access them using getter() and setter().
import java.util.Random;
class random
{
public static void main(String[] args)
{
int n[];
Random rand=new Random();
for(int i=0;i<=10;i++)
{
int n[i]=rand.nextInt();
System.out.println("The random number is::"+n[i]);
}
}
}
This is the error i get while compiling:
I have no idea can anyone please help.
// first you need to declare the size for the n array
int n[] = new int [11]; // needs to be 11
Random rand=new Random();
for(int i=0;i<=10;i++)
{
n[i]=rand.nextInt(); // and then just assign
System.out.println("The random number is::"+n[i]);
}
but to be honest you do not even need this array in this code as it is not being re-used
More simpler would be
Random rand=new Random();
for(int i=0;i<=10;i++)
{
System.out.println("The random number is::" + rand.nextInt());
}
You need to initialize your array. See link for an example.
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
n = new int[11];
before the for loop should do it.
Thanks for the catch wombat
try this thing...
import java.util.Random;
class random
{
public static void main(String[] args)
{
int[] n= {1,2,3,4,5,6,7,8,9,10,11};
for(int i=0;i<=10;i++)
{
Random rand=new Random();
n[i]=rand.nextInt();
System.out.println("The random number is::"+n[i]);
}
}
}
First of all, suppose we want to use array we can use in two ways:
As a variable where you need to define fixed size first otherwise you will get ArrayIndexOutOfBoundsException:
int[] id = new int[size fo array];
example : -
`
import java.util.Random;
class random
{ public static void main(String[] args)
{
// here first you need to initilized the array with fixed sizea
int n[] = new int[11];
Random rand=new Random();
for(int i=0;i<=10;i++)
{
n[i]=rand.nextInt();
System.out.println("The random number is::"+n[i]);
}
}
}
`
As an Argument of the method where you need not define the fixed size:
the best example is a command line argument
For execution below code, you need to pass command line argument at runtime.
`
import java.util.Random;
class random
{
public static void main(String[] args)
{
System.out.println(args[0] + args[1]);
}
}
`
I wish to create a list, and the list has a input as length, however after I put in the preferable length as input, the list won't show up;
import java.util.ArrayList;
import java.util.Scanner;
public class JJ {
public static void main(String args[]) {
JJ.getalist();
}
public static ArrayList<Integer> getalist(){
ArrayList<Integer> JJ = new ArrayList<Integer>();
System.out.println("Oh, How long would you want your list to be?");
Scanner in = new Scanner(System.in);
int length = in.nextInt();
for (int i=0; i<length; i++) {
int point = (int) (Math.random()*9);
JJ.add(new Integer(point));
}
return JJ;
}
}
You didn't use System.out.println() in the main method when invoking JJ.getalist(). You can pass JJ.getalist() return value as the argument of the method printing to the console like this:
System.out.println(JJ.getalist()).
I want to populate an arrayList with random numbers then print array. However I get a huge number of errors when executing the program. Any help would be appreciated.
public class methods {
//variables
int capacity;
private static ArrayList<Double> randomArray;
public methods(int capacity) {
//default constructor to initalize variables and call populateArray to
//populate ArrayList with random numbers
randomArray = new ArrayList<>(capacity);
populateArray();
}
//Method that populates Array with random numbers
private void populateArray()
{
Random rand = new Random();
for (int i=0; i<= capacity; i++)
{
double r = rand.nextInt() % 256;
randomArray.add(i,r);
}
}
//Get Array adds numbers to the string that is called in my main class and printed
public String getArray() {
String result = "";
for (int i=0; i<= capacity; i++)
{
result += String.format("%4d", randomArray);
}
return result;
}
}
//main
public class Benchmarking {
public static void main (String args[]){
Scanner scanner = new Scanner(System.in);
System.out.println("What is the capacity of your Array?");
int capacity = scanner.nextInt();
methods array1 = new methods(capacity);
System.out.println(array1.getArray());
}
After I run the program and enter the capacity it crashes. I just need to create an arrayList populate it with random numbers and print it. Here are the list of Errors I am receiving:
Exception in thread "main" java.util.IllegalFormatConversionException: d != java.util.ArrayList
at java.util.Formatter$FormatSpecifier.failConversion(Formatter.java:4302)
at java.util.Formatter$FormatSpecifier.printInteger(Formatter.java:2793)
at java.util.Formatter$FormatSpecifier.print(Formatter.java:2747)
at java.util.Formatter.format(Formatter.java:2520)
at java.util.Formatter.format(Formatter.java:2455)
at java.lang.String.format(String.java:2927)
at Benchmarking.methods.getArray(methods.java:68)
at Benchmarking.Benchmarking.main(Benchmarking.java:27)
I think I am doing something fundamentally wrong with my methods.
You cannot pass randomArray (which is a java.util.ArrayList) to String.format().
You probably want to pass randomArray.get(i) instead.
Add this.capacity = capacity; into public methods() { constructor to start with. You are referencing this variable but never setting it.
String s contains a set of integers separated by white space (blanks, tabs, or newlines). Return the sum of the integers.
You can use a Scanner object to solve this problem. Create a new Scanner(s) and store it in a variable, say in. Then, use in.hasNextInt() to control a while loop. Each iteration of the while loop uses in.nextInt() to get the next integer from the String s. Accumulate this integer into a variable and return that variable when the loop exits.
You may use a main method to test your method by creating an instance of the Calculator class and calling sum(…) with several combinations of values using that instance.
For example, sum(“3 4 5 27 3”) is 42.
I have written this so far:
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
}
public int sum(String s){
int i = 0;
Scanner in = new Scanner(s);
while (in.hasNextInt()) {
sum = sum + in.nextInt();
}
return sum;
}
}
To call the method from main and display the results make the sum method static and then call it and print the result:
public static void main(String[] args) {
System.out.println(sum("1 2 3"));
}
import java.util.Scanner;
public class Calculator{
public static void main(String[] args){
System.out.println(sum("1 2 3"));
}
public static int sum(String s){
int i = 0;
int sum = 0;
Scanner in = new Scanner(s);
while (in.hasNextInt()) {
sum = sum + in.nextInt();
}
return sum;
}
}