In an arbitrary class, I decided to make a method for making a divider based on the character you want the divider made out of, and the amount you want.
public String divider(String s, int amount){
StringBuilder repeated = new StringBuilder();
for(int i = 0; i < amount; i++){repeated.append(s);}
return repeated.toString();
}
The method is defined in the Catalog class.
And I'm calling it as
this.divider("-", 10);
in the toString() of the class. And I'm calling it in the main method as
mainCat.divider("-", 10)
mainCat is a Catalog object.
I've tried a bunch of different ways of multiplying a string by itself in a loop to make copies of itself but they all come up blank for me. Any suggestions would be appreciated, thanks!
You better just use StringUtils.repeat(str, count).
Related
Is it possible to know/get how much space/memory are used when a method is executed or when there is a return value? I don't want to know how much space used by the app, just some code like method or the return value. I tried the runtime.getRuntime, but from my understanding, It looks like it tells me how much space is used by the entire code/app, am I right?
EDIT :
public int [] randtotal(int times2)
{
int in1[] = new int[times2];
for (int i = 0; i<Num2; i++)
Random rand = new Random();
{
in1[times2]= rand.NextInt(5);
}
totalNum(in1);
return int1;
}
As you can see here, at the end of the code there is the "return int1;" , so I want to know when these code is executed how much space is allocated for the value here?
You can use Visualvm tool to profile the overall application and you can also profile certain package, class or function
see this link :
https://visualvm.java.net/profiler.html
I'm confusing myself here. My goal was to make a simple program that took the number of values the user wants to average, store them in an array (while adding them together) and finally giving the average of these numbers.
My thing is, I am trying to understand the concept of multiple classes and methods as I am new so I tried using another class just do do all the work, while the Main class would just create the object from the other class, and then run their methods. Maybe I am asking something impossible. Take a look at my code.
This is my Main class:
public class Main
{
public static void main(String[] args)
{
System.out.println("Please enter numbers to average together");
OtherClass averages = new OtherClass();
averages.collectNumbers();
averages.AverageNumbers();
}
}
Now I am not sure if anything goes in those parameters, or if I can even use "averages.AverageNumbers();" without creating another object with "OtherClass" called something else? I am pretty sure it's legal though.
Here is my other class for this project entitled "OtherClass"
import java.util.Scanner;
public class OtherClass // using this to name obj
{
public void collectNumbers() //name of our method that does things
{
Scanner sc = new Scanner(System.in);
System.out.println("how many integers would you like to average? ");
int givenNum = sc.nextInt();
System.out.println("Alright, I will average " + givenNum + " values. \nPress enter after each:");
int[] numCollect = new int[givenNum];
int sum = 0;
for (int i = 0; i < numCollect.length; i++)
{
numCollect[i] = sc.nextInt();
sum = sum + numCollect[i];
}
System.out.println(sum);
}
public int AverageNumbers(int givenNum, int sum)
{
int average = sum / givenNum;
System.out.println(average);
return average;
}
}
So when I run this now with the the method AverageNumbers, it does not work. I am suspecting that maybe I am passing in the integers wrong? I have been toying with it for about an hour now, so I am asking for help. How do I make this work?
This will work if you declare sum and givenNum as fields of your OtherClass, instead of as local variables. So, before the collectNumbers method, write
private int sum;
private int givenNum;
and remove the declarations of these two variables inside collectNumbers. So, for example, instead of
int givenNum = sc.getInt();
you'll just have
givenNum = sc.getInt();
because the variable already exists. Also change the declaration of the averageNumbers method to
public int averageNumbers()
because you no longer need to pass those two values in to this method.
This is the archetypical example of using the objects of a class to carry a small amount of data around, instead of just using a class as a way to group methods together. The two methods of this class work with sum and givenNum, so it makes sense to store these in each object of this class.
Lastly, in your averageNumbers method, you have an integer division, which will automatically round down. You probably want a floating point division instead, so you could write
double average = (double) sum / givenNum;
which converts sum to a double-precision floating point number before the division, and therefore does the division in floating point, instead of just using integers. Of course, if you make this change, you'll need to change the return type of this method to double too.
I'm attempting to generate a random four digit number with no repeating digits. I have a method to generate the number and two to check for length and repetition. It compiles and works as expected, however, occasionally, I will get a StackOverflowError while it is running. Here is the block of code where it seems to be having a problem with:
//ensures that generated pattern is four digits long
public void randomCheck(){
int patternNum = Integer.parseInt(pattern);
if(patternNum<1000){
numGen();
}
else{
repeatCheck();
}
}
//ensures that pattern is unique
public void repeatCheck(){
solutionNumber();
if((secondSolnDigit==firstSolnDigit)||(firstSolnDigit==thirdSolnDigit)||
(firstSolnDigit==fourthSolnDigit)||(secondSolnDigit==thirdSolnDigit)||
(secondSolnDigit==fourthSolnDigit)||(thirdSolnDigit==fourthSolnDigit)){
numGen();
}
else{
return pattern;
}
}
//generates random number
public void numGen();{
Random rand = new Random();
int randomNum = rand.nextInt(10000);
String patternString = Integer.toString(randomNum);
pattern = patternString;
randomCheck();
}
The stack overflow error happen when a there is too many method call in each other. It generally happen in recursive methods. Here it happens because you call numGen() from randomCheck() and repeatCheck() then numGen() call back randomCheck().
The solution here is to test in a while loop, remove you method randomCheck() and replace your code by:
//ensures that pattern is unique AND four digits long
public void repeatCheck(){
solutionNumber();
int patternNum = Integer.parseInt(pattern);
while((secondSolnDigit==firstSolnDigit)||(firstSolnDigit==thirdSolnDigit)||
(firstSolnDigit==fourthSolnDigit)||(secondSolnDigit==thirdSolnDigit)||
(secondSolnDigit==fourthSolnDigit)||(thirdSolnDigit==fourthSolnDigit) || patternNum<1000){
numGen();
}
return pattern;
}
//generates random number
public void numGen();{
Random rand = new Random();
int randomNum = rand.nextInt(10000);
String patternString = Integer.toString(randomNum);
pattern = patternString;
}
Moreover why do you cast your integer in string and then cast it back in integer, can't you just use the int as it is generated? and convert it after if you really need it as a string.
Hope this helped.
StackOverflowError is when you have to many method calls stacked on one another. There is a limit in Java to how many method calls can be stacked on one another.
You are calling randomCheck() from your numGen() method and calling numGen() from your randomCheck() method this appears to be the problem. Your code is probably chasing it's own tail. If numGen() is not called from randomCheck() then repeatCheck() is which also calls numGen().
It may work fine sometimes if it reaches the end of method calls before the stack runs out of space. But in some cases it is making more method calls than others adding more calls to the stack and eventually running out of space. That is why it works sometimes and not others.
You could try using a loop to accomplish the same thing. This way you won't have to worry about StackOverflowError.
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++){
.....
}
Looks like this is the week for this type of question. And after reading through all of the new ones and several old ones, I'm no less confused!
I have a text file with 5 employees, each having 10 salary values listed beneath their name. I am to read in this file, find and display the employee Name, minimum salary, maximum salary and the average salary for each person. I must have 3 loops: One to control reading the file, one to lad the data into the array, and one to do the calculations. I have to print the information for each person on one line, and i must allow decimals rounded to 2 decimal places apparently using Math.round which I've never heard of!
I am embarrassed to show you the mess of code I have because it's not much, but I don't know after reading all that I have if I've even started correctly. I do not know if I have even the right idea of how to proceed. Your help is appreciated.
UPDATED CODE: AGAIN!
import javax.swing.*;
import java.io.*;
public class MinMaxSalary3
{
public static void main(String args[])throws Exception
{
// Declare input file to be opened.
FileReader fr = new FileReader ("salary.dat");
BufferedReader br = new BufferedReader (fr);
//General Declarations
final String TITLE = "Employee's Salary Report";
String employeeName, salaryString;
double avgSalary=0.0;
double totalSalary = 0.0;
double sum = 0.0;
// Declare Named Constant for Array.
final int MAX_SAL = 10;
// Declare array here.
int salary[] = new int[MAX_SAL];
System.out.println (TITLE);
while ((employeeName = br.readLine()) != null)
{
System.out.print ("" + employeeName);
// Use this integer variable as your loop index.
int loopIndex;
// Assign the first element in the array to be the minimum and the maximum.
double minSalary = salary[1];
double maxSalary = salary[1];
// Start out your total with the value of the first element in the array.
sum = salary[1];
// Write a loop here to access array values starting with number[1]
for (loopIndex = 1; loopIndex < MAX_SAL ;loopIndex++)
// Within the loop test for minimum and maximum salaries.
{
if (salary[loopIndex] < minSalary)
{
minSalary = salary[loopIndex];
if (salary[loopIndex] > maxSalary)
maxSalary = salary[loopIndex];
}
{
// Also accumulate a total of all salaries.
sum += sum;
// Calculate the average of the 10 salaries.
avgSalary = sum/MAX_SAL;
}
// I know I need to close the files, and end the while loop and any other loops. I just can't think that far right now.
}
{
// Print the maximum salary, minimum salary, and average salary.
System.out.println ("Max Salary" + maxSalary);
System.out.println ("Min Salary" + minSalary);
System.out.println ("Avg Salary" + avgSalary);
}
System.exit(0);
}
}
}
I must have 3 loops: One to control reading the file, one to lad the
data into the array, and one to do the calculations.
What I've written below might just be more gobbledygook to you now, but if you ever get past this class it might be useful to know.
Another way to look at this would be more object-oriented and better decomposition to boot: You need an object to hold the data, to perform the calculations, and render output. How you get that data is immaterial. It's files today; next time it might be HTTP requests.
Start with an Employee object. I deliberately left out a lot of detail that you'll have to fill in and figure out:
package model;
public class Employee {
private String name;
private double [] salaries;
public Employee(String name, int numSalaries) {
this.name = name;
this.salaries = new double[numSalaries];
}
public double getMinSalary() {
double minSalary = Double.MAX_VALUE;
// you fill this in.
return minSalary;
};
public double getMaxSalary() {
double maxSalary = Double.MIN_VALUE;
// you fill this in.
return maxSalary;
}
public double getAveSalary() {
public aveSalary = 0.0;
if (this.salaries.length > 0) {
// you fill this in.
}
return aveSalary;
}
}
The beauty of this approach is that you can test it separately, without worrying about all the nonsense about file I/O. Get this object right, put it aside, and then tackle the next piece. Eventually you'll have a clean solution when you assemble all these smaller pieces together.
Test it without file I/O using JUnit:
package model;
public class EmployeeTest {
#Test
public void testGetters() {
double [] salaries = { 10000.0, 20000.0, 30000.0, 40000.0 };
Employee testEmployee = new Employee("John Q. Test", salaries);
Assert.assertEquals("John Q. Test", testEmployee.getName());
Assert.assertEquals(10000.0, testEmployee.getMinSalary(), 1.0e-3);
Assert.assertEquals(40000.0, testEmployee.getMaxSalary(), 1.0e-3);
Assert.assertEquals(25000.0, testEmployee.getMinSalary(), 1.0e-3);
}
}
The approach you would want to espouse in this situation is an object-oriented approach. Bear in mind that objects are a representation of related data. Consider that an Employee may have information about their salary, name, and what department they work in (as an example).
But that's just one Employee. You may have hundreds.
Consider creating a model of an Employee. Define what is most pertinent to one of them. For example, they all have to have a name, and have to have a salary.
One would then elect to handle the logic of finding information about the collection of Employees - including min, max, and average salaries - outside of the scope of the generic Employee object.
The idea is this:
An Employee knows everything about itself.
The onus is on the developer to tie multiple Employees together.
It's possible that I don't know enough about what your problem is specifically looking for - I'm not even sure that you can use objects, which would really suck - but this is definitely a start.
As for your compilation errors:
salary is a double[]. An array holds many different values of type double inside of it, but a double[] isn't directly a double. Assigning a non-array type to an array type doesn't work, from both a technical stance, and a semantic stance - you're taking something that can hold many values and trying to assign it to a container that can hold one value.
From your code sample, you want to use a loop (with a loop variable i) to iterate over all elements in salary, and assign them some value. Using just salary[0] only modifies the first element.