Write a program that asks for the names of three runners and the time, in minutes, it took each of them to finish a race. The program should display the names of the runners in the order that they finished.
The program works for whole numbers but is unable to arrange decimals. If I change the variable to integers, the input causes an error. Is there a solution for this?
import java.util.Arrays;
import java.util.Scanner;
class Runners implements Comparable<Runners> {
public String name;
public double time;
public Runners(String name, double time) {
this.name = name;
this.time = time;
}
public String toString() {
return String.format(" %s: %.2f minute(s) ", name, time);
}
public int compareTo(Runners other) {
return (int) (this.time - other.time);
}
}
public class Question2 {
public static void main(String[] args) {
int count = 3;
Runners[] runnersData = new Runners[count];
Scanner input = new Scanner(System.in);
for (int i = 0; i < count; i++) {
System.out.println("Enter runner's name and time taken in minutes: ");
runnersData[i] = new Runners(input.next().strip(), input.nextDouble());
}
input.close();
Arrays.sort(runnersData);
System.out.println(Arrays.toString(runnersData));
}
}
The unsorted decimals:
The error if changed to int:
compareTo doesn't require you to return the results of your arithmetic. You only have to return an integer signifying whether the items are equal, greater or less than.
public int compareTo(Runners other) {
if(this.time == other.time)
return 0;
else if(this.time > other.time)
return 1;
else
return -1;
}
See the documentation on compareTo here. Also be aware that comparing doubles won't always behave the way you expect. I added the above for an example usage, but you can probably just return Double.compareTo(d1, d2). See those docs.
Related
I have a Java Class named Real
public class Real {
private long wholeNumPart;
private long decimalPart;
public Real(){
wholeNumPart =0;
decimalPart=0;
}
public Real(long wholeNumPart, long decimalPart) {
this.wholeNumPart =wholeNumPart;
this.decimalPart = decimalPart;
}
public long getWholeNumPart() {
return wholeNumPart;
}
public long getDecimalPart() {
return decimalPart;
}}
I have another class name RealApplication where I need to create two methods
createRealObject() that allows a user to input a real number and creates an object representing
that number.
2.createRealNumber() which accepts an object of type Real and returns a real number represented
by that object.
I am having difficulty creating these two methods
Here is what I've done so far
import java.util.Scanner;
public class RealApplication {
public void createRealNumber() {
Scanner sc=new Scanner(System.in);
//Allows user input
System.out.print("Please, enter a real number: ");
long n = sc.nextLong();
//Creates Real object ( is this correct????)
Real in = new Real();
}
public long createRealNumber(Real num) {
long realNum=0;
//I do not know what to write here :(
return realNum;
}
}
Your Real class looks good with some changes in the RealApplication class we can achieve what you want:
import java.util.Scanner;
public class RealApplication {
public static Real createRealObject() {
Scanner sc=new Scanner(System.in);
//Allows user input
System.out.print("Please, enter a real number: ");
String n = sc.nextLine();
String[] pieces = n.split("[.,]+"); //special pattern to recognize comma and dot
long wholeNumPart;
long decimalPart;
try {
wholeNumPart = Long.valueOf(pieces[0]);
decimalPart = Long.valueOf(pieces[1]);
}
catch (NumberFormatException e) {
System.out.println("You should enter a number!");
return null;
}
Real in = new Real(wholeNumPart, decimalPart);
sc.close();
return in;
}
The important point is that I declared the both methods as static in this way you can use the methods without creating an instance of RealApplication class.
You should use "double" primitive type to store fractional numbers not "long". Now the method that returns the number equivalent of that object:
public static double createRealNumber(Real num) {
double realNum;
long wholeNumPart = num.getWholeNumPart();
long decimalPart = num.getDecimalPart();
int numOfDigits = (int)(Math.log10(decimalPart)+1);
realNum = wholeNumPart + (decimalPart / Math.pow(10,numOfDigits));
return realNum;
}
And if we write a main method:
public class Main {
public static void main(String[] args) {
Real realObj = new Real(10,2323232);
double number = RealApplication.createRealNumber(realObj);
System.out.println("Equivalent number for the object: " + number);
Real newObj = RealApplication.createRealObject();
if (newObj != null) {
System.out.println("New object's number part: " + newObj.getWholeNumPart());
System.out.println("New object's decimal part: " + newObj.getDecimalPart());
}
else{
return;
}
}
}
Because of the regex pattern we used, the inputs separated with "." and "," are allowed like 10.23 10,23 .
this is my first class for the Crackerpacker,i have created another class for the arraylist and then added all these cracker packers to that arraylist , now i want to sort the arraylist in descending order of number of boxes packed by the CrackerPackers
public class CrackerPacker {
private String name;
private int numberOfBoxes;
public CrackerPacker (String name, int numberOfBoxes){
this.name = name;
this.numberOfBoxes = numberOfBoxes;
}
public int getNumberOfBoxes() {
return numberOfBoxes;
}
public void setNumberOfBoxes(int numberOfBoxes) {
this.numberOfBoxes = numberOfBoxes;
}
public String getName() {
return name;
enter code here
}
#Override
public String toString() {
return "CrackerPacker{" +
"name='" + name + '\'' +
", numberOfBoxes=" + numberOfBoxes +
'}';
}
public double getwage() {
if ( numberOfBoxes < 51 ) {
return numberOfBoxes * 1.15;
}
else {
double wage = (57.5 + ((numberOfBoxes - 50) * 1.25));
return wage;
This is the second class in which i have created an arraylist to add all the crackerpacker objects in it
this arraylist i want sort in descending order of the number of boxes packed by the CrackerPackers
import java.util.ArrayList;
import java.util.Collections;
public class Common {
public static ArrayList<CrackerPacker> lectures = new ArrayList<>();
int sum = 0;
int boxes = 0;
public int totalWage() {
for (int i = 0; i < lectures.size(); i++) {
sum += lectures.get(i).getwage();
}
return sum;
}
public int totalBoxes() {
for (int i = 0; i < lectures.size(); i++){
boxes += lectures.get(i).getNumberOfBoxes();
}
return boxes;
This my main method , i want sort the array list in descending roder of the number of boxes packed by the objects , please show me how can do it
import java.util.Collections;
public class Main {
public static void main(String[] args) {
CrackerPacker steve = new CrackerPacker("STEVE", 127);
CrackerPacker gary = new CrackerPacker("Gary", 103);
CrackerPacker tony = new CrackerPacker("tony", 473);
CrackerPacker saad = new CrackerPacker("Saad", 129);
CrackerPacker rubiya = new CrackerPacker("rubiya", 117);
Common common = new Common();
Common.lectures.add(steve);
Common.lectures.add(gary);
Common.lectures.add(tony);
Common.lectures.add(saad);
Common.lectures.add(rubiya);
for ( CrackerPacker element : Common.lectures) {
System.out.println(element);
}
System.out.println(common.totalWage());
System.out.println(common.totalBoxes());
i think i have use the compareto method but i dont knwo how to implement it
The below compares the numberOfBoxes of the passed CrackerPacker with that of the current objects. This will have the effect of sorting it in descending order.
public class CrackerPacker implements Comparable<CrackerPacker> {
#Override
public int compareTo(CrackerPacker c) {
return Integer.compare(c.numberOfBoxes, this.numberOfBoxes);
}
}
From the javadoc,
Compares this object with the specified object for order. Returns a
negative integer, zero, or a positive integer as this object is less
than, equal to, or greater than the specified object.
Hence, when comparing two CrackerPacker objects we are reversing the Integer compare check to achieve a descending ordering.
Example: Comparing 5 and 10, we are comparing 10 with 5 and hence Integer.compare returns 1 (since 10 > 5). But from outside comparison, we are stating that the first object is bigger than the second and hence it will appear after the second (..10....5...). This sorts the list in descending order.
The following expression will help
Collections.sort(Common.lectures, (Comparator< CrackerPacker >) (o1, o2) -> Integer.compare(o1.getNumberOfBoxes(), o2.getNumberOfBoxes()));
This question already has answers here:
Error in System.out.println
(5 answers)
Closed 4 years ago.
My Task:
Create a class called Icosahedron which will be used to represent a regular icosahedron, that is a convex polyhedron with 20 equilateral triangles as faces. The class should have the following features:
A private instance variable, edge, of type double, that holds the
edge
length.
A private static variable, count, of type int, that holds the
number of Icosahedron objects that have been created.
A constructor that takes one double argument which specifies the edge length.
An
instance method surface() which returns the surface area of the
icosahedron. This can be calculated using the formula 5*√3 edge².
An
instance method volume() which returns the volume of the icosahedron.
This can be calculated using the formula 5*(3+√5)/12*edge³.
An
instance method toString() which returns a string with the edge
length, surface area and volume as in the example below:
Icosahedron[edge= 3.000, surface= 77.942, volume= 58.906]
The numbers in this string should be in floating point format with a field
that is (at least) 7 characters wide and showing 3 decimal places.
Please use the static method String.format with a suitable formatting
string to achieve this. A static method getCount() which returns the
value of the static variable count.
Finally, add the following main method to your Icosahedron class so that it can be run and tested:
public static void main(String[] args) {
System.out.println("Number of Icosahedron objects created: " + getCount());
Icosahedron[] icos = new Icosahedron[4];
for (int i = 0; i < icos.length; i++)
icos[i] = new Icosahedron(i+1);
for (int i = 0; i < icos.length; i++)
System.out.println(icos[i]);
System.out.println("Number of Icosahedron objects created: " + getCount());
}
Okay. so heres what i have started on:
import java.util.Scanner;
public class Icosahedron {
private double edge = 0;
private int count = 0;
Scanner input = new Scanner(System.in);
double useredge = input.nextDouble();
System.out.println("Enter Edge Length: ");
}
i receive an error on the last line. i cant use println() what am i doing wrong? or maybe im understanding the question wrong? any guidance would be appreciated.
thanks.
Your Icosahedron class should look like the following:
public class Icosahedron {
private double edge;
private int count;
public Icosahedron(int count) {
this.count = count;
}
public double getEdge() {
return edge;
}
public void setEdge(double edge) {
this.edge = edge;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
#Override
public String toString() {
return "Icosahedron{edge=" + edge + ", count=" + count + '}';
}
}
And your class containing the main method (I called it MoreProblem):
import java.util.Scanner;
public class MoreProblem {
public static void main(String[] args) {
Icosahedron[] icos = new Icosahedron[4];
for (int i = 0; i < icos.length; i++) {
icos[i] = new Icosahedron(i+1);
Scanner input = new Scanner(System.in);
System.out.println("Enter Edge Length: ");
double userEdge = input.nextDouble();
icos[i].setEdge(userEdge);
}
for (Icosahedron icosahedron : icos) {
System.out.println(icosahedron);
}
System.out.println("Number of Icosahedron objects created: " + icos.length);
}
}
I'm trying to create a FileIO where random numbers are placed into a .txt file and outputted, sorted in another .txt file. I have a bubble sort code that can sort numbers & I have another code that makes a .txt file. I'm just not sure how I'd implement these 2 together.
Here's my fileIO code:
public static void main(String[] args) {
File file = new File("test.txt");
//Writes name and age to the file
try {
PrintWriter output = new PrintWriter(file);
output.println("Rober");
output.println(27);
output.close();
} catch (IOException ex) {
System.out.printf("ERROR: %s\n", ex);
}
//Reads from the file
try {
Scanner input = new Scanner(file);
String name = input.nextLine();
int age = input.nextInt();
System.out.printf("Name: %s Age %d\n", name, age);
} catch (FileNotFoundException ex) {
System.out.printf("ERROR: %s\n", ex);
}
}
And here is my bubble sort code:
public static void main(String[] args) {
Random num = new Random();
//Creating an array for 10 integers
int [] number = new int [10];
System.out.print("Random Numbers:");
/*Display the unsorted numbers in a random order.
These numbers range from 0 to 100
*/
for (int d = 0 ; d<number.length ; d++){
/* We add a "+1" to the nextInt(100) here because then the numbers
will only range from 0 to 99.
*/
int RandomG = num.nextInt(100)+1;
number[d] = RandomG;
System.out.print(" " +RandomG);
}
//Display the sorted numbers
System.out.print("\nSorted Numbers:"+Arrays.toString(BubbleSortAsceMethod(number)));
}
public static int [] BubbleSortAsceMethod(int[] number){
int placeholder;
for(int i = 0 ; i < number.length-1 ; i++){
for ( int x = 1 ; x < number.length-i ; x++){
/*If the first number in the sequence is greater than the second
number, than save the first number of sequence in placeholder
and place the second number in the first numbers position, and
put the placeholder in the second numbers position (SWAP).
*/
/*
Since this is saying that when the first term is bigger than the
2nd term, the sequence will increase. If we flip the relational
operator, the sequence will decrease.
*/
if ( number[x-1] < number[x]){
placeholder = number[x-1];
number[x-1] = number[x];
number[x] = placeholder;
}
}
}
return number;
}
I'm kinda new to all this java stuff so please go a bit easy on me! Any help at all is appreciated :)
As the data contained in the file will consist of a pair of values: The name (String) and the age (int), you will need to retain their relationship. The best way of doing this would be to create a Class to represent the data. Eventually you want to sort the data on age using your BubbleSort method. While practically this would not be your first choice to sort data, I assume that this is a requirement. The BubbleSort method you have sorts an int[] by comparing each entry against it's immediate neighbor. With int being primitive, you can directly compare each element using the < operator.
public class Person implements Comparable<Person> {
private String name;
private int age;
public Person(String name, int age) {
this.age = age;
this.name = name;
}
public String getName() { return name; }
public int getAge() { return age; }
#Override
public String toString() {
return name + System.lineSeperator() + age;
}
#Override
public int compareTo(Person person) {
return this.age - person.age;
}
}
You may want to implement the Comparable interface to compare Objects; in which the interface must be implemented by Overriding the compareTo(Person person) method. You can impose sorting on age by returning the difference in age. This is not the only way you can impose the order you want; you may wish to compare directly using the getAge() of each Object or create a Comparator object.
Using the Comparable interface does allow you to make your BubbleSort class more generic, however (though the array must be of Objects that implement the interface; hence no primitive types).
public class BubbleSort {
public static <T extends Comparable> T[] BubbleSortAsceMethod(T[] array) {
for (int i = 0; i < array.length - 1; i++) {
for (int x = 1; x < array.length - i; x++) {
if (comparator.compare(array[x - 1], array[x]) < 0) {
T placeholder = array[x - 1];
array[x - 1] = array[x];
array[x] = placeholder;
}
}
}
return array;
}
}
You will notice that this sort method has some slight differences from your original, namely the BubbleSortAsceMethod method signature with the introduction of generic type parameters. Once again, this is completely optional, though this does give you the flexibility to use this method in the future for other arrays of Classes that extend the Comparable interface.
If you don't want to use generics or the Comparable interface, you will need to change the method signature and if statement.
You're method signature should instead look like public static Person[] BubbleSortAsceMethod(Person[] array) and the if statement if (array[x-1].getAge() < array[x].getAge())
This can give you an illustration of it working, though this does not consider the file io which should be simple to implement from what you have done already.
static Random random = new Random();
public static void main (String args[]) {
int size = 100;
Person[] peopleArray = new Person[size];
for (int i = 0; i < size; i++) {
String name = generateName(random.nextInt(4) + 4);
int age = random.nextInt(100);
peopleArray[i] = new Person(name, age);
}
peopleArray = BubbleSort.BubbleSortAsceMethod(peopleArray);
}
Note that this conforms, at least as much as possible, to the code you have implemented this far. If the BubbleSort and use of arrays are not critical, data structures that implement the List interface, such as ArrayList, can allow you to implement this much cleaner. This does not use the BubbleSort method at all.
public static void main (String args[]) {
int size = 100;
ArrayList<Person> people = new ArrayList<>();
for (int i = 0; i < size; i++) {
String name = generateName(random.nextInt(4) + 4);
int age = random.nextInt(100);
people.add(new Person(name, age));
}
peopleList.sort(Person::compareTo);
//or, if you don't want to implement comparable
peopleList.sort(Comparator.comparing(Person::getAge));
}
Appendix:
Used for illustrative purposes: Generates a name of a set length (randomly).
static char[] alphabet = "abcdefghijklmnopqrstuvwxyz".toCharArray();
public static String generateName(int length) {
if (length > 0) {
return alphabet[random.nextInt(alphabet.length)] + generateName(length - 1);
}
return "";
}
I have a final project for my Data Structures class that I can't figure out how to do. I need to implement Radix sort and I understand the concept for the most part. But all the implementations I found online so far are using it strictly with integers and I need to use it with the other Type that I have created called Note which is a string with ID parameter.
Here is what I have so far but unfortunately it does not pass any JUnit test.
package edu.drew.note;
public class RadixSort implements SortInterface {
public static void Radix(Note[] note){
// Largest place for a 32-bit int is the 1 billion's place
for(int place=1; place <= 1000000000; place *= 10){
// Use counting sort at each digit's place
note = countingSort(note, place);
}
//return note;
}
private static Note[] countingSort(Note[] note, long place){ //Where the sorting actually happens
Note[] output = new Note[note.length]; //Creating a new note that would be our output.
int[] count = new int[10]; //Creating a counter
for(int i=0; i < note.length; i++){ //For loop that calculates
int digit = getDigit(note[i].getID(), place);
count[digit] += 1;
}
for(int i=1; i < count.length; i++){
count[i] += count[i-1];
}
for(int i = note.length-1; i >= 0; i--){
int digit = getDigit((note[i].getID()), place);
output[count[digit]-1] = note[i];
count[digit]--;
}
return output;
}
private static int getDigit(long value, long digitPlace){ //Takes value of Note[i] and i. Returns digit.
return (int) ((value/digitPlace ) % 10);
}
public Note[] sort(Note[] s) { //
Radix(s);
return s;
}
//Main Method
public static void main(String[] args) {
// make an array of notes
Note q = new Note(" ", " ");
Note n = new Note("CSCI 230 Project Plan",
"Each person will number their top 5 choices.\n" +
"By next week, Dr. Hill will assign which piece\n" +
"everyone will work on.\n");
n.tag("CSCI 230");
n.tag("final project");
Note[] Note = {q,n};
//print out not id's
System.out.println(Note + " Worked");
//call radix
Radix(Note);
System.out.println(Note);
//print out note_id's
}
}
Instead of
public Note[] sort(Note[] s) { //
Radix(s);
return s;
}
I should have used
public Note[] sort(Note[] s) { //
s = Radix(s);
return s;
}
and change the variable type of Radix from void to Note[].