How To Sort Names Using Compareto

Feb 24, 2014

i have this problem with my code. it need to put three names in alphabetical order that are entered from the user. then output the alphabetical result. the program compiles but when you put in different names there are not alphabeticals. i think only the first if works good.

import javax.swing.JOptionPane;
public class Sort
{
public static void main(String[] args)
{
String name1;
String name2;
String name3;
 
[code]...

View Replies


ADVERTISEMENT

Sort ArrayList By Object Field WITHOUT Using CompareTo Methods?

Mar 9, 2014

I have a project where I must sort a collection of songs by a number of fields: year, rank, title and artist. in the project, we must use certain methods and we cannot add others without getting marked down. Here are the specific requirements:

Sorting

The -sortBy option will cause the output to be sorted by a particular field. If this option is specified, the output should be ordered according to the field named. If there are ties, the tied songs should appear in same order in which they were in the input file. If no -sortBy option is specified, the output should maintain the order of the input file.

public void sortYear()

Order the songs in this collection by year (ascending).public void sortRank()
Order the songs in this collection by rank (ascending).public void sortArtist()
Order the songs in this collection lexicographically by artist (ascending, case-insensitive).public void sortTitle()
Order the songs in this collection lexicographically by title (ascending, case-insensitive).

Here is the relevant code:

SongCollection Class
Java Code: import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.*;

[code]....

View Replies View Related

Sort String List Alphabetically With CompareTo Method / If Else Statements - Logic Errors

Oct 6, 2014

I'm having trouble with sorting Strings- 3 strings inputted by user, and I would like to output them in alphabetical order. I've used the str.compareToIgnoreCase method, and then I've tried to loop them through a series of if/ else statements. Everything I've been able to find online (including the forums here) has suggested to use the Comparator class, or to put the strings into an array, and sort list- I really would like to stick with just the String class, and its methods .

The program itself works and compiles, but I am getting logic errors that I have been unable to solve. I'm using IntelliJ Idea, and I've ran it through the built in debugger, about 100+ times (not exaggerating, lol) just to see what it's doing in particular scenarios. For instance, I can get c, a, b, to print out as a,b,c correctly, but a,b,c, will print out as b,a,c.

For me this is kind of like a Sudoku puzzle, or a Rubik's cube! Each time I fix one scenario, it breaks another one, so I don't know if there's a(logic) solution to fix all possible scenarios (abc, acb, bac etc... to all print abc) or if possibly I just need more if statements. I've only pasted in the area where I'm having problems (the if statements). I'm a big fan of the "Next Line" syntax.

(Note: please assume the non relevant content- import Scanner class, main method, etc... I didn't want to paste the entire program.)

System.out.println("Enter the first statement: ");
//input.nextLine();
string1 = input.nextLine();
System.out.println("Enter the second statement: ");
string2 = input.nextLine();
System.out.println("Enter the third statement: ");
string3 = input.nextLine();

[Code] ....

View Replies View Related

Write Program To Sort Names According To Number Of Vowels?

Feb 15, 2014

write a program to sort names according to number of vowels sort({sam,ratan,alok,raj}) the op is {sam,ratan,alok,raj}

View Replies View Related

Casting For CompareTo

Nov 11, 2014

I am trying to compare some items from a generic arraylist with each other, but I keep getting an error stating that I need to cast the values in line 38. However, when I heed the warning and change it to what it wants, I get a warning stating "type safety: Unchecked cast from K to Comparable<K>". Should I ignore this warning or is there a better way to compare the two items? Also, is there another way for me to use compareTo w/o making my class extending/implementing comparable or is that the only way?Here is what I have:

class WordInfo<K, V extends Comparable <K>> {
private FileReader fr;
private String word;
private ArrayList<K> list;
private BufferedReader br;
private int current = 0;

[code]....

View Replies View Related

How Does CompareTo Work If There Are More Than 2 Elements In List

Jan 8, 2015

Lets suppose that I pass to the sort method a list of 2 objects of the same class (which implements Comparable interface). I read (in head first java) that one object is compared relative to another with one object calling the CompareTo() while the other object being passed as a parameter to the same method. Now am I safe in assuming that the first object in the list calls the method with the second object being passed as a parameter.And also how does the CompareTo() work if there are more than 2 elements in the list. Which objcet calls the method and which is passed as a parameter?

View Replies View Related

Inventory Program - CompareTo Not Working

Jul 16, 2014

My instructor gave me this code to use as my Array sort. I can not get this to work. I do not get any compile errors, the code just does not do anything.

Java Code:

package inventoryprogram4;
import java.util.Scanner;
public class Inventoryprogram4
{
static GUI mainGUI = new GUI();
static String outText = "";

[Code] .....

View Replies View Related

Overriding CompareTo From Comparable Interface

Oct 31, 2014

Here is my code:

/*
* Implement the Comparable interface on objects of type Order.
* Compare orderId, then productId. The lesser orderId should come first. If the orderIds match, then the lesser productId should come first.
*/

@Override
public int compareTo(Order ord) {
// TODO Auto-generated method stub
if(orderId > ord.orderId){
return 1;

[Code] ....

Here is the output:

Actual: 0
Expected: -1
Actual: -1
Expected: -1
Actual: 1
Expected: 1
Actual: 1
Expected: 1
Actual: 0
Expected: 0
Actual: 0
Expected: 0

In short, the "Actual" is what my code produces and the "Expected" is what it is supposed to produce. As you can see, only the first one is mismatching... I'll admit, the comment section above the method is confusing and I wasn't exactly sure what it wants me to do, but I thought I figured it out. I just don't see how 5/6 of these tests can work and the 6th one not.

View Replies View Related

Implementing CompareTo Method Of String Class

Apr 26, 2015

I've tried implementing the compareTo method in several ways and no luck.. I keep getting errors and now it just says bad operand type for binary operator with the ">" symbol and also the less than. I'm attempting to give an implementation for the compareTo method so it compares the value of the requestDate instance variable of the two objects. if the calling object of request is greater then I have to return ""1" if it's smaller then returns "-1" and if they are the same then returns value of "0"

package librarysystem_phase2;
import java.io.Serializable;
/**
* This class represents a request a member makes to checkout or download an item from the library.
*/
public class Request implements Serializable, Comparable<Request>

[code]....

View Replies View Related

CompareTo Statement - Null Pointer Exception

Apr 16, 2014

I am getting a NullPointerException at my compareTo statement in this section of my code. Why this is popping up?

public static int findPos(String theArray[], String playerName, int arrayCount)
{
int index;
int pos;
for(index = 0; index < arrayCount; index++) {
while ((index < arrayCount) && (playerName.compareTo(theArray[index]) > 0)) {
index++;
}
}
pos = index;
return pos;
}

Error is also creeping up on the line highlighted in a comment as "THIS LINE", and is linked to the compareTo error above.

while(yesOrNo == 'Y' || yesOrNo == 'y')
{
switch(option)
{
//Add a Player and their Stats to the Array

[Code] ....

View Replies View Related

CompareTo Function To Identify Relationship Between Two Values In Array

Mar 28, 2014

I am having difficulty with a sorting routine. I believe that the concept is valid (although not necessarily the most efficient), but I keep running into a problem. I am trying to use the compareTo function to identify the relationship between two values in an array, but it seems to have an issue with it being a comparison of two float values.

Java Code:

for (int x = 0; x < 430; x++) {
for (int y = 0; y < 430; y++) {
if (dataArray[y].compareTo(dataArray[y + 1]) > 0); {
tempOpen = dataArray[y];

[Code] ....

It gives the compile error as follows:

File: C:UsersBradDownloadsAssignment 3Calculations.java [line: 157]
Error: Cannot invoke compareTo(float[]) on the array type float[]

View Replies View Related

Map Same Names In 2 Enums

Oct 2, 2014

I have 2 enums like below

enum enum1{
TEST_1("name_1","name 1"),
TEST_2("name_2,"name 2");

private String name;
private String description;

[Code] .....

How can i map the same names in 2 enums and get message from enum 1 and code from enum 2.

View Replies View Related

Getting Names Of Objects?

Jan 22, 2015

In my project I had to create 2 classes, Room and Animal.

Room had to have an array (NOT arrayList-I know theyre better and easier but I need to use an array, for now) This array must be able to be populated by 10 "Animals", and the Room class needs two methods, a method to add animal a to the room (rooms array) and a toString() that returns the name of the room and the names of the animals in the room. The teacher added a hint saying that this toString() should reference the animal classes toString()

Here is my code thus far:

public class Room {
private String name;
Animal[] inRoom = new Animal[10];
public Room(String roomName){
name = roomName;
} public void addAnimal(Animal a){
for(int i = 0; i < 10; i++){

[code].....

View Replies View Related

How To Add Row Names To JTable

Jan 17, 2015

I'm trying to implement a spreadsheet-like table using JTable and this is the basic structure.

String[] colnames={"A","B","C","D","E"};
String[][]data=new String[28][5];
sheet = new JTable(data,colnames);
//sheet.setBounds(10, 36, 527, 214);
JPanel tablepane=new JPanel();
tablepane.add(new JScrollPane(sheet));
tablepane.setSize(800, 400);

In a spreadsheet, alphabetical letters are column names and numbers represent rows. I have named the columns and I need to name the rows in the same way. Or if I am to set the first column in every row as row headers, how can I make then non-editable by the user? In addition to that, how can I make the table appear bigger? There's a lot of space but the table appears to be small.

View Replies View Related

Random User Names

Nov 9, 2014

Program is running fine. I can create usernames and everything but somehow I cannot quit or exit the program when I enter my sentinal value "QUIT". Here is my program question: Create an application that will create a username for a school computer system. Input a user’s first and last name. The username will be the first letter of the first name followed by the first 5 letters of his last name followed by a random 3 digit number. Continue to create and display usernames until a sentinel value is entered.

import java.text.*;
import java.util.Random;
import java.text.DecimalFormat;
public class username

[code]...

View Replies View Related

Get All Controls Names On Layout

Oct 1, 2014

I'm new on Java/android and I wounder how could I get name of each control in a layout, ex.

for (int i=0;i<table1.getChildCount();i++ ) {
Object child=table1.getChildAt(i);
if( child instanceof EditText)
{
//get control name here
}
}

View Replies View Related

Randomizing Names From A List?

Feb 2, 2014

I'm trying to use the DataFactory class to pull in a list of names, as I need to populate my app in development with randomized test data for testing.

DataFactory

So, I can get a random name like so:-

package domainentities;
import java.util.Random;
import java.util.Collections;
import org.fluttercode.datafactory.AddressDataValues;

[Code] .....

But - it always prints 'Lindsey'. I need a way of completely randomizing but I can't see the class has a method to let me do this? I can use the randomize method but this takes an int argument which will always bring back the same index value (same name).

I wonder if I am over complicating this. I can use a simple String array of names, but I don't want, like 10,000 names in my array and I want a good way of generating good, randomized data. Perhaps a .csv file of names could be read in? Here is a second method I wrote but I don't have the skills to know how to read the array values from my large .csv file:

public String randomSecondName(){
String[] lastNames = {"Smith", "Jones", "Collins","Jackson",
"Dearsley", "Trump", "Carr", "O'Connell", "Dyer", "Furstzwangler" };
Random ran = new Random();
String lastName = lastNames[ran.nextInt(lastNames.length)];
return lastName;
}

View Replies View Related

Get All Access Table Names?

Jul 12, 2014

I'm using MS Access database. What I want to do, is to get all names of my tables in database.My SQL query :

SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES

is it correct? I found it in one example and didn't change anything.

I could of course execute this and check, but the problem is, that it returns ResultSet(I'm using Java), and I do not know how to manipulate this object in this situation.Cause usually ResultSet contains columns and rows, I think now I should get only bunch of String values.

View Replies View Related

How To Separate Names In Scripts

Feb 26, 2014

Java Code:

setseatpos: function(previouspos, position) {
this.seatelement.removeclass("seat-empty").removeclass("seat-pos-" + previouspos).removeclass("seat-inactive").addclass("seat-pos-" + position);
},
renderseat: function() {

[Code] ....

View Replies View Related

Swing/AWT/SWT :: Getting A Row Of Names From The First Column Of JTable?

Feb 9, 2014

I have a JTable with the model " Names " , " Quantity " and " Unit " .

I'm coding a program where you get the ingredients names.

So i need to get the whole row of one column and String it all up together,because i need to store it in mySql and i have already set it all as String.

how i can do this ?

My code are as follows :

JTable Code:

DefaultTableModel model = (DefaultTableModel)table.getModel();
if(!txtQty.getText().trim().equals("")){
model.addRow(new Object[]{ingCB.getSelectedItem().toString(),txtQty.getText(),unitCB.getSelectedItem().toString()});
}else{
JOptionPane.showMessageDialog(null,"*Quantity field left blank");
}

Getting the values and for storing :

for(int i = 1; i<= i ; i++){
ingredients = table.getName();
}

This is for loop is wrong and it does not work because i have a constructor to take in Ingredients but because it is inside the loop, it cannot take it in.

View Replies View Related

How To Make A List Of Names With Java

Oct 16, 2014

One of my assignments was to make a program that would read a sequence of names and then list them all.Just to be clear, it would read them all first, and then it would list them all at the same time.

View Replies View Related

Method Header For File Names?

Feb 27, 2015

I'm new to Methods and do not really know how to write a method header. What would an appropriate header look like for the following instance? getFilename: This method takes no parameters. It asks the user for a filename. If that file exists, it returns the filename. If it does not exist, it asks the user for another filename. It continues to ask for filenames until the user gives the name of a file that exists.

Also, how would I make a return tag for this and call it into the main method.

View Replies View Related

How To Replace Author Names With Numbers

Nov 4, 2014

I have a coauthorship network and I want to replace the authors names with numbers.Part of my datadet:

1992,M_DINE,R_LEIGH,P_HUET,A_LINDE,D_LINDE
1992,C_BURGESS,J_CLINE,M_LUTY
1992,M_DINE,R_LEIGH,P_HUET,A_LINDE,D_LINDE
1992,F_ZWIRNER
1992,O_HERNANDEZ
...

I want the result to be sth like this:

1992 1,2,3,4
1992 5,67
....

and a table of mappings

M_DINE 1
R_LEIGH 2
P_HUET 3

....

I give my dataset in csv (or text) format to my program but it says "(The system cannot find the file specified)" even though the file exists.

what should I do?

here is my code:

Java Code: public class ReadCSV {
HashMap<String, Integer> authorList = new HashMap<>();
File file = new File("d:/Course/thesis/predict/whole.scv");
int authorCounter = 0;
public static void main(String[] args) {
ReadCSV obj = new ReadCSV();

[Code]...

View Replies View Related

Searching Through Array (List Of Names)

Oct 5, 2014

An array which contain a list of names. I let for a user input and I use that to search through the array. For example lets say the string name "Christian" is stored inside the names array and the user types in Chri, the program looks in the array and finds a name that contains Chri and prints them out. How do I go about doing this?

View Replies View Related

Format Of Java File Names

Mar 30, 2015

In Java® identifiers, you are allowed letters and numbers (also _ $£¢€ etc, but you should avoid them in normal identifiers). So you cannot have spaces. You cannot write public class Hello World because the javac tool will see World as a separate identifier and not understand what it means and will fail to compile the code. You must write public class HelloWorld instead. And because the class is labelled public you must call the source file Hello World. java. Since you can't have two classes with the same [fully‑qualified] name, you cannot write two public classes in the same source file.

“What about names of source files?” somebody will ask. Well, some file systems will permit spaces in file names; ext4 will and I suspect so will NTFS. Can you write file names with spaces in? You would have to have a different name of the class inside the file, because you can't have spaces, and you therefore cannot make the class public, but maybe you can write a package‑private class with a different name.

On ext4, you have to write out the name of the file and the shell will interpret the space as meaning there are two different file, so you have to escape the space.

campbell@campbellsComputer:~/java$ gedit My First Class.java
// My First Class.java
class Foo
{
public static void main(String... args)
{
System.out.println("Hello, World!");
}
}
campbell@campbellsComputer:~/java$ javac My First Class.java
campbell@campbellsComputer:~/java$ java Foo

View Replies View Related

Method Header For File Names?

Feb 26, 2015

I'm new to Methods and do not really know how to write a method header. What would an appropriate header look like for the following instance? getFilename: This method takes no parameters. It asks the user for a filename. If that file exists, it returns the filename. If it does not exist, it asks the user for another filename. It continues to ask for filenames until the user gives the name of a file that exists.

Also, how would I make a return tag for this and call it into the main method.

View Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved