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


ADVERTISEMENT

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

Class Method Which Take String And Returns A String In Reversed Version

Dec 16, 2014

i am trying to write a class method which will take in a string and returns a string which is the reversed version of that string. it compiles fine but when i try to run it it states Main method not found in class StringReverse,please define the main method as public static void main(String[]args). I am new to java and cannot figure out

import javax.swing.JOptionPane;
public class StringReverse {
public String reverseString(String str){
JOptionPane.showInputDialog(null,"Please enter word");
char c = str.charAt(str.length()-1);
if(str.length() == 1) return Character.toString(c);
return c + reverseString(str.substring(0,str.length()-1));}}

View Replies View Related

How To Call String From Main Method In Different Class

Dec 9, 2014

The following code is located in my main class called InjectionFix. I have another class where I need to call or initiate the string in the code below. How can I achieve this. I tried to create an Object of the class but I cant do this because my other class doesnt contain a main method.How can I get the other class to initiate the code below which is loacted in my main class.
 
public static String escapeDN(String name) {
  StringBuilder sb = new StringBuilder();
  // space or # character at the beginning of a string
  if ((name.length() > 0) &&
        ((name.charAt(0) == ' ') ||
             (name.charAt(0) == '#'))) {

[Code] .....

View Replies View Related

Swing/AWT/SWT :: Implementing Listener Of GUI In A Different Class?

Jun 26, 2014

I have two different classes called Login (in the package View) and RegButtonListener (in the package Controller). I want to use the MVC pattern.

Login creates a GUI for login. I used NetBeans GUI Builder to create it.

In the class RegButtonListener there is the code for the click of the buttons, then various listeners of the GUI.

Now I want to close the login frame at the click of a button so I want to use the dispose() method.

If I had all the code (GUI code and code of the listener) in the same file, close the frame would be easy enough to do because this.dispose(). But in my case I have two different classes.

I also have a second problem.

In Login class (in the packege View) I have included the line :

regButton.addActionListener(Controller.RegButtonListener).

However, Netbeans tells me an error "package regButton does not exist. <identifier> expected". Why does he consider regButton a package? How can I fix these two problems?

How do I do then?
 
Below is the code of the two classes.

Login class.
public class Login extends javax.swing.JFrame {
/** Creates new form Login */
public Login() {
initComponents();

[code]....

View Replies View Related

Implementing A Java Class Library?

Apr 18, 2014

i have been given a homework assignment where I have to get rid of a stack object I wrote for a program and replace it with the Stack<E> library java offers ie:

public class Stack<E> extends Vector<E> {
public Stack(); // constructor
public Boolean empty();
public E peek();
public E pop();
public E push(E item);
}

my question is do i have to actually write all these methods? Or can i just construct a stack and use the methods?

View Replies View Related

Ambiguity When Implementing Multiple Interfaces With Same Method / Variable Names?

Oct 14, 2014

imagine you are implementing 2 interfaces having identical method signatures:

interface A {
void doStuff();
}
interface B {
void doStuff();

[Code] ....

How can I implement both methods?

Or another example with member variables:

interface A {
public static final int i = 3;
}
interface B {
public static final int i = 33;

[Code] ....

How can I go about making clear which 'i' is meant?

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 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 View Related

Method Creation - Take A String With Duplicate Letters And Return Same String Without Duplicates

Nov 7, 2014

How can I write a method that takes a string with duplicates letters and returns the same string which does not contain duplicates. For example, if you pass it radar, it will return rad. Also i would like to know how can I Write a method that takes as parameters the secret word and the good guesses and returns a string that is the secretword but has dashes in the places where the player has not yet guessed that letter. For example, if the secret word is radar and the player has already guessed the good guesses letters r and d, the method will return r-d-r.

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

String Split Method To Tokenize String Of Characters Inputted?

Sep 27, 2014

I am currently trying to make a calculator in Java. I want to use the String split method to tokenize the string of characters inputted. I thought I was using the String split method wrongly, because I had surrounded the characters I wanted to delimit with square brackets. However, when I removed the square brackets, the code threw an exception when I pressed the equal button. The exception was a PatternSyntaxException exception. Am I using the String split method wrongly? And why is the exception thrown? Here is my code:

import javax.swing.*;//import the packages needed for gui
import java.awt.*;
import java.awt.event.*;
import java.util.Arrays;
import java.util.List;
import static java.lang.Math.*;
public class CalculatorCopy {
public static void main(String[] args) {

[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

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

Accepting String And String Array In Just ONE Method?

Mar 18, 2014

Code a Java method that accepts a String array and a String. The method should return true if the string can be found as an element of the array and false otherwise. Test your method by calling it from the main method which supplies its two parameters (no user input required). Use an array initialiser list to initialise the array you pass. Test thoroughly.

public class test {
public static void main(String[] args) {
Printhelloworld();
String[] verbs = {"go", "do", "some", "homework"};
printArrays(verbs);

[Code] .....

View Replies View Related

String Split Method To String Array

Sep 21, 2014

So I'm creating a class which when given three inputs uses them as sides of a triangle and tells ther user what type of triangle it is, or if the input is invalid, tells them why it is invalid. I'm readin the input as a string and then trying to split it into a string array, from there checking to see if it has 3 elements.. in which the data is good at that point, and then converting them to ints and checking to see if they're negative ansd finally checking to see if they can work as sides of a triangle ie a+b >c, a+c >b , b+c >a.

I'm trying to split it into an array of strings but am getting an error, and can't seem to figure out why as this should be working from what I've read of the string.split method online.

import java.util.*;
public class TriangleTest{
private int sideA;
private int sideB;
private int sideC;
public static void main(String[] args){
TriangleTest triangle = new TriangleTest("3 4 5");

[Code] ....

The output reads [Ljava.lang.String;@15db9742

View Replies View Related

Accessing Parent Class Method Using Child Class Object?

Feb 4, 2015

I want to know is there any way we can call parent class method using child class object without using super keyword in class B in the following program like we can do in c++ by using scoop resolution operator

class A{
public void hello(){
System.out.println("hello");
}
}
class B extends A{
public void hello(){
//super.hello();
System.out.println("hello1");

[code]....

View Replies View Related

Error Passing Value Of A Variable From One Class To Main Method Of Another Class

Jan 8, 2014

I've 3 classes.

1. Circle
2. GetInputFromUser
3. testCircle

package ABC;
public class Circle {
private double radius;
public double getRadius() {
return radius;

[Code] .....

In the testCircle class, in the line: getRadius = ui1.GetInput();

It's showing the error: The method GetInput(float) in the type GetInputFromUser is not applicable for the arguments ()

And when I do: getRadius = ui1.GetInput(rad);

It's showing the error: rad cannot be resolved

View Replies View Related

How To Call A Method That Exist Within A Class Into Main Method

Feb 13, 2014

I am just trying to test this array, for a locker combination program that involves classes...but the array is printing out the whacky numbers for the location. When I try to call the method in the main, it does not work. How do I call a method that exist within a class into the main method?

public class locker { 
public static void main(String[] args) {
CombinationLock();

[code]....

View Replies View Related

Calling Private Method To Another Method Located In Same Class

Oct 23, 2014

I am trying to call a private method to another method that are located in the same class.

I am trying to call prepareString to the encode method below.

Java Code:

public class ShiftEncoderDecoder
private String prepareString(String plainText)
{
String preparedString = "";
for(int i = 0 ; i < plainText.length();i++)
if(Character.isAlphabetic(plainText.charAt(i)))

[Code] .....

View Replies View Related

Dice Game - Invoking Method In Other Method Of Same Class

Feb 26, 2015

I am currently working on a dice game. I have a private method called rollDice and it performs the action of rolling two dice. For my project, I need to create another method called playerRolls and I am supposed to invoke the rollDice method in the playerRolls method and perform actions based off of that. My question right now is how do I invoke a method into another method of the same class?

View Replies View Related

App That Declares A Class Person (String Name / Int Age) And Account Class?

Mar 31, 2014

I want to write an app that declares a class Person(String name, int age), and an Account class, Account(int code, double balance).But, additionally, every Person has at most 3 accounts, and each account has a Peron associated with it.

my code so far...

public class Person {
private String name;
private int age;
private Account[] accounts;
private int numOfAccounts;
public Person(String name,int age){
this.name=name;

[code]....

My problem is:When I make data input for a person, and additionally I want to read data for the account(s) that this rerson has, what code should I write to create a new Account object as account[numOfAccounts].And, what is the code to assign an owner to a new created Account object?

There exists a relationship between the two classes, but I cannot find the way to implement this relation....

View Replies View Related

Calling Method Of Another Class Which Is Implemented By Runnable Class

Aug 11, 2014

i am having a problem while calling a method..i am having a class

Java Code:

public class MySer implements Runnable {
public void getMessage(String msg)
{
...,
}..,
} mh_sh_highlight_all('java');
i use the above class in another class

[code]....

View Replies View Related







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