I am trying to finish my assignment, but I am not sure how to complete it.
I have 3 arrays in my code, each of which have first names and last names (the last name comes before the first one in the arrays).
Which function should I use in order to decided whether a string is before the other?
I was thinking compare, but I'm not too sure how to implement it.
This is my code so far:
public static void main(String[] args)
{
String[] section1 = {"Curie, Marie", "Feynman, Richard", "Germain, Sophie",
"Turing, Alan"};
String[] section2 = {"Bolt, Usain", "Graf, Steffi","Hamm, Mia"};
String[] section3 = {"Bach, Johann Sebastian", "Beethoven, Ludwig van",
"Mozart, Wolfgang Amadeus", "Schumann, Clara"};
String[] merged = mergeSortedArrays(section1, section2);
String[] merged = mergeSortedArrays(merged, section3);
for(int i = 0; i < merged.length(); i ++)
System.out.print(merged[i]);
}
//Do not change the method header
public static String[] mergeSortedArrays(String[] a1, String[] a2)
{
int i = 0, j = 0, k = 0;
while(a1[i] != null && a2[j] != null)
{
if(a1[i] "comes before" a2[j])
{
merged[k] = a1[i];
i++;
else {
merged[k] = a2[j];
j++;
}
k++;
}
return merged;
}
}
To compare two strings, use
if(a1[i].compareTo(a2[j]) <= 0) { //Means: a1[i] <= a2[j]
System.out.println("a1[" + i + "] (" + a1[i] + ") is less-than-or-equal-to a2[" + i + "] (" + a2[i] + "));
}
Or
if(a1[i].compareTo(a2[j]) < 0) { //Means: a1[i] < a2[j]
System.out.println("a1[" + i + "] (" + a1[i] + ") is less than a2[" + i + "] (" + a2[i] + "));
}
I recommend the comments as I've done, because I find looking at the compareTo function very confusing. I have to keep reminding myself that the operator is sort of "in place" of the compareTo. I always comment it like this.
I've noticed some serious issues with your code, unrelated to string comparison:
Your else has no close curly-brace before it.
The object merged is never declared in the mergeSortedArrays function
Your while loop needs to check that the array indexes are not too high given the arrays, or you're going to get an ArrayIndexOutOfBoundsException
anArray.length() is incorrect. Eliminate the parentheses.
Related
I am working on a part of an assignment that requires me to the compute runners who ran above the average speed (based on 15 runners whose speed/names.. are given in the assignment and I already added all 15 values to the array in the main method).
In the definition class, I have created a method ( which must be type String according to assignment) to compute if runner [i]'s time is =< average speed.
This is my method for finding the above average runners (there are more than one) BUT this method only prints ONE runner when ran in main. How would I allow for MULTIPLE array values to be returned??
Code:
// Finding above average:
public static String getAboveAverageRunners(BanffMarathonRunner[] runners) {
for (int i = 0; i < runners.length; i++) {
if (runners[i].getTime() <= BanffMarathonRunner.getAverageTime(runners)) {
String aboveAverage = runners[i].getFirstName() + " " + runners[i].getLastName() + ", Years Competing: "
+ runners[i].getYears();
return aboveAverage;
} // End of if
} // End of for loop
return null;
} // End of getAboveAverageRunner method:
} // End of class BanffMarathonRunner:
Revised :
public static String getAboveAverageRunners(BanffMarathonRunner[] runners) {
ArrayList<String> thoseAbove = new ArrayList <String>();
for (int i = 0; i < runners.length; i++) {
if (runners[i].getTime() <= BanffMarathonRunner.getAverageTime(runners)) {
String aboveAverage = runners[i].getFirstName() + " " + runners[i].getLastName() + ", Years Competing: "
+ runners[i].getYears();
thoseAbove.add(aboveAverage);
//return aboveAverage;
// End of if statement:
}
// End of for loop:
}
return thoseAbove;
Now, I get an error on the return thoseAbove
Type mismatch: cannot convert from ArrayList<String> to String
I understand the error I just don't know how to fix it while keeping the return type.
If it has to return a string then how about returning a pipe delimitered string?
e.g.
StringBuilder myList = new StringBuilder ();
for (int i = 0; i < runners.length; i++) {
if (runners[i].getTime() <= BanffMarathonRunner.getAverageTime(runners)) {
String aboveAverage = runners[i].getFirstName() + " " + runners[i].getLastName() + ", Years Competing: "
+ runners[i].getYears();
myList.append (aboveAverage).append ("|");
// End of if statement:
}
// End of for loop:
}
return myList.toString (); // maybe remove the trailing pipe
Then in your calling method you can use String.split ("\\|")
Your problem is you're stopping at the first runner that qualifies and returning that. Instead you need to somehow collect all runners that qualify.
You probably want to return a List<String> rather than a String. Fortunately, java 8 can help here:
public static List<String> getAboveAverageRunners(BanffMarathonRunner[] runners) {
int averageTime = BanffMarathonRunner.getAverageTime(runners);
return Arrays.stream(runners).filter(r -> r.getTime() < average)
.map(r -> r.getFirstName() + " " + r.getLastName() + ", Years Competing: " + r.getYears())
.collect(Collectors.toList());
}
If you absolutely must return a single String value (not recommended), then join them with semi-colons (or whatever you like):
public static List<String> getAboveAverageRunners(BanffMarathonRunner[] runners) {
int averageTime = BanffMarathonRunner.getAverageTime(runners);
return Arrays.stream(runners).filter(r -> r.getTime() < average)
.map(r -> r.getFirstName() + " " + r.getLastName() + ", Years Competing: " + r.getYears())
.collect(Collectors.joining(",", "\"", "\""));
}
Note: this will return a csv of quoted values, like "John Smith ...", "Bob Brown ...", .... The quotes are added in case the data contains a comma.
Better yet would be to return a List<Runner>, and render them elsewhere as you need:
public static List<Runner> getAboveAverageRunners(BanffMarathonRunner[] runners) {
int averageTime = BanffMarathonRunner.getAverageTime(runners);
return Arrays.stream(runners).filter(r -> r.getTime() < average)
.collect(Collectors.toList());
}
I have two lists which contains some values,I have to make String from them so that i will take the 1st value of first list and 1 st value of 2 nd list and also 2nd value of first list and 2 nd value of 2nd list and so on..Lets says those two lists contains the interview timings.So i am giving my code here
List<String> interviewTimingToFrom1 = Arrays.asList(interviewTime1.split(","));
for(String a :interviewTimingToFrom1){
System.out.println("Timing 1:"+a);
}
List<String> interviewTimingToFrom2 = Arrays.asList(interviewTime2.split(","));
for(String a :interviewTimingToFrom2){
}
The values contain in the 1 st and 2nd list are
Timing 1:12:00am
Timing 1:2:00am
Timing 2:1:00am
Timing 2:3:00am
So now i need to make a string like from 12.00am to 1.00 am ,from 2.00 am to 3.00am how i can do that .Please help
int maxSize = Math.max(interviewTimingToFrom1.size(),interviewTimingToFrom2.size());
StringBuilder result = new StringBuilder();
for (int i=0; i<maxSize; i++)
{
if (i < interviewTimingToFrom1.size())
result.append(interviewTimingToFrom1.get(i));
if (i < interviewTimingToFrom2.size())
result.append(interviewTimingToFrom2.get(i));
}
System.out.println(result.toString());
Try this;
List<String> interviewTimingToFrom1 = Arrays.asList(interviewTime1.split(","));
List<String> interviewTimingToFrom2 = Arrays.asList(interviewTime2.split(","));
if (interviewTimingToFrom1.size() == interviewTimingToFrom2.size()) {
int noOfSlots = interviewTimingToFrom1.size();
for (int i = 0; i < noOfSlots; i++) {
System.out.println("from " + interviewTimingToFrom1.get(i)
+ " to " + interviewTimingToFrom1.get(i));
}
} else {
System.out.println("No match");
int noOfSlots = (interviewTimingToFrom1.size() > interviewTimingToFrom2
.size() ? interviewTimingToFrom2.size()
: interviewTimingToFrom1.size());
for (int i = 0; i < noOfSlots; i++) {
System.out.println("from " + interviewTimingToFrom1.get(i)
+ " to " + interviewTimingToFrom2.get(i));
}
}
So I need to print out the different instances of the array. Using the code below. Everything in the array prints out even the portion of the array that is not filled with anything. If i add a break statement in each if statement it only prints the last instance of that array and not everything that that stored.
public static void display(ExampleA[] example)
{
for(int pos = 0; pos < example.length; pos++)
{
output += "Example number " + (i + 1);
if(example[pos] instanceof A)
{
output += example[pos].toString() + "\n\n";
}
if(example[pos] instanceof B)
{
output += example[pos].toString() + "\n\n";
}
}
What I would like it to do is print out everything in the array grouped together by the instance. and not the whole array that is partially empty.
You can create two output variables, one for the A instances and one for the B instances. Then you can append each instance to its corresponding output variables, and print out the output variables at the end. Here's an example using your code:
public static void display(ExampleA[] example)
{
for(int pos = 0; pos < example.length; pos++)
{
if(example[pos] instanceof A)
{
outputA += "Example number " + (i + 1);
outputA += example[pos].toString() + "\n\n";
}
if(example[pos] instanceof B)
{
outputB += "Example number " + (i + 1);
outputB += example[pos].toString() + "\n\n";
}
}
System.out.println("A:\n" + outputA);
System.out.println("B:\n" + outputB);
}
You should also look into using StringBuilder to append the Strings, as it's much faster than using +=
I want to compare two Strings in two different arrays. Strings are stored in s1 and s2 variables. This part works great, but if I add if condition, if(s1.equals(s2)){/*...*/}, I get ArrayIndexOutOfBoundsException.
Look at these two screen shots:
In both cases arrays have same values. The only thing that was changed is the if condition.
Image#1
Image#2
Code:
Vagon tmp = first;
int stevec = 1;
while(tmp != null){
double trenutenVolumen = 0;
for(int j = 0; j < tmp.opisTovora.length; j++){
trenutenVolumen += tmp.volumenTovora[j];
}
double lahkoDodamVolumna = tmp.volumen-trenutenVolumen;
double lahkoDodamTeze = lokomotiva.najvecjaMasa-trenutnaTeza;
System.out.println("len: "+tmp.opisTovora.length);
if(tmp.tipTovora == tipTovora[0] && lahkoDodamVolumna >= volumenTovora[0] && trenutnaTeza+tezaTovora <= lokomotiva.najvecjaMasa){
if(!tmp.tipTovora){
String s1 = tmp.opisTovora[0];
String s2 = opisTovora[0];
//if(s1.equals(s2)){
System.out.println(s1 + " == " + s2);
System.out.println("LAHKO DODAM TOVOR #" + (i+1) + " => V VAGON #" + stevec);
break;
//}
}
if(tmp.tipTovora){
System.out.println("LAHKO DODAM TOVOR #" + (i+1) + " => V VAGON #" + stevec);
break;
}
}
stevec++;
tmp = tmp.next;
}
Your exception is on this line - String s1 = tmp.opisTovora[0]. It means that tmp.opisTovora is an empty array, so tmp.opisTovora[0] is out of the bounds of that array.
It has nothing to do with equals.
I did a lot of searching on this subject, but I couldn't find anything usable for my problem: I'm making a simple memory game in Java based on an integer array. I want the array to contain only duplicate entries and no unique ones. Unfortunately most of the questions here are dealing with avoiding or removing duplicate entries, but what about enforcing them?
My code so far looks like this.
public Field[] getField(){
Random r = new Random();
int pool = 16;
ArrayList<Integer> used = new ArrayList<Integer>();
int rand = r.nextInt(pool);
System.out.println("First random: " + rand);
for(int i = 0; i < fields.length; i++){
System.out.println("ITERATION " + i + " STARTED");
while(used.contains(rand)){
System.out.println(rand + " is used, recalculating...");
rand = r.nextInt(pool);
System.out.println("New random is " + rand);
}
fields[i] = new Field(rand);
System.out.println(rand + " added in Field " + i);
int tmp = r.nextInt(fields.length - 1);
System.out.println("First tmp calculated: " + tmp);
while(fields[tmp] != null && i <= fields.length / 2){
tmp = r.nextInt(fields.length - 1);
System.out.println("Field " + tmp + " is used, looking for another...");
}
fields[tmp] = new Field(rand);
System.out.println(rand + " added in temp Field " + tmp);
used.add(rand);
System.out.println("ITERATION " + i + " ENDED");
System.out.println();
}
return fields;
}
fields[] is an array of the type Field (basically has just one member (int id).
If I'm understanding what you're after correctly, I think you're probably making this a lot harder than it has to be.
It is much easier to iterate over your fields array in order and add two Fields of the same value each iteration, then shuffle the array. Something like the following code:
{
...
for (int i = 0; i < fields.length; i += 2)
fields[i] = fields[i + 1] = new Field(r.nextInt(pool));
shuffleFields(fields);
return fields;
}
You can take your pick of shuffling algorithms. The Fisher-Yates shuffle is popular. E.g.:
void shuffleFields (Field[] fields)
{
Random r = new Random();
for (int i = fields.length - 1; i >= 1; --i)
{
int j = r.nextInt(i + 1);
Field t = fields[i];
fields[i] = fields[j];
fields[j] = temp;
}
}