So, I have to make a random number generator to get numbers ranging from 0 to 400. I'm putting these into an array and then sorting them later on. I just am not sure how to go about doing this. I was given something along the lines of;
public int nextInt(400) //gives me errors
{
random.setSeed(12345L);
for (int i = 0; i < arr.size; i++)
{
val = random.nextInt(400);
a[i] = val;
}
}
I've already called the random class, since the directions indicated that. I just don't know why this is not working. It's giving me errors especially with the first part; class, interface, or enum expected. Could somebody steer me in the right direction please?
Functions in Java (all programming languages) have "variables" in their definition.
You've got:
public int nextInt(400)
Over here, you want your 400 to be a value that is passed to the function.
Think of this as math. I'm sure you've dealt with something like f(x) = 2 * x. Here, x is the variable, and you "evaluate" f(x) with a value for x. Similarly, in programming, we'd have something like :
public int nextInt(int x)
As you see, our function defines x to be of type int. This is necessary in a language like Java because you're telling the compiler that this function will only accept integers for x.
Now that you've done that, you can use x as a variable in the body of your function.
Note that whenever you use a variable, it first has to be defined. A line such as:
int variable;
defines variable as an int.
Your program is missing these for random, val, arr, and a. Note here that arr and a are arrays (and somehow I get the feeling that they should not be two separate variables).
You should really brush up on variables definitions, arrays, and functions before attempting this question. Your best resource would be your textbook, because it'll explain everything in an organized, step-by-step manner. You can also try the many tutorials that are available online. If you have specific questions, you can always come back to StackOverflow and I'm sure you'll find help here.
Good luck!
You need to define this function within a class definition
even you have specified :
public int nextInt(400)
in this line function returns int and in your whole body u didn't have any return statement.
and yes as Kshitij Mehata suggested dont use 400 directly as value use variable over there.
this should be your function:
public int[] nextInt(int x) //gives me errors
{
random.setSeed(12345L);
int[] a=new int[arr.size];
for (int i = 0; i < arr.size; i++)
{
val = random.nextInt(400);
a[i] = val;
}
return a;
}
even there is some issue with arr from where this arr come?
Related
I've searched extensively online but all solutions I've found use two parameters to keep track of the size of the area being used. This would be easy if I was allowed to do that, but I'm not. As you can see below, the code lacks a stop value, because I have no idea how to retain the original information.
This is the code on Wikipedia, you can see they use imin and imax for tracker variables: http://en.wikipedia.org/wiki/Binary_search_algorithm#Recursive
My (very incorrect) code is below. The mid variable doesn't mean anything, because I don't know how to set low and high correctly if I'm not allowed to have any extra arguments in the function.
public static int findRecursiveB( String s, char c)
{
int low = 0;
int high = s.length()-1;
int mid = (low+high)/2;
if (s.charAt(mid) < c) {
return findRecursiveB(s.substring(low, mid), c);
}
else if (s.charAt(mid) >= c) {
return findRecursiveB(s.substring(mid+1, high), c);
}
else return mid;
}
One crucial point here is what does the original String s contain? For this to work, it has to be a sorted String, meaning that the characters in the String must be in order. Specifically, it looks like you've written code that expects s to be sorted in reverse order. Otherwise, unless I'm totally missing something, your code does exactly what it is supposed to: no need to pass extra params because you are passing in the substring on each recursive call.
Otherwise, good job.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am preparing for an exam next week, and I decided to look for some exam questions online for better preparation.
I came across this question and the answer is c. But I really want to know how or the step by step process to answer to answer a question like this. The part where I got stuck is trying to logically understand how a int m = mystery(n); How can a number equal a method? Whenever I get to a question like this is their anything important I should breakdown first?
private int[] myStuff;
/** Precondition : myStuff contains int values in no particular order.
/*/
public int mystery(int num)
{
for (int k = myStuff.length - 1; k >= 0; k--)
{
if (myStuff[k] < num)
{
return k;
}
}
return -1;
}
Which of the following best describes the contents of myStuff after the
following statement has been executed?
int m = mystery(n);
(a) All values in positions 0 through m are less than n.
(b) All values in positions m+1 through myStuff.length-1 are
less than n.
(c) All values in positions m+1 through myStuff.length-1 are
greater than or equal to n.
(d) The smallest value is at position m.
(e) The largest value that is smaller than n is at position m.
See this page to understand a method syntax
http://www.tutorialspoint.com/java/java_methods.htm
int m = mystery(n); means this method going to return int value and you are assigning that value to a int variable m. So your final result is m. the loop will run from the array's end position to 0. loop will break down when array's current position value is less than your parameter n. on that point it will return the loop's current position. s o now m=current loop position. If all the values of the loop is greater than n it will return -1 because if condition always fails.
Place the sample code into a Java IDE such as Eclipse, Netbeans or IntelliJ and then step through the code in the debugger in one of those environments.
Given that you are starting out I will give you the remainder of the code that you need to make this compile and run
public class MysteriousAlright {
private int[] myStuff;
public int mystery(int num)
{
for (int k = myStuff.length - 1; k >= 0; k--) {
if (myStuff[k] < num) {
return k;
}
}
return -1;
}
public static void main(String[] args) {
MysteriousAlright ma = new MysteriousAlright();
ma.setMyStuff(new int[] {4,5,6,7});
int m = ma.mystery(5);
System.out.println("I called ma.mystery(5) and now m is set to " + m);
m = ma.mystery(3);
System.out.println("I called ma.mystery(3) and now m is set to " + m);
m = ma.mystery(12);
System.out.println("I called ma.mystery(12) and now m is set to " + m);
}
public void setMyStuff(int[] myStuff) {
this.myStuff = myStuff;
}
}
You then need to learn how to use the debugger and/or write simple Unit Tests.
Stepping through the code a line at a time and watching the values of the variables change will help you in this learning context.
Here are two strategies that you can use to breakdown nonsense code like that which you have sadly encountered in this "educational" context.
Black Box examination Strategy
Temporarily ignore the logic in the mystery function, we treat the function as a black box that we cannot see into.
Look at what data gets passed in, what data is returned.
So for the member function called mystery we have
What goes in? : int num
What gets returned : an int, so a whole number.
There are two places where data is returned.
Sometimes it returns k
Sometimes it returns -1
Now we move on.
White Box examination Strategy
As the code is poorly written, a black box examination is insufficient to interpret its purpose.
A white box reading takes examines the member function's internal logic (In this case, pretty much the for loop)
The for loop visits every element in the array called myStuff, starting at the end of the array
k is the number that tracks the position of the visited element of the array. (Note we count down from the end of the array to 0)
If the number stored at the visited element is less than num (which is passed in) then return the position of that element..
If none of elements of the array are less than num then return -1
So mystery reports on the first position of the element in the array (starting from the end of the array) where num is bigger than that element.
do you understand what a method is ?
this is pretty basic, the method mystery receives an int as a parameter and returns an int when you call it.
meaning, the variable m will be assigned the value that returns from the method mystery after you call it with n which is an int of some value.
"The part where I got stuck is trying to logically understand how a int m = mystery(n); How can a number equal a method?"
A method may or may not return a value. One that doesn't return a value has a return type of void. A method can return a primitive value (like in your case int) or an object of any class. The name of the return type can be any of the eight primitive types defined in Java, the name of any class, or an interface.
If a method doesn't return a value, you can't assign the result of that method to a variable.
If a method returns a value, the calling method may or may not bother to store the returned value from a method in a variable.
I'm new to stack overflow so sorry for anything that might consider me a newbie.
I understand java to a certain degree, however, i am stuck on one thing i hope you guys can help me on.
I am in the process of making a floating point simulator and i am struggling on this section of the code.
I need the next part of the array [1] to reach the total length of the mantissa my knowledge with arrays in java are not exactly the best so any help would be much appreciated.
Thanks
public float toDecimal()
{
/**
* Convert Exponent and find shift
*/
char[] mantissaCharArray = mantissa.toCharArray();
int mantissaLength = mantissaCharArray.length;
float[] mantissaMultiplierArray = new float[mantissaLength];
mantissaMultiplierArray[0]= 1;
for (mantissaMultiplierArray[1];mantissaCharArray;mantissaMultiplierArray++)
{
//for loop to cover array from [1] to the lengthmantissa
}
//each one multiply current
}
Try this,
for (int i=(int)mantissaMultiplierArray[0];i< mantissaCharArray.length;i++)
{
//
}
mantissaMultiplierArray[0] will return float value.
So you want to run through each element of an array? You are right with the for loop, just wrote it wrong. It should go something like this;
for(int i = (int)mantissaMultiplierArray[0]; i < mantissaCharArray.length; i++)
{
System.out.println(mantissaMultiplierArray[i]);
}
Let me explain the setup of this for loop a bit more;
You are setting an integer value i to the first value of mantissaMultiplierArray. You are also parsing it as an int because it is a float, hence the (int)
You give i a limitation - the total size of the mantissaCharArray
increment i
In the for loop I have it set to print out the values of the mantissaMultiplierArray for each value of i, but yu can do whatever you want inside of it.
Good evening people,
I have a method that creates, populates, and returns an array to the function call as so:
public double[] getTotalDistances(){
double[] distance;
distance = new double[3];
for(Activity r: diary ){
if(r instanceof Run){
distance[0] += r.getDistance();
}
}
return distance;
}
and i can't seem to find a way to access this returned array to print it out in the main method, i have tried this: (where m is the object i have instantiated)
for(int i = 0; i< m.getTotalDistances().length; i++){
System.out.println(m.getTotalDistances().distance[i]);
}
this says it cannot find the variable distance.
i am aware that i can do something like:
for(double i: m.getTotalDistances()){
System.out.println(i);
}
this will print out the returned array, however, i would like to know how to do it in the "classic" way.I know that this must be extremely novice, but i couldn't find an answer. Any kind of help will be greatly appreciated.
It should be m.getTotalDistances()[i] and not m.getTotalDistances().distance[i]
Use a variable to store it before iterating.
double[] distance = m.getTotalDistances();
for(int i = 0; i < distance.length; i++){
System.out.println(distance[i]);
}
Your approach would call your getTotalDistances() method over and over inside the loop. You only need it once to work with.
You get this error
this says it cannot find the variable distance.
because the variable distance is only known in the scope of your method getTotalDistances() and thus you cannot use it outside of that (and it wouldn't make sense either).
The way it is written, distance is not defined. You will need to create a pointer the the returned value if you want to reference it.
double[] distance = getTotalDistances();
for(int i = 0; i < distance.length; i++) {
System.out.println(distance[i]);
}
Also, as it is written, any values other than the first will always be 0, and an accumulator makes more sense.
Another thing to note is that, as it is written, getTotalDistances() will run twice on each iteration of your for loop; once for the condition and again for the println(). If you were to scale this concept to a larger use case, the performance implications would be huge.
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I have been trying for weeks in this project where I have to make one class that generates 500 random numbers from 1-250 and in a second class I have to inherit the first class properties and write all those numbers in a text file but when I have being having problems getting the properties and work with it and I haven't found a way to do it online.
My First class is
import java.util.Random;
public class GenKeys {
public static void random(){
for (int i = 0; i < 250; i++) {
int x = (int) (Math.random() * 100);
}
}
}
and my second code is
import java.util.Random;
import java.io.*;
import java.lang.*;
public class MainProg extends GenKeys{
public static void main(String[] args){
public static void random(){
try {
BufferedWriter out = new BufferedWriter(new FileWriter("file.txt"));
out.write( x + System.getProperty("line.separator"));// when i compile the x is not found!!!
out.close();
} catch (IOException e) {
System.out.print(e);
}
}
How can I make the two classes work together?
What am i doing Wrong ?
You are using inheritance instead of just using an instance of GenKeys in MainProg
You keep overwriting your random values, since you only use a single variable x, when you should be using e.g. an array
You create 250 values in range [0..99] instead of 500 values in range [1..250]
You don't store or return anything from your random() method
and i havent found a way to do it online.
I'm not sure you've looked hard enough.
How to get your code working
Firstly, you want to change the type and name of your method to an int.
public static int randomNum()
Then, remove the loop from the code, and just return the random number generated:
return (int)Math.Random() * 100; //By the way there is a Random class.
In the random method, you want the loop:
for(int x = 0; x < 250; x++)
{
BufferedWriter out = new BufferedWriter(new FileWriter("file.txt"));
out.write( randomNum() + System.getProperty("line.separator"));
}
out.close();
The various issues with your code
You're mis-using inheritance here. Your class is not a type of GenKey. It simply uses it, so it should be a field in your class.
Secondly, a method can only return one value, or one object. It can not return 250 numbers as is. You're assigning 250 numbers to x. This is only going to store the last number generated.
I don't think this is right approach. you need another class, for example KeyWriter to inherit from GenKeys. let it use GenKeys method random (it doesn't need to be static)
also, your random method is wrong, you only generate 250 keys instead of 500, and they are not from 0 to 250.
my solution is:
1) inherit KeyWriter from GenKeys
2) modify random to return only 1 generated number using nextInt
3) use cycle inside KeyWriter to call random 500 times and write those values into a file
4) use KeyWriter class inside you main method
I don't post the actual solution, cause it looks like you're doing your homework.
Well, somethings aren't correct here, but the weirdest of all is that you made the random() function a void.
void random()
Where X goes to? You just create a new int, but do nothing about it.
Besides this, there are other problems, as other folks mentioned around.
I'd recommend you to read about function in Java, especially about the difference between int and void.
Some problems (and comments) I see of the bat:
x is not an instance field and is not stored anywhere thus how can it be accessible from the child class.
Like others have said x is being overwritten with each iteration of your for loop.
Why is the mainProg.random() method declared inside of the mainProg.main() method?
I dont think inheritance is the way to go unless it is absolutely required for this project. Why not just make an instance of your random class inside the main method of the mainProg class?
If you want to use inheritance I believe a call to super.random() will be necessary inside of the mainProg.random() method.(Please someone confirm this. Im not 100% sure)
If it was me I would do something along the lines of this in my GenKeys.random() method:
public int[] random() {
int[] keys = new int[500];
for(int i = 0; i < 500; ++i)
{
keys[i] = (int) (Math.random() * 100);
}
return keys;
}
This code creates and returns an array of 500 keys. NOT in the range of 1-250. See here for that: How do I generate random integers within a specific range in Java?
Hopefully that will get you started on the right track.
x is the local variable of random().
so you can't directly access local variable out side the class.
And you are trying to generate 500 random no. between 1-250 so change the for loop in first class
for (int i = 0; i < 500; i++){
.....
}