Field with random int value - java

I'm writing a program that simulates simple bank account activities and I was wondering how to do it so that if I create a new Account without any parameters, it receives random 7digit identification number that is shown as String. The way I do, I only receive java.util.Random#2a0364ef in output.
Looking forward to any help and additional comments on this question as it is the first one I've posted on this website.
import java.util.Random;
class Account {
String id;
double stan;
int num;
static int counter;
public Account() {
**id = randomId().toString();**
stan = 0;
num = ++counter;
}
public Account(String id) {
this.id = id;
stan = 0;
num = ++counter;
}
public Account(String id, double mon) {
stan = 0;
this.id = id;
this.stan = mon;
num = ++counter;
}
**static String randomId() {
Random rand = new Random(7);
return String.valueOf(rand);**
}
String getId() {
return id;
}
double getStan() {
return stan;
}
int getNum() {
return num;
}
#Override
public String toString() {
return "Account's id " + getId() + " and balance " + getStan();
}
}
public class Exc7 {
public static void main(String[] args) {
Account account = new Account("0000001"),
acount0 = new Account("0000002", 1000),
acount1 = new Account();
System.out.println(account + "\n" + account0 + "\n" + account1);
}
}

Change return String.valueOf(rand);
To
return String.valueOf(rand.nextInt());
Reason:
You are passing random Object to valueOf method, not the value you need. Call nextInt() method on it to get the desired random value.

Use this code:
Random rand = new Random(7);
return String.valueOf(Math.abs(rand.nextInt()));
Right now you are representing the Random instance.
Instead printing the String representation of the mathematical absolute of the next int of your random will do the trick.
The Math.abs part is important, otherwise you might have negative numbers.

Use
return String.valueOf(rand.nextInt());
otherwise you will get the string representation of the Random object and not of a random int that it can produce.

Related

Generate a random integer on an interval

So I have this class called Organism:
public class Organism implements Comparable{
// Represents the organisms guess for the unknown string
String value;
// String the organism is trying to guess
String goalString;
int n;
public Organism(String goalString) {
this.goalString = goalString;
this.value = goalString;
}
public Organism(String value, String goalString, int n) {
this.goalString = goalString;
this.value = value;
this.n = n;
}
public int fitness(){
// Represents the fitness of the organism
int count = 0;
for(int i = 0; i < goalString.length(); i++) {
if(value.charAt(i) == goalString.charAt(i)) {
count ++;
}
}
return count;
}
public Organism[] mate(Organism other) {
// Generate a random integer from [0, n-1]
int crossOver;
return new Organism[0];
}
#Override
public int compareTo(Object o) {
return 0;
}
public void mutate(double mutateProb) {
}
#Override
public String toString() {
return "Value: " + value + " " + "Goal: " + goalString + " " + "Fitness: " + fitness();
}
public String getValue() {
return value;
}
public String getGoalString() {
return goalString;
}
public int getN() {
return n;
}
}
Inside of the mate method I need to generate a random integer on the interval [0, n-1] where n is the length of value and goalString. I then need to store that inside of the crossOver variable inside of the mate method. What would be the best way to do that?
This should do the thing:
int n = other.getValue().length() + other.getGoalString().length();
Random rand = new Random();
int crossOver = rand.nextInt(n);
If you meant n should be the sum of the value and goalStrng of the current (this) object, simply remove the other. or replace it with this..
All have to be placed in the public Organism[] mate(Organism other) method.

How can I produce unique values of Object via Random Process in Java

I want to produce unique values of Movie Object via Random. I wrote a code snippet but I'm not sure all values cannot be unique by using Random().
How can I do this process to produce all of these unique values?
Here is my code snippets shown below.
private static ArrayList<Movie> addMovies(ArrayList<Movie> movieList) {
for(int i=0;i<20;i++) {
Movie movie = new Movie();
movie.setId(defineMovieId());
movie.setTitle(defineMovieName(15));
movieList.add(movie);
}
return movieList;
}
public static String defineMovieName(int n) {
// chose a Character random from this String
String AlphaNumericString = "ABCÇDEFGHIİJKLMNOÖPQRSŞTUÜVWXYZ"
+ "abcçdefghıijklmnoöpqrsştuüvxyz";
StringBuilder sb = new StringBuilder(n);
for (int i = 0; i < n; i++) {
int index
= (int)(AlphaNumericString.length()
* Math.random());
sb.append(AlphaNumericString
.charAt(index));
}
return sb.toString();
}
public static long defineMovieId() {
int max = 1000;
int min = 1;
int range = max - min + 1;
int res = (int) ( Math.random()*range) + min;
return res;
}
The methods which you have defined do not guarantee random IDs or random names. For guaranteed unique values, you can do the following:
For unique ID: create a static variable of AtomicLong type and use getAndIncrement()
For unique names: use UUID.randomUUID()
Demo:
import java.util.UUID;
import java.util.concurrent.atomic.AtomicLong;
public class Main {
static final long INITIAL_VALUE = 1000000;
static AtomicLong atomicLong = new AtomicLong(INITIAL_VALUE);
public static void main(String[] args) {
// Tests
System.out.println("10 random IDs:");
for (int i = 1; i <= 10; i++) {
System.out.print(defineMovieId() + " ");
}
System.out.println();
System.out.println("10 random movie names:");
for (int i = 1; i <= 10; i++) {
System.out.print(defineMovieName() + " ");
}
}
public static long defineMovieId() {
return atomicLong.getAndIncrement();
}
public static String defineMovieName() {
return UUID.randomUUID().toString().replace("-", "");
}
}
Output:
10 random IDs:
1000000 1000001 1000002 1000003 1000004 1000005 1000006 1000007 1000008 1000009
10 random movie names:
0c77d209fb624415af7100c3184b35a6 1262e50b680f4a738a607ff757f2b510 7b93c73d93b34db88fc99d1096c1ce84 cbb9c6c90fb8489dbd9c52d4ebdc2ca3 9ba1d409b32b4c55a7562d714aadc220 ec40b647f33a4fc6becc8c5741eb8bf7 c1fbb7bb77d1417c86c2064039f62dec 82b52fdae1d24602b5ee9becd73ba3ce 2d82d481282b4684b55c168e9d216f36 27b02bf63b054d32a0e43992a5fcb124
Random is not generate a series of unique numbers, just if get lucky.
Better use a static int field for id and increase it each time you need a new id.
//classes names are obvious fake since there are not any random involved, just an example
public class TestRandom {
static int id=0;
public static void main(String[] args)
{
TestRandom tr = new TestRandom();
RandomIdObj ro1 = tr.new RandomIdObj(tr.getNextId(),"obj_1");
RandomIdObj ro2 = tr.new RandomIdObj(tr.getNextId(),"obj_2");
System.out.println(ro1);
System.out.println(ro2);
}
public int getNextId()
{
return ++id;
}
class RandomIdObj
{
int id;
String name;
RandomIdObj(int id,String name)
{
this.id =id;
this.name = name;
}
public String toString()
{
return this.id+":"+this.name;
}
}
}
Output:
[unique_id,obj_name]
1:obj_1
2:obj_2

The for loop in the method gets skipped when 3rd entry goes in. JAVA

When I run this code, for some reason when it hits test10 to be added into the Array sort, the addListing method ignores the for loop and just skips to the bottom. I am curious why the for loop runs for test2.addListing(test); and test2.addListing(test9); but not for the one after.
import java.util.Scanner;
public class TestListings {
public static void main(String[] args) {
StudentListings test = new StudentListings();
StudentListings test9 = new StudentListings();
StudentListings test10 = new StudentListings();
test.input();
test9.input();
test10.input();
Scanner sc = new Scanner(System.in);
int aSize = 0;
System.out.print("Enter Array Size: ");
aSize = Integer.parseInt(sc.nextLine());
ArraySort test2 = new ArraySort(aSize);
test2.addListing(test);
test2.addListing(test9);
test2.addListing(test10);
test2.showAllListings();
}
}
This is the method written, and it runs for the first run through, next = 0; intially, but the 3rd time (in test10) it just looks at the line and skips it.
public class ArraySort
{
private StudentListings[] data;
private int size = 0;
private int next = 0;
public ArraySort()
{
data = new StudentListings[size];
size = 0;
next = 0;
}
public ArraySort(int ArraySize)
{
size = ArraySize;
data = new StudentListings[size];
next = 0;
}
public void addListing(StudentListings newListing)
{
System.out.print(next);
for(i = next - 1; i <= 0; i--)
{
try {
if (newListing.compareTo(data[i].getLName()) < 0)
{
data[i+1] = data[i].deepCopy();
}
else
{
data[i+1] = newListing;
next++;
break;
}
}
catch(ArrayIndexOutOfBoundsException | NullPointerException exception)
{
int x = i + 1;
data[x] = newListing;
next++;
break;
}
}
System.out.print(next);
}
public void showAllListings()
{
for(int i = 0; i < next; i++)
{
System.out.println((i + 1) + ". " + data[i]);
}
}
}
This is the class that is getting created to be inserted into the array.
import java.util.Scanner;
public class StudentListings {
private String firstName;
private String lastName;
private int id;
private double gpa;
public StudentListings()
{
firstName = "";
lastName = "";
id = 0;
gpa = 0.0;
}
public StudentListings(String firstName, String lastName, int id,
double gpa)
{
this.firstName = firstName;
this.lastName = lastName;
this.id = id;
this.gpa = gpa;
}
public void setName(String firstName, String lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}
public String getName()
{
return firstName + " " + lastName;
}
public void setId(int id)
{
this.id = id;
}
public int getId()
{
return id;
}
public void setGpa(double gpa)
{
this.gpa = gpa;
}
public double getGpa()
{
return gpa;
}
public String getLName()
{
return lastName;
}
public void input()
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter First Name: ");
this.firstName = sc.nextLine();
System.out.print("Enter Last Name: ");
this.lastName = sc.nextLine();
System.out.print("Enter Student ID: ");
this.id = sc.nextInt();
System.out.print("Enter Student GPA: ");
this.gpa = Double.parseDouble(sc.next());
}
public String toString()
{
return "Last Name: " + lastName + " First Name: " + firstName + " ID:
" + id + " GPA: " + gpa;
}
public StudentListings deepCopy()
{
StudentListings clone = new StudentListings(firstName, lastName, id,
gpa);
return clone;
}
public int compareTo(String targetKey)
{
return(lastName.compareTo(targetKey));
}
}
If next is 0 the first time then it’s 2 the third time and i starts at 1 so the condition i <= 0 is false from the start
I'm not solving that problem, because in my opinion you're trying to do (intricately) something already defined in Java. When you create a class, and have to manage an array of object of that class, Java offers a very simple way to do that, I'll explain what I would do in your position step by step:
1 - The first thing to do is to define the comparison between the object belonging to that class, you can achieve that by overriding the method compareTo of that class (the class has to implement Comparable <YourObject>); in your case i guess it schould be something like:
public class StudentListings implements Comparable<StudentListings>{
...
#Override
public int compareTo(StudentListings element){
return ...;
}
}
In which you define when a StudentListing object is bigger than another.
2 - The second thing to do is to define an ArrayList<StudentListings> in your main, and initialize it:
ArrayList<StudentListings> yourArray = new ArrayList<>();
3 - Then you have to add the elements to that array (obviously after you initialized them):
yourArray.add(test);
yourArray.add(test9);
yourArray.add(test10);
4 - Now you have your array, not sorted, to sort it you just have to call the method
Collections.sort(yourArray);
Now you have your ArrayList of StudentListings sorted.
There is another way to achieve this result, that is described here, I don't like it very much because using that way you have to redefine the comparison everytime you need to sort an array and because your main code results more complex, but it has the same result of the steps I explained (therefore the linked method is useful if you have to sort two different arrays of the same class objects in different ways, eg. one by students name and the other by students surname).

Constructor isn't printing as expected

public class Fraction
{
public Franction(int n, int d)
{
int num = n;
int denom = d;
}
public static void main(String[] args)
{
Fraction f1 = new Fraction(5,10);
System.out.println("Fraction = " + f1);
}
}
Hello, I'm trying to learn Java... The book I'm working out of suggests that the output of the code above should print "Fraction = 5/10", but when I try it I just receive "Fraction = Fraction#33469a69" which I assume is printing the reference to where it is stored? I understand how it is suppose to work with the constructor I just don't receive the expected output. Any help would be greatly appreciated... Thanks!
To get the desired output, you need to overload toString() method in the Franction class. This method is used to determine textual representation of the object. By default, it is ClassName#hashCode.
Also, you probably would like to store the values you receive in the constructor as fields. Right now, you store the numerator and denominator in constructor's local variables, that are destroyed as soon as the constructor exits.
Try something like this:
public class Fraction
{
private final int num
private final int denom;
public Franction(int n, int d)
{
this.num = n;
this.denom = d;
}
#Override
String toString()
{
return String.format("%d/%d", num, denom);
}
public static void main(String[] args)
{
Fraction f1 = new Fraction(5,10);
System.out.println("Fraction = " + f1);
}
}
You need to override the toString method for the same
public String toString(){
StringBuilder stringToReturn = new StringBuilder();
stringToReturn.append(this.num);
stringToReturn.append("/");
stringToReturn.append(this.denom);
return stringToReturn.toString();
}
You have to override the toString() function in your Fraction class.
As per docs of toString()
Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object.
So
Fraction#33469a69 is the textual representation of Fraction class.
To get the required output, write the logic in overridden toString method in Object class and return the string there.
A simple toString implementation looks like
#Override
public String toString() {
StringBuilder result = new StringBuilder();
result.append(this.someMemeber); //will be in String format
result.append(this.someMemeber);
return result.toString();
}
Try this
public class Fraction
{
private int num;
private int denom;
public Franction(int n, int d)
{
num = n;
denom = d;
}
public int getNum()
{
return num;
}
public int getDenom()
{
return denom;
}
public static void main(String[] args)
{
Fraction f1 = new Fraction(5,10);
System.out.println("Fraction = " + f1.getNum() + "/" + f1.getDenom());
}
}
Alternative (Better way to do this)
public class Fraction
{
private int num;
private int denom;
public Franction(int n, int d)
{
num = n;
denom = d;
}
public int getNum()
{
return num;
}
public int getDenom()
{
return denom;
}
#Override
public String toString(){
return (f1.getNum() + "/" + f1.getDenom());
}
public static void main(String[] args)
{
Fraction f1 = new Fraction(5,10);
System.out.println("Fraction = " + f1 );
}
}
You need to study more about encapsulation , the Object class and the toString() method.
Happy Coding :)
Try the following:
public class Fraction {
private final int num;
private final int denom;
public Fraction(int num, int denom) {
this.num = num;
this.denom = denom;
}
#Override
public String toString() {
return num + "/" + denom;
}
public static void main(String[] args) {
Fraction f1 = new Fraction(5, 10);
System.out.println("Fraction = " + f1);
}
}
You have to store the values in the object you create. Then override the toString method of Object to get your desired output.
Output:
Fraction = 5/10
All you are doing is printing out the Object.
If you want to print the contents of the Object you will to create a toString method in you class.
see http://www.javapractices.com/topic/TopicAction.do?Id=55

Java program grading

I've been working on this program for hours and I can't figure out how to get the program to actually print the grades from the scores Text file
public class Assign7{
private double finalScore;
private double private_quiz1;
private double private_quiz2;
private double private_midTerm;
private double private_final;
private final char grade;
public Assign7(double finalScore){
private_quiz1 = 1.25;
private_quiz2 = 1.25;
private_midTerm = 0.25;
private_final = 0.50;
if (finalScore >= 90) {
grade = 'A';
} else if (finalScore >= 80) {
grade = 'B';
} else if (finalScore >= 70) {
grade = 'C';
} else if (finalScore>= 60) {
grade = 'D';
} else {
grade = 'F';
}
}
public String toString(){
return finalScore+":"+private_quiz1+":"+private_quiz2+":"+private_midTerm+":"+private_final;
}
}
this code compiles as well as this one
import java.util.*;
import java.io.*;
public class Assign7Test{
public static void main(String[] args)throws Exception{
int q1,q2;
int m = 0;
int f = 0;
int Record ;
String name;
Scanner myIn = new Scanner( new File("scores.txt") );
System.out.println( myIn.nextLine() +" avg "+"letter");
while( myIn.hasNext() ){
name = myIn.next();
q1 = myIn.nextInt();
q2 = myIn.nextInt();
m = myIn.nextInt();
f = myIn.nextInt();
Record myR = new Record( name, q1,q2,m,f);
System.out.println(myR);
}
}
public static class Record {
public Record() {
}
public Record(String name, int q1, int q2, int m, int f)
{
}
}
}
once a compile the code i get this which dosent exactly compute the numbers I have in the scores.txt
Name quiz1 quiz2 midterm final avg letter
Assign7Test$Record#4bcc946b
Assign7Test$Record#642423
Exception in thread "main" java.until.InputMismatchException
at java.until.Scanner.throwFor(Unknown Source)
at java.until.Scanner.next(Unknown Source)
at java.until.Scanner.nextInt(Unknown Source)
at java.until.Scanner.nextInt(Unknown Source)
at Assign7Test.main(Assign7Test.java:25)
Exception aside, you actually are printing objects of type Record. What you would need to do is override toString() to provide a decent representation of your object.
#Override
public String toString() {
return "Something meaningful about your Record object.";
}
I also note that you're advancing the Scanner by use of nextLine() in System.out.println('...'). You may want to comment that part out of your code.
The reason you are getting this error is because of the fact that you are expecting an integer, but the next thing your scanner reads is not a number.
Also, put this in your toString of your record to stop printing out addresses.
i.e.
public static class Record {
public Record() {
}
public Record(String name, int q1, int q2, int m, int f)
{
}
public String toString(){}//print out stuff here.
}
change your Record to something like this
public static class Record {
String name;
int q1;
int q2;
int m;
int f;
public Record() {}
public Record(String name, int q1, int q2, int m, int f) {
// here you save the given arguments localy in the Record.
this.name = name;
this.q1 = q1;
this.q2 = q2;
this.m = m;
this.f = f;
}
#Override
public String toString(){
//here you write out the localy saves variables.
//this function is called when you write System.out.println(myRecordInstance);
System.out.println(name + ":" + q1 + ":" + q2 + ":" + m + ":" + f);
}
}
What it does: you have to save the argments by creating the Record.
Additional you have to override the toString method if you want to use System.out.println(myRecordInstance); instead you could write an other function returning a String in your Record and print out the return values of this function like System.out.println(myRecordInstace.writeMe()); Then you ne to add the function to the record.
public String writeMe(){
System.out.println(name + ":" + q1 + ":" + q2 + ":" + m + ":" + f);
}

Categories