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));
}
}
Related
can someone please tell me why I am getting this error when compiling?
import java.util.*;
import java.io.*;
public class StatsCalculator
{
public static void main (String[]args)
{
programHeader();
randomNo(random);
printArray(random);
}
public static void programHeader()//writes program header
{
System.out.println("****************");
System.out.println("Stats calculator");
System.out.println("****************");
}
public static int[] randomNo(int[] random)// fills an array with 10 random numbers
{
random = new int[10];
for (int i=0; i< random.length; i++){
int randomNumber= (int) (Math.random()*10)+1;
random[i] = randomNumber;
}
return random;
}
public static int[] printArray (int[] random)//prints array
{
System.out.println("Your ten random values are: ");
for (int i=0; i<random.length; i++){
System.out.print(Arrays.toString(random));
}
return random;
}
}
I am writing a simple program to fill and array with 10 random numbers 1-10 and then calculate the sum, mean, mode and median of all the random numbers but i can get the methods to work just to fill the array and to print the array.
any help is appreciated.
You should get return value of randomNo() then pass it to next method. This may help you:
import java.util.Arrays;
public class StatsCalculator {
public static void main(String[] args) {
programHeader();
int[] random = randomNo();
printArray(random);
}
public static void programHeader()//writes program header
{
System.out.println("****************");
System.out.println("Stats calculator");
System.out.println("****************");
}
public static int[] randomNo()// fills an array with 10 random numbers
{
int[] random = new int[10];
for (int i = 0; i < random.length; i++) {
int randomNumber = (int) (Math.random() * 10) + 1;
random[i] = randomNumber;
}
return random;
}
public static int[] printArray(int[] random)//prints array
{
System.out.println("Your ten random values are: ");
for (int i = 0; i < random.length; i++) {
System.out.print(Arrays.toString(random));
}
return random;
}
}
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;
}
}
I want to run a method that returns an array. Code such as this:
public static int[] getArray() {
int square[] = new int[5];
int input = 0;
System.out.println("Input a valid integer from 1-49");
System.out.println("for array input please \\(^-^)/");
System.out.println("Remember (^_'), don't repeat numbers");
Scanner reader = new Scanner(System.in);
for (int i = 0; i < 5; i++) {
System.out.println(
"Please input the integer for position " + (i + 1) + " of the array");
input = reader.nextInt();
square[i] = input;
}
return square;
}
I have researched that you can make a variable like so int[] data = getArray();
How would I make it so that data can be accessible to other methods in the same class so I could do something like
public static int linearSearch(data) {
}
without having to constantly be re-entering the values for the array?
You can try out to introduce private variable of int[] and provide a lazy initialization for it, something like this:
class aClass {
int[] data; // default to the null
private int[] getArray() {
if (data == null) {
// your console logic for initialization
}
return data;
}
public static int linearSearch() {
int[] localData = getArray();
}
}
But in this case you can change the contents of data field in your methods across the class.
This can be done two ways:
- Either declaring the variable as class-level variable
- Or declaring it as local variable inside main method
public class ReturnIntArraysSO {
/**
* #param args
*/
public static void main(String[] args) {
int[] data = getArray();
for(int i : data){
System.out.print(i+" ");
}
linearSearch(data);
}
/**
*
* #return
*/
public static int[] getArray() {
int square[] = new int[5];
int input = 0;
System.out.println("Input a valid integer from 1-49");
System.out.println("for array input please \\(^-^)/");
System.out.println("Remember (^_'), don't repeat numbers");
Scanner reader = new Scanner(System.in);
for (int i = 0; i < 5; i++) {
System.out.println("Please input the integer for position "
+ (i + 1) + " of the array");
input = reader.nextInt();
square[i] = input;
}
return square;
}
/**
*
* #param data
* #return
*/
public static void linearSearch(int[] data) {
for(int a : data){
if(a == 5){
System.out.println("\nFound 5!!");
}
}
}
}
You need to declare i your array like this:
public YourClass {
public static int[] square = new int[5];
}
This way you can access this array from any other class and it will remain with the exact array (that's what static for). Example:
From Class1 - YourClass.square
From Class2 - YourClass.square
Both are the same array instance
I am trying to create a square matrix filled with random numbers from 1 - 99.
I have set this up, but anything over 7 dimensions returns an error, and I'm not sure why.
Every time I have started over the max dimensions it will break at is different.
package matrix;
import java.util.Arrays;
import java.util.Scanner;
import java.util.Random;
public class Matrix {
static int dim;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String repeat="yes";
do
{if (dim<=25)
{//prompt user for dimensions, only need one number
System.out.println("Please enter the dimensions of the matrices. Enter one number that is greater or equal to 25.");
dim=sc.nextInt();
//all rows and columns are equal
matrices m1 = new matrices(dim);
m1.randomFill();
m1.printMatrix();
System.out.print("\n Would you like to repeat the program? (yes/no)");
repeat=sc.next();
}
else
{System.out.print("Invalid dimensions, pleasse enter a number greater or equal to 25.");
dim=sc.nextInt();
}
}
while (repeat.trim().equalsIgnoreCase("yes"));
}
}
public class pool {
//instance variables
private int size;
static int [] poolArray;
private Random ridx;
//constructors
public pool (int sz)
{size = sz;
poolArray = new int [sz];
ridx = new Random ();
}
//instance methods
public void fillPool ()
{for(int n=0; n<size; n++)
{poolArray [n]=n+1;
}
}
public int randomValue ()
{int idx = ridx.nextInt(size);
int rval = poolArray [idx];
size--;
poolArray [idx] = poolArray [size];
return (rval);
}
public static void main(String[] args) {
pool p1 = new pool (99);
{p1.fillPool ();}
System.out.println(poolArray[0]+", "+poolArray[25]+", "+poolArray[98]);
System.out.println(p1.randomValue());
}
}
public class matrices {
static int [][] m;
static int size;
static pool p1 = new pool (99);
{p1.fillPool ();}
static pool p2 = new pool (99);
{p1.fillPool ();}
matrices (int dimension)
{m=new int [dimension][dimension];
size=dimension;}
static void randomFill ()
{int i, j; // loop counters
for (i=0;i<size;i++)
{ for(j=0;j<size;j++)
m[i][j]=p1.randomValue();
}
}
static void printMatrix()
{ int i, j; // loop counters
for (i=0;i<size;i++)
{ for(j=0;j<size;j++)
System.out.print(m[i][j] + " ");
System.out.println("");
}
System.out.println("");
}
}
This is the error that comes up:
Exception in thread "main" java.lang.IllegalArgumentException: n must be positive
at java.util.Random.nextInt(Random.java:300) at matrix.pool.randomValue(pool.java:34)
at matrix.matrices.randomFill(matrices.java:28) at matrix.Matrix.main(Matrix.java:30) Java
Result: 1
Please, format your code!
But rids.nextInt(size) can throw an error if size < 0, which it indicates.
Subsequently this is possible if you have an integer overflow, where you are trying to store an integer > Integer.MAX_VALUE, possibly resulting in a negative value due to the overflow. This behaviour differs per integer.
**This is my first post so don't know if I did this right. But I have to read a file and then put the list in order from smallest to largest by the population. All I get is Alabama and that shows up only one time. I think my problem is from the "for" statement but I am not sure. It could also be from the "return" statement. The file is set up like this
Alabama,4779736
Alaska,7102313**
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class Inorder {
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
PrintWriter prw = new PrintWriter("outfile.txt");
File f = new File("census2010.txt");
if(!f.exists()) {
System.out.println( "f does not exist ");
}
Scanner infile = new Scanner(f);
infile.useDelimiter ("[\t|,|\n|\r]+");
final int MAX = 50;
int [] myarray = new int [MAX];
String[] statearray = new String[MAX];
int fillsize;
fillsize = fillarray (myarray, statearray, infile);
printarray (myarray, fillsize, prw);
sortarray(myarray, statearray, fillsize);
}
public static int fillarray (int[] num, String[] states, Scanner infile){
for( int count = 0; count < 50; count++){
int retcnt = 0;
int pop;
String state;
state = infile.next();
pop = infile.nextInt();
System.out.println(state + " " + pop + " ");
states[retcnt] = state;
num[retcnt] = pop;
retcnt++;
return (retcnt); }
}
public static void printarray (int[] num, int fillsize, PrintWriter prw){
for (int counts = 0; counts < fillsize ; counts++){
System.out.println("For the position ["+counts+"] the value is " + num[counts]);
prw.println("For the position ["+counts+"] the value is " + num[counts]);
}
return;
}
public static void sortarray(int[] poparray, String[] statearray, int fillsize){
for( int fill = 0; fill < fillsize -1; fill = fill+1){
for ( int compare = fill+1; compare < fillsize; compare++){
if( poparray[compare] < poparray[fill]){
int poptemp = poparray[fill];
poparray[fill] = poparray[compare];
poparray[compare] = poptemp;
// do I need something here?
String statetemp = statearray[fill];
statearray[fill] = statearray[compare];
statearray[compare] = statetemp;
}
}
}
}
}
It looks like you just need to move your return statement outside of the for loop.
public static int fillarray (int[] num, String[] states, Scanner infile){
for( int count = 0; count < 50; count++){
// ...
} // Finish *all* iterations of the loop, *then* return
return (retcnt);
}
By having a return inside your loop, you only execute the first iteration and the method returns (preventing all other 49 iterations). You do this correctly in your printarray method.
Edit:
As you mentioned, moving the return statement outside of your loop makes it so that retcnt is no longer accessible. This is because you declare retcnt inside the loop; if you declare retcnt before the loop, you will have no problems.
int retcnt = 0;
for (//...) {
//...
}
// The variable retcnt is now accessible for the entire method scope,
// instead of just the loop block
return retcnt;