compare the last names of two students in a directory - java

I'm trying to compare the last names of two students in a directory, I'm doing this by overriding the compareTo method. The following code does not reflect exactly what I'm wanting to do here, the return value is just a placeholder for now. It is saying it won't compile because it cannot find the symbol for subString(int) in class String.
for (int i = 0; i < this.getLastName().length(); i++) {
if (!this.getLastName().subString(i).equals(s.getLastName().subString(i))) {
return 1;
}
}
Update: I appreciate y'all pointing out my idiocy in case sensitivity (no really, thanks) here's an update to where I'm at in the code. I think I can take it from here.
#Override
public int compareTo(Student s) {
for (int i = 0; i < this.getLastName().length(); i++) {
if (!this.getLastName().equals(s.getLastName())) {
for(int j = 0; j < this.getLastName().length() || j < s.getLastName().length(); j++) {
if (this.getLastName().charAt(j) < s.getLastName().charAt(j)) {
return 1;
}
else {
return -1;
}
}
}
}
looking at it again, I don't even need that first for loop.
and here's the finished method.
#Override
public int compareTo(Student s) {
if (!this.getLastName().equals(s.getLastName())) {
for(int j = 0; j < this.getLastName().length() || j < s.getLastName().length(); j++) {
if (this.getLastName().charAt(j) < s.getLastName().charAt(j)) {
return 1;
}
else if (this.getLastName().charAt(j) > s.getLastName().charAt(j)) {
return -1;
}
}
}
if (!this.getFirstName().equals(s.getFirstName())) {
for (int i = 0; i < this.getLastName().length() || i < s.getLastName().length(); i++) {
if (this.getFirstName().charAt(i) < s.getFirstName().charAt(i)) {
return 1;
}
else if (this.getFirstName().charAt(i) > s.getFirstName().charAt(i)) {
return -1;
}
}
}
return 0;
}

The simple way to compare two Java strings is to use the String.compareTo(String). You don't need to implement that yourself using loops. (Or at least, not in a real world context.)
If you want to order by lastname then firstname:
call `compareTo` on the last name string
- if the result is non zero, return it
- if the result is zero, compare the first name string.
I'll leave you to figure out the rest ... since this is clearly a "learning exercise".

Not sure why you want to reinvent the wheel. Stephen C was trying to point out that you can achieve the same result like this:
#Override
public int compareTo(Student that) {
int compare = this.getLastName().compareTo(that.getLastName());
if (compare == 0) {
compare = this.getFirstName().compareTo(that.getFirstName());
}
return compare;
}

Related

How can i use a nested loops to help identify if i have 2 different matching pairs of dices

So I just had a lesson on loops and nested loops. My professor said that nested loops can help us do tasks such as knowing if we rolled 2 different matching pairs with 4 dices (4242) I'm a bit confused on how that would work.
So I started to work it out and this is what I was able to create.
public boolean 4matchDice(String dice){
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
}
}
I used boolean as the return as it will tell us whether or not we have 2 different matching pairs.
Thing is, what do I put in the the loops? That's what's confusing me the most.
Here's a solution I came up with, seems to be returning the correct outcome for all the test cases I ran.
public static boolean matchDice(String dice) {
char[] diceArray = dice.toCharArray();
int pairs = 0;
for (int i = 0; i < 4; i++) {
for (int j = i + 1; j < dice.length(); j++) {
if (diceArray[i] == diceArray[j]) {
diceArray[i] = 'X';
diceArray[j] = 'Y';
pairs++;
}
}
}
return (pairs > 1);
}
If you're only comparing two sets with two dice each, this is enough:
public boolean match4Dice(int first, int second, int third, int fourth) {
if ((first == third && second == fourth) || (first == fourth && second == third)) {
return true;
}
return false;
}
But if you're comparing 2 sets with any number of dice, the following algorithm would suit you better.
public boolean matchDice(String firstDiceSet, String secondDiceSet) {
// validate input, string must contain numbers from 1 - 6 only.
// lenghts of strings firstDiceSet & secondDiceSet must be equal
// works for any number of dice in each set.
// The dice only match if all numbers in the firstDiceSet all present in the secondDiceSet also.
// Let us count the matching numbers to check if this true.
int numberOfMatches = 0;
for (int i = 0; i < firstDiceSet.length(); i++) {
for (int j = 0; j < secondDiceSet.length(); j++) {
if (firstDiceSet[i] == secondDiceSet[j]) { // and not used
// increment number of matches
// mark secondDiceSet[j] as used, so that you do not count the same match twice.
// account for cases where firstDiceSet = "33" and the secondDiceSet = "35"
}
}
}
// your dice set match if the following condition is true
return (numberOfMatches == secondDiceSet.length());
}
Hi I just coded up a solution that will take "4242" as an input, although sindhu_sp's method is more practical i believe. I just wanted to show you another example to help your learning of java!
public static boolean fourMatchDice(String dice){
int match = 0;
for (int i = 0; i < dice.length(); i++){
for (int j = i+1; j < dice.length(); j++){
if (dice.toCharArray()[i] == dice.toCharArray()[j]){
System.out.println("does " + dice.toCharArray()[i] + " = " + dice.toCharArray()[j]);
match ++;
}
}
}
if(match == 2) *EDIT* //Change to (match >= 2) if 4 of the same pair is allowed.
return true;
return false;
}
public static void main(String[] args) {
System.out.println(fourMatchDice("4242"));
}
output:
does 4 = 4
does 2 = 2
true

For-loop is executed only once?

I'm implementing Insertionsort for university. My code works in theory, but my for-loop is executed only once instead of books.size() (which is 5, I've tested that). I tried it using the number 5, but it won't work and I'm kind of desperate because I can't seem to find the error.
Here is my code:
static void sort(LinkedList<Book> books)
{
int i;
for ( i = 0; i < books.size(); i++)
{
Book temp = books.get(i);
books.remove(i);
for (int j = 0; j < books.size(); j++) {
if (books.get(j).compareTo(temp) > 0) {
books.add(j, temp);
return;
}
}
books.add(temp);
}
}
The compareTo function of the Book-Class looks like the following:
public int compareTo(Book other)
{
int iAutor = autor.compareTo(other.getAutor());
if (iAutor != 0)
return iAutor;
else
{
int iTitel = titel.compareTo(other.getTitel());
if (iTitel != 0)
return iTitel;
else
{
if (this.auflage < other.getAuflage())
return -1;
else if (this.auflage > other.getAuflage())
return 1;
else
return 0;
}
}
}
Am I simply blind?
You need to swap return for break and fix the logic to avoid adding the book twice. There may be more elegant ways than this, but it should work:
int i;
for ( i = 0; i < books.size(); i++)
{
Book temp = books.get(i);
books.remove(i);
bool added = false;
for (int j = 0; j < books.size(); j++) {
if (books.get(j).compareTo(temp) > 0) {
books.add(j, temp);
added = true;
break;
}
}
if (!added) {
books.add(temp);
}
}
Well, I found out how to solve it, just if someone has the same problem (don't think that will happen, but it's a good habit I hope).
As #Klitos Kyriacou pointed out right, I had a twist in my thoughts about the process of Insertionsorting.
The solution is changing the loops in the following:
static void sort(LinkedList<Book> books) {
Book temp;
for (int counter = 0; counter < books.size(); counter++) {
temp = books.get(counter);
for (int position = 0; position < counter; position++)
{
if (temp.compareTo(books.get(position)) < 0)
{
books.remove(counter);
books.add(position, temp);
break;
}
}
}
}

Java Interface Code is Wrong?

I'm currently working on an assignment about java interface and I'm in the last 2 steps stuck there without knowing the exact problem here is the code I wrote
#Override
public boolean isNonDescending() {
double smallestElement = data[0];
for (int i = 0; i < data.length;) {
if (data[i] >= smallestElement) {
i++;
}
}
return true;
}
but when I submit my work to WebCat, it says this specific method is not working as it suppose to do, the main thing it should do is:
• isNonDescending: Returns a boolean value indicating whether the set of elements
is organized from smallest to largest (with equal elements being adjacent). Put
another way, a set of elements is nondescending if there is no smaller element that
comes after a larger element. For example, (1, 2, 2, 3, 4, 5) is nondescending while
(1, 2, 2, 3, 1, 5) is not, because a smaller element (1) came after a larger element (3).
the other method which are mentioned smallestElement in the method IsNonDescending if you need it:
#Override
public double smallestElement() {
double minElement = data[0];
for (int i = 1; i < data.length; i++) {
if (data[i] < minElement) {
minElement = data[i];
}
}
return minElement;
}
My question is where is the line with a wrong code or am i missing something?
Thanks in advance
Let's imagine I run your isNonDescending method on the following array : [ 1,2,0]
The if test is going to be wrong for the first element, so i will never be incremented and you will have an infinite loop. Plus, you never return false in your method. You should do this to fix it :
#Override
public boolean isNonDescending() {
// starting at 1 since we will be looking at data[i-1], which
// must start at 0. Alternatively, you can write
// for (int i=0 ; i < data.length - 1 ; i++) and work with data[i+1]
for (int i = 1 ; i < data.length ; i++)
if (data[i] > data[i-1]) return true;
return false;
}
public static boolean isNonDescending() {
for (int i = 1; i < data.length-1; i++) {
if (data[i-1] > data[i]) {
return false;
}
}
return true;
}
but I would name it isAscending(), nonDescending() doesn't describe your example correctly.
I think this is what you're looking for:
#Override
public static boolean isNonDescending() {
boolean success = true;
for (int i = 1; i < data.length - 1; i++) {
if (data[i - 1] > data[i]) {
success = false;
}
}
return success;
}
Hope it helps.
Clemencio Morales Lucas.

Custom indexOf without String methods

I created my own indexOf function. I was wondering if anyone could help me come up with a way to make it more efficient. I am practicing for interviews so the catch is that I cannot use any String methods. I believe the runtime of this method is O(n^2) with space of O(n). Correct me if I am wrong.
Also, I want to ensure the program runs safely and correctly, the only test case I can think of it the length comparison.
code:
public static int myIndexOf(char[] str, char[] substr) {
int len = str.length;
int sublen = substr.length;
int count = 0;
if (sublen > len) {
return -1;
}
for (int i = 0; i < len - sublen + 1; i++) {
for (int j = 0; j < sublen; j++) {
if (str[j+i] == substr[j]) {
count++;
if (count == sublen) {
return i;
}
} else {
count = 0;
break;
}
}
}
return -1;
}
Try here for string searching algorithms:
http://www-igm.univ-mlv.fr/~lecroq/string/
And here for a way to test your implementation:
http://junit.org/

Java logic issues

I'm working on a method that finds the first instance of a given value and returns its position. It works for some cases, but if I give it an array of [1,2,3], and set the value to 2, it returns 0, instead of 1. I'm not sure why, either. Here is the code:
int b = 0;
for(int a = 0; a < values.length; a++) {
if (values[a] == find){
b++;
}
}
return b-1;
Thanks in advance!
Its because you are returning b-1. In fact, if you need to find the same instance and return the index, you wont even need the variable b. You could achieve this with something like this:
for( int a = 0; a < values.length; a++) {
if (values[a] == find){
return a;
}
}
return -1 // Notfound
}
Add the return -1 line for when a value is not found, to use as a sentinel value.
Try
for( int a = 0; a<values.length; a++) {
if (values[a] == find){
return a;
}
}
Why not return a itself instead of doing b-1;
Maybe you can add a break statement too to stop iterating as you just need the position of first instance
int b=0,result;
for( int a = 0; a<values.length; a++)
{
if (values[a] == find)
{
result=a;
break;
}
}
return result;

Categories

Resources