I'm creating a program that will generate 100 random numbers between 1 and 1000, add them to a list, and then sum up those numbers. Here's my code:
public class Iteration {
public static void main (String [] args){
private int RandomDataAnalyzer(int Rando) {
Random rand = new Random();
List<Integer> NumList = new ArrayList<Integer>();
for (int i=0;i<=100;i++){
Rando = rand.nextInt(1001);
NumList.add(Rando);
}
int sum = 0;
for (int i=0; i<100; i++)
{
Rando = rand.nextInt(100);
sum = sum + Rando;
}
return sum;
}
}
}
And here's my errors:
H:\Java\Iteration.java:12: error: illegal start of expression
private int RandomDataAnalyzer(int Rando) {
^
H:\Java\Iteration.java:12: error: ';' expected
private int RandomDataAnalyzer(int Rando) {
^
H:\Java\Iteration.java:12: error: ';' expected
private int RandomDataAnalyzer(int Rando) {
Any help, please?
You can't define a method inside another method. Close your main method first, then start RandomDataAnalyzer:
public static void main(String[] args) {
// Contents of main.
}
public int RandomDataAnalyzer(int Rando) {
// Contents of RandomDataAnalyzer.
}
I'm going to assume that this isn't a homework problem and that you're learning Java on your own. If I'm wrong, shame on me for giving a working version. But my impression is that you'll learn from this:
public class gpaCalc
{
static Random rand;
static int rando;
public static void main(String[] args)
{
ArrayList<Integer> NumList = new ArrayList<>(); // use ArrayList
for (int i=0;i<=100;i++)
{
rand = new Random();
rando = rand.nextInt(1001);
NumList.add(rando);
}
int sum = 0;
for (int i=0; i<100; i++)
{
rando = NumList.get(i); // get is "opposite" of put--get the value put into the list earlier
sum = sum + rando;
}
System.out.println(sum);
}
}
There doesn't seem to be a need for a separate method called randomDataAnalyzer.
Welcome to StackOverflow.
Let's begin with the first issue: randomDataAnalyzer is being defined inside main method. Which is wrong, you should be actually defining it at the same level.
Taken into consideration, you should also add the static word before this function because this method is part of the class, and not of the elements. It's not necessary to create a new element of the class 'Iteration' for using a simple method.
Last, but not least, you are looping through the arraylist incorrectly. You are not even calling it. As you will see now:
import java.util.*;
public class Iteration
{
public static void main(String[] args)
{
ArrayList<int> numberList = new ArrayList<int>(); // we define the arraylist
for (int i = 0; i < 100; i++)
{
numberList.add(new Random().nextInt(1001)); // we add a random number to the list
}
// finally, after the 100 values were added..
System.out.println(randomDataAnalyzer(numberList)); // we show the output
}
public static int randomDataAnalyzer(ArrayList<int> list) // we will send this function an arraylist which will get the Σ.
{
int sum = 0;
for (int value : list) // this is how we loop through foreach value in the list
{
sum += value; // which means sum = sum + value.
}
return sum; // after looping and summing up, here'll be the result
}
}
I hope this was what you were looking for.
Here's a working version. Note the changes to your original:
Don't define methods inside methods: it is illegal syntax.
Rando, NumList: the naming conventions are to start classes, interfaces, enums (i.e. types) with a capital letter, and methods, fields, and variables with a lowercase case letter;
Removed the int Rando parameter alltogether: it's value was never used (it was only assigned to)
Use the values from numList rather than generating new numbers.
Added a method illustrating that the use of such a list is not needed in this case; the 'list' of 1000 numbers is still present, but only conceptually.
import java.util.*;
public class Iteration {
public static void main (String [] args) {
int sum = new Iteration().randomDataAnalyzer();
System.out.println(sum);
}
private int randomDataAnalyzer() {
Random rand = new Random();
List<Integer> numList = new ArrayList<Integer>();
for ( int i=0; i<100; i++ )
{
numList.add( 1 + rand.nextInt(1000) );
}
int sum = 0;
for ( int i=0; i<numList.size(); i++ )
{
sum = sum + numList.get(i);
}
return sum;
}
// Note that the above method has the same effect as this one:
private int moreEfficient() {
Random rand = new Random();
int sum = 0;
for ( int i=0; i < 100; i++)
sum += 1 + rand.nextInt(1000);
return sum;
}
}
Related
I've started learning java some time ago. I'm reading through the Java Foundations book and doing exercises from the book to practice.
Just come across this one "Modify the java program so that it works for the numbers in the range between -25 and 25." and I wonder if you have any different solutions to it or is it really that simple? :)
Here's the original code:
public class BasicArray
{
public static void main(String[] args)
{
final int LIMIT = 15;
final int MULTIPLE = 10;
int[] list = new int[LIMIT];
// Initialize the array values
for(int index = 0; index < LIMIT; index++)
list[index] = index * MULTIPLE;
list[5] = 999; // change one array value
// Print the array values
for(int value : list)
System.out.println(value + "");
}
}
And here's my solution to it:
public class BasicArray
{
public static void main(String[] args)
{
final int LIMIT = 51;
final int MULTIPLE = 1;
int[] list = new int[LIMIT];
// Initialize the array values
for(int index = 0; index < LIMIT; index++)
list[index] = (index - 25) * MULTIPLE;
list[5] = 999; // change one array value
// Print the array values
for(int value : list)
System.out.println(value + "");
}
}
Yes, basically it's really simple exercise.
Regarding to your solution we actually don't need MULTIPLE in code.
public class BasicArray {
public static void main(String[] args) {
final int LIMIT = 51;
int[] list = new int[LIMIT];
// Initialize the array values
for(int index = 0; index < LIMIT; index++) {
list[index] = (index - 25);
}
list[5] = 999; // change one array value
// Print the array values
for(int value : list) {
System.out.println(value + "");
}
}
}
If you are ready for a bit of advanced java, you can try following:
public class BasicArray {
public static void main(String[] args) {
IntStream.rangeClosed(-25, 25)
.forEach(System.out::println);
}
}
Or this if you need to replace one value:
public class BasicArray {
public static void main(String[] args) {
IntStream.rangeClosed(-25, 25)
.forEach(i -> {
if (i == -20) { // change one array value
System.out.println(999);
} else {
System.out.println(i);
}
});
}
}
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.
I'm trying to generate a list of 25 non-repeating random numbers in Java, and I keep getting the Missing Return Statement error. As can be seen, I tried putting return before calling the method within itself. Not sure what's missing. It also didn't work with just the return (rando)
import java.util.*;
public class arrayList{
ArrayList<Integer> checkRandom;
ArrayList<Integer> array4;
ArrayList<Integer> array2;
ArrayList<Integer> array3;
public int addRandom(){
Random rnd = new Random();
int b=0;
for (int i=0; i<26; i++){
int rando = rnd.nextInt(101);
if (checkRandom.indexOf(rando) != -1){
return addRandom();
}
else{
checkRandom.add(rando);
array4.add(rando);
return (rando);
}
}
for (int j=0;j<26;j++){
int right;
right = checkRandom.get(j);
System.out.println(right);
}
return -1;
}
public static void main(String args[]){
arrayList randomGen = new arrayList();
randomGen.addRandom();
}
}
Exception in thread "main" java.lang.NullPointerException
at arrayList.addRandom(arrayList.java:14)
at arrayList.main(arrayList.java:37)
I'd suggest you use a much simpler method using Java 8 streams. For example, to create an array of 26 distinct random integers betweeen 0 and 100:
int[] randomArray = new Random().ints(0, 101).distinct().limit(26).toArray();
To explain in a bit more detail, this statement can be interpreted as: create a random number generator, use it to generate an endless stream of random numbers between 0 and 100, remove any duplicates, get the first 26 numbers in the stream and convert them to an int array.
Streams are incredibly powerful. Once your generator is in this form it's trivial to add a sorted operator or a filter, or to collect them into a List or Map.
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
Random rand = new Random();
while (list.size() < 25) {
int index = rand.nextInt(101);
if (!list.contains(index)) {
list.add(index);
}
}
System.out.println(list);
}
}
Initialize a method local variable b inside your addRandom method and reassign it in your for loop finally return variable b.
public int addRandom(){
Random rnd = new Random();
int b=0;
for (int i=0; i<26; i++){
int rando = rnd.nextInt(101);
if (checkRandom.indexOf(rando) != -1){
b= addRandom();
}
else{
checkRandom.add(rando);
array4.add(rando);
b=rando;
}
}
return b;
}
Your method
public int addRandom(){
Random rnd = new Random();
for (int i=0; i<26; i++){
int rando = rnd.nextInt(101);
if (checkRandom.indexOf(rando) != -1){
return addRandom();
}
else{
checkRandom.add(rando);
array4.add(rando);
return (rando);
}
}
}
does not have a return statement at the end. The method signature states you must return an integer. The compiler does not know that the for statement will be executed until runtime. Thus, you have to handle the case where the for loop is not executed. Since you can tell it will be executed every time, adding a return -1; before the end of the method will solve your problem.
i.e.
public int addRandom(){
Random rnd = new Random();
for (int i=0; i<26; i++){
int rando = rnd.nextInt(101);
if (checkRandom.indexOf(rando) != -1){
return addRandom();
}
else{
checkRandom.add(rando);
array4.add(rando);
return (rando);
}
}
return -1;
}
You can call the method by creating an instance of the class i.e.
arrayList randomGen = new arrayList();
randomGen.addRandom();
Btw, its standard in java to name your classes CamelCased. i.e. ArrayList. Although, you may want to rename it something else so you don't confuse your class with java.util.ArrayList (a popular java class)
If you want use recursion, you don't need loops. for example:
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Test {
List<Integer> randomList = new ArrayList<Integer>();
Random rnd = new Random(); // do not create new Random object in each function call.
final static int LIST_SIZE = 25;
public void addRandom(List someList) {
if (randomList.size() < LIST_SIZE) {
int random = rnd.nextInt(101); // LIST_SIZE must be lesser than 101 otherwise you will got infinite recursion.
if (!randomList.contains(random)) {
randomList.add(random);
someList.add(random);
}
addRandom(someList);
}
}
public static void main(String args[]) {
Test test = new Test();
List<Integer> array4 = new ArrayList<Integer>();
test.addRandom(array4);
for (Integer value : array4) {
System.out.println(value);
}
}
}
I am working on a problem for 5 hours, and I searched in a book and on the Internet, but I still cannot solve this problem, so please help me to check what's wrong with the program. And the pic is the requirement for this program.
//imports
import java.util.Scanner;
import java.util.Random;
public class Lab09 // Class Defintion
{
public static void main(String[] arugs)// Begin Main Method
{
// Local variables
final int SIZE = 20; // Size of the array
int integers[] = new int[SIZE]; // Reserve memory locations to store
// integers
int RanNum;
Random generator = new Random();
final char FLAG = 'N';
char prompt;
prompt = 'Y';
Scanner scan = new Scanner(System.in);
// while (prompt != FLAG);
// {
// Get letters from User
for (int index = 0; index < SIZE; index++) // For loop to store letters
{
System.out.print("Please enter the number #" + (index + 1) + ": ");
integers[index] = RanNum(1, 10);
}
// call the printStars method to print out the stars
// printArray(int intergers, SIZE);
} // End Main method
/***** Method 1 Section ******/
public static int RanNum(int index, int SIZE);
{
RanNum = generator.nextInt(10) + 1;
return RanNum;
} // End RanNum
/***** Method 2 Section ******/
public static void printArray(int integers, int SIZE) {
// Print the result
for (int index = SIZE - 1; index >= 0; index--) {
System.out.print(integers[index] + " ");
}
} // End print integers
} // End Lab09
As Tim Biegeleisen and Kayaman said, you should put everything in the question and not just an external image.
You have a lot of errors in your code. Below the code will compile and run but I recommend you to take a look and understand what it has been done.
Errors:
If you are declaring a method, make sure you use { at the end of the declaration. You have:
public static int RanNum(int index, int SIZE);
Should be:
public static int RanNum(int index, int SIZE){
// Code here
}
You also should declare outside your main method so they can be accessed across the program.
If you are passing arrays as arguments, in your method the parameter should be an array type too.
You have:
public static void printArray(int integers, int SIZE) {
// Code her
}
Should be
public static void printArray(int[] integers, int SIZE) {
// Code her
}
Here is the complete code:
package test;
import java.util.Random;
import he java.util.Scanner;
public class Test {
//Local variables
public static final int SIZE = 20; //Size of the array
static int integers[] = new int[SIZE]; //Reserve memory locations to store integers
static int randomNumber;
static Random generator = new Random();
static String prompt;
static final String p = "yes";
static boolean repeat = true;
static Scanner input = new Scanner(System.in);
Test() {
}
/***** Method 1 Section ******/
public static int RanNum (int low, int high) {
randomNumber = generator.nextInt(high-low) + low;
return randomNumber;
} //End RanNum
/***** Method 2 Section ******/
public static void printArray(int[] intArray, int SIZE) {
//Print the result
for (int i = 0; i < SIZE; i++) {
System.out.print (intArray[i] + " ");
}
} //End print integers
public static void main (String [] arugs) {
do {
for (int i = 0; i < SIZE; i++) {
integers[i] = RanNum(1, 10);
}
printArray(integers, SIZE);
System.out.println("Do you want to generate another set of random numbers? Yes/No");
prompt = input.nextLine();
} while(prompt.equals(p));
}
}
I want to make a function that pick a randomly number in array and avoid to pick the same number in next time.
Here is my code (it work in sometime and mostly inf-loop)
please help me, Thank you.
private static int pick(int[] x) {
int upperbound = x[x.length-1];
int lowerbound = x[0];
int count=0;
int ranvalue;
int ranindex;
Random rand = new Random();
do{
ranindex = rand.nextInt(upperbound-lowerbound) + lowerbound;
count++;
}while(x[ranindex]==-1||count!=x.length-1);
ranvalue=x[ranindex];
x[ranindex]=-1;
return ranvalue;
}
If your array has size n, then you can get at most n different indexes. I advise the following :
Create an array with numbers from 0 to n-1.
Shuffle it.
At each step, take the next element from this array and use it as an offset for your source array.
You should also wrap this logic into a class like this :
public class Picker {
private int[] source;
private List<Integer> offsets;
private int currentIndex = 0;
public Picker(int[] source) {
this.source = source;
Integer[] indexes = new Integer[source.length];
for(int i=0;i<source.length;i++) {
indexes[i] = i;
}
this.offsets = Arrays.asList(indexes);
Collections.shuffle(this.offsets);
}
public Integer next() {
return source[offsets.get(currentIndex++)];
}
}
Example :
public static void main(String[] args) {
int[] source = {8,3,5,9};
Picker picker = new Picker(source);
for(int i = 0; i<4;i++) {
System.out.println(picker.next());
}
}
Output :
5
3
8
9
EDIT : Or even simpler :
Integer[] source = {8,3,5,9};
//Copy the source and shuffle it
List<Integer> dest = Arrays.asList(source);
Collections.shuffle(dest);
//Then display
for (int i = 0;i<source.length;i++) {
System.out.println(dest.get(i));
}