Social counter query - java

I have this challenge to create a facebook-like counter that will show how many people liked a post. I'm relatively new to Java, but have managed to do it. My question is - Is there a more practical and short way of writing the below method?
im just using a simple static array in the Main called users[] with some names in it.
public static void facebookCounter(String users[])
{
if(users.length == 1)
{
System.out.println(users[0] + " liked this");
}
else if(users.length == 2)
{
System.out.println(users[0] + " " + users[1] + " liked this.");
}
else if(users.length > 2)
{
System.out.println(users[0] + " " + users[1] + " and " + (users.length-2) + " others liked this");
}
}
Sorry if my pasted code is not formatted well, I pasted it from my intelliJ
Thanks to anyone who has any ideas!

Another approach could be using switch statement rather than if/else:
public static void facebookCounter(String users[]) {
switch (users.length) {
case 0: break;
case 1:
System.out.println(users[0] + " liked this");
break;
case 2:
System.out.println(users[0] + " " + users[1] + " liked this.");
break;
default:
System.out.println(users[0] + " " + users[1] + " and " + (users.length-2) + " others liked this");
}
}

My suggestion is to stream the first 1 or 2 array items (depending on array's length), collect to String with a joining space char. then, add appropriate suffix:
public static void facebookCounter(String users[])
{
String msg = IntStream.range(0, Math.min(2, users.length))
.mapToObj(i -> users[i])
.collect(Collectors.joining(" "));
if (users.length > 2) msg += " and " + (users.length-2) + " others";
msg += " liked this";
System.out.println(msg);
}
EDIT:
the suffix can be specified in the joining() method:
System.out.println(
IntStream.range(0, Math.min(2, users.length))
.mapToObj(i -> users[i])
.collect(Collectors.joining(" ", "",
users.length > 2 ? " and " + (users.length-2) + " others liked this" : " liked this"
)
)
);

Related

How can I print something based on the result of a boolean method?

I have two methods
*`public boolean validateMarks() {
return (this.qualifyingMarks >= 65 && this.qualifyingMarks <= 100);
}
public boolean validateCourseId() {
return (this.courseId >= 1001 && this.courseId <= 1005);
}`*
validateMarks(): Used to validate qualifying exam marks - qualifying marks is in the range of 65 to 100(both inclusive)
validateCourseId(): Used to validate the course entered, based on the courseId - given in the table above
calculateCourseFee(): Used to calculate the course fee after applying the discount.
So when is less than 65 print print "not elegible, you've failed" and when the course is not valid "course is not correct, please try again with the correct number of the course"
and this is my calculateCourseFee method
***if(this.validateMarks()) {
this.courseFee = fee - (fee * discount);
System.out.println("****Course Allocation Details****" + "\n" +
"Student Name: " + this.getStudentName() + "\n" +
"Course Id: " + this.getCourseId() + "\n" +
"Qualifying Exam Marks: " + this.getQualifyingMarks() + "\n" +
"Student's Registration Id: " + this.getRegistrationId() + "\n" +
"Total Course Fee: " + this.getCourseFee() + "\n" +
"Hostel Required: " + hostel);
}else {
System.out.println("wrong for marks ");
}
if(this.validateCourseId()) {
this.courseFee = fee - (fee * discount);
System.out.println("****Course Allocation Details****" + "\n" +
"Student Name: " + this.getStudentName() + "\n" +
"Course Id: " + this.getCourseId() + "\n" +
"Qualifying Exam Marks: " + this.getQualifyingMarks() + "\n" +
"Student's Registration Id: " + this.getRegistrationId() + "\n" +
"Total Course Fee: " + this.getCourseFee() + "\n" +
"Hostel Required: " + hostel);
}else {
System.out.println("Wroog for course");
}
***
I make two different ifs for the two requirements, but everytime I run it, it prints the else statement to, even if marks is greather than 65... am I missing something?
Reviewing my code and tell me what am I missing or what am I doing wrong
The portion of the code you have shown here seems to be working as expected.
public class Driver {
public static void main(String args[]) {
Eligible e1 = new Eligible();
e1.calculateCourseFee();
}
}
class Eligible{
int qualifyingMarks = 66;
int courseId = 1002;
public boolean validateMarks() {
return (this.qualifyingMarks >= 65 && this.qualifyingMarks <= 100);
}
public boolean validateCourseId() {
return (this.courseId >= 1001 && this.courseId <= 1005);
}
public void calculateCourseFee(){
if(this.validateMarks()) {
System.out.println("works for marks");
}else {
System.out.println("wrong for marks ");
}
if(this.validateCourseId()) {
System.out.println("works for course");
}else {
System.out.println("Wroog for course");
}
}
}
output:
works for marks
works for course
Maybe the issues is with how you set the values for the qualifyingMarks and courseId variables?
I wish I could give you a like or thumbs up, I finally did it, thanks to all of your answers you gave me, and I just combined the two ifs into one. here's the code:
if(this.validateCourseId() && this.validateMarks()) {
this.courseFee = fee - (fee * discount);
System.out.println("****Course Allocation Details****" + "\n" +
"Student Name: " + this.getStudentName() + "\n" +
"Course Id: " + this.getCourseId() + "\n" +
"Qualifying Exam Marks: " + this.getQualifyingMarks() + "\n" +
"Student's Registration Id: " + this.getRegistrationId() + "\n" +
"Total Course Fee: " + this.getCourseFee() + "\n" +
"Hostel Required: " + hostel);
}else if(!this.validateCourseId()) {
System.out.println("Wrong course");
}
else if(!this.validateMarks()) {
System.out.println("You've failed");
}
Thanks everyone!!
maybe qualifyingMarks is zero or another value, print qualifyingMarks in method "validateMarks",u will get the reason of your problem.

Trying to mimic Splitwise app logic - suggest a better way to handle settlements

I am trying to write the basic logic used in apps like Splitwise.
Input - Transactions in the trip
a|a,b,c,d|120
b|a,b,d|210
c|a,b,c,d|40
a|a,b,c|60
a, b, c and d are friends on a trip
in the first transaction a paid 120 units for a transaction involving all four friends
in the second transaction b paid 210 units for a transaction involving only a, b and d
there are n such transactions and there can be m friends
Expected Output
a has to get 50
b has to get 80
c has to give 20
d has to give 110
d has to give 80 to b
d has to give 30 to a
c has to give 20 to a
This is what I tried. Person class is the pojo used.
public class Person {
private String name;
private Integer totalExpense;
private Integer totalSpent;
private Integer balanceAmt;
}
This is the code for settle operation.
public void settle(Map<String, Person> personMap) {
List<Person> getterList = new ArrayList<>();
List<Person> giversList = new ArrayList<>();
for (String key : personMap.keySet()) {
Person user = personMap.get(key);
int balanceAmt = user.getTotalSpent() - user.getTotalExpense();
user.setBalanceAmt(Math.abs(balanceAmt));
if (balanceAmt > 0) {
System.out.println(key + " has to get " + balanceAmt);
getterList.add(user);
} else if (balanceAmt < 0) {
System.out.println(key + " has to give " + Math.abs(balanceAmt));
giversList.add(user);
} else if (balanceAmt == 0) {
System.out.println(key + " is all settled");
}
}
getterList.sort((p2, p1) -> p1.getBalanceAmt().compareTo(p2.getBalanceAmt()));
giversList.sort((p2, p1) -> p1.getBalanceAmt().compareTo(p2.getBalanceAmt()));
giversList.forEach(giver -> {
getterList.forEach(getter -> {
if (getter.getBalanceAmt() == 0) {
return;
}
if (giver.getBalanceAmt() == getter.getBalanceAmt()) {
System.out.println(giver.getName() + " has to give " + giver.getBalanceAmt() + " to " + getter.getName());
giver.setBalanceAmt(0);
getter.setBalanceAmt(0);
} else if (giver.getBalanceAmt() > getter.getBalanceAmt()) {
System.out.println(giver.getName() + " has to give " + getter.getBalanceAmt() + " to " + getter.getName());
giver.setBalanceAmt(giver.getBalanceAmt() - getter.getBalanceAmt());
getter.setBalanceAmt(0);
} else if (giver.getBalanceAmt() < getter.getBalanceAmt()) {
System.out.println(giver.getName() + " has to give " + giver.getBalanceAmt() + " to " + getter.getName());
giver.setBalanceAmt(0);
getter.setBalanceAmt(getter.getBalanceAmt() - giver.getBalanceAmt());
}
});
});
}
The code is not good, it has too many loops.
Suggest a good method to settle the amount and come up with the second part of the output.
Reduce your bottom part's logic from O(m2) to O(m) by using two pointer.
int giverPointer = 0;
int getterPointer = 0;
while(giverPointer < giversList.size() && getterPointer < getterList.size()){
if (giversList.get(giverPointer).getBalanceAmt() == getterList.get(getterPointer).getBalanceAmt()) {
System.out.println(giversList.get(giverPointer).getName() + " has to give " + giversList.get(giverPointer).getBalanceAmt() + " to " + getterList.get(getterPointer).getName());
giversList.get(giverPointer).setBalanceAmt(0);
getterList.get(getterPointer).setBalanceAmt(0);
giverPointer++;
getterPointer++;
} else if (giversList.get(giverPointer).getBalanceAmt() > getterList.get(getterPointer).getBalanceAmt()) {
System.out.println(giversList.get(giverPointer).getName() + " has to give " + getterList.get(getterPointer).getBalanceAmt() + " to " + getterList.get(getterPointer).getName());
giversList.get(giverPointer).setBalanceAmt(giversList.get(giverPointer).getBalanceAmt() - getterList.get(getterPointer).getBalanceAmt());
getterList.get(getterPointer).setBalanceAmt(0);
getterPointer++;
} else {
System.out.println(giversList.get(giverPointer).getName() + " has to give " + giversList.get(giverPointer).getBalanceAmt() + " to " + getterList.get(getterPointer).getName());
giversList.get(giverPointer).setBalanceAmt(0);
getterList.get(getterPointer).setBalanceAmt(getterList.get(getterPointer).getBalanceAmt() - giversList.get(giverPointer).getBalanceAmt());
giverPointer++;
}
}

JUnit Test Case Keeps Failing - toString

Not quite sure why this is failing, worked fine on a previous class/test pair.
Test:
#Test
public void testToString() {
OrderLine o = new OrderLine("Tuna 4 pack", 399 , 2);
String toStr = o.toString();
assertTrue("The toString method should be in the standard convention format",
toStr.startsWith("OrderLine:[") &&
toStr.contains("=" + o.getId() + ", ") &&
toStr.contains("=" + o.getUnitPrice() + ", ") &&
toStr.endsWith("=" + o.getQuantity() + "]"));
}
Class Function:
public String toString()
{
return ("OrderLine:[ ID = " + id +
", UnitPrice = " + unitPrice +
", Quantity = " + quantity +
"]");
}
Apologies if the answer to this is really obvious, its been grating me for some time and I don't exactly have any fellow students I can ask for help right now.
Thanks!
I had no idea that the spaces AFTER the equals mattered as my mind just seems to have read that they were irrelevant. I only put them there for the purpose of readability (my mistake I know)
This is the rectified code o.O
return ("OrderLine:[ID =" + id +
", UnitPrice =" + unitPrice +
", quantity =" + quantity +
"]");

Is there any possibility to get the currentStockLevel from this method?

I need the currentStockLevel for another void Method in java, is there any possibility to get it?
I think no, because of void right?
public void receive (int currentStock)
{
String outLine;
if (currentStockLevel > 0)
outLine = productCode;
{
outLine = ". Current Stock: " + currentStockLevel;
outLine += " Current Stock changed from " + currentStockLevel;
currentStockLevel += currentStock;
outLine += " to " + currentStockLevel;
int storeCost = wholeSalePrice * currentStockLevel;
System.out.println (productCode + ":" + " Received " + currentStockLevel + "." + " Store Cost " + "$" + storeCost + "." + " New stock level: " + currentStockLevel);
}

If statement always returns false

I have a series of if statements that all seem to work except for when I reach two arguments after a command (Minecraft Bukkit server/API). With two arguments it returns false no matter what. I am using the command /jukebox play 13 to test it.
Current code:
#SuppressWarnings("deprecation")
public boolean onCommand(CommandSender sender, Command cmd, String commandlabel, String[] args) {
Player p = (Player) sender;
if (cmd.getName().equalsIgnoreCase("jukebox")) {
if (args.length == 0) {
sender.sendMessage(ChatColor.GOLD + "** " + ChatColor.AQUA + "Jukebox version " + pdFile.getVersion() + ChatColor.GOLD + " **\n" + ChatColor.RED + "Usage: " + ChatColor.LIGHT_PURPLE + "/jukebox play (track)");
return true;
}
if (args.length == 1) {
if (args[0].equalsIgnoreCase("play")) {
String recordNames = "Stop, 13, Cat, Blocks, Chirp, Far, Mall, Mellohi, Stal, Strad, Ward, 11, Wait";
String regex = "\\[|\\]";
recordNames = recordNames.replaceAll(regex, "");
sender.sendMessage(ChatColor.AQUA + "Track selection: " + ChatColor.GREEN + recordNames + "\n" + ChatColor.AQUA + "Type " + ChatColor.LIGHT_PURPLE + "/jukebox play (track)" + ChatColor.AQUA + " to play a track.");
return true;
}
if (args.length == 2 && (args[0].equalsIgnoreCase("play"))) {
if (args[1].equalsIgnoreCase("13")) {
p.playEffect(p.getLocation(), Effect.RECORD_PLAY, 2256);
sender.sendMessage(ChatColor.AQUA + "Now playing " + ChatColor.GREEN + "13" + ChatColor.AQUA + ".");
return true;
}
else {
sender.sendMessage(ChatColor.AQUA + "Please enter a valid track name.");
}
}
}
}
return false;
}
}
Does anyone see why it is returning false? Just as a side note, if you see anything in here that could be coded more efficiently, feel free to suggest that too.
Your indention is throwing you off. Your closing braces are in the wrong place. Your args.length == 2 check is nested within the args.length ==1 check. At the minimum you will have to :
1. add a closing brace before the if statement for args.length == 2 check
2. delete a closing brace before the return false statement.
It looks like a bracket is in the wrong place:
if (args.length == 1) {
if (args[0].equalsIgnoreCase("play")) {
String recordNames = "Stop, 13, Cat, Blocks, Chirp, Far, Mall, Mellohi, Stal, Strad, Ward, 11, Wait";
String regex = "\\[|\\]";
recordNames = recordNames.replaceAll(regex, "");
sender.sendMessage(ChatColor.AQUA + "Track selection: " + ChatColor.GREEN + recordNames + "\n" + ChatColor.AQUA + "Type " + ChatColor.LIGHT_PURPLE + "/jukebox play (track)" + ChatColor.AQUA + " to play a track.");
return true;
}
should be:
if (args.length == 1) {
if (args[0].equalsIgnoreCase("play")) {
String recordNames = "Stop, 13, Cat, Blocks, Chirp, Far, Mall, Mellohi, Stal, Strad, Ward, 11, Wait";
String regex = "\\[|\\]";
recordNames = recordNames.replaceAll(regex, "");
sender.sendMessage(ChatColor.AQUA + "Track selection: " + ChatColor.GREEN + recordNames + "\n" + ChatColor.AQUA + "Type " + ChatColor.LIGHT_PURPLE + "/jukebox play (track)" + ChatColor.AQUA + " to play a track.");
return true;
}
}
notice the } at the end. Right now, you're code is doing this:
if(args.length == 1){
if(args.length > 1 && args[0].equalsIgnoreCase("play")){
}
}
which will always return false, as args cannot have a length of one, and also have a length greater than one
As other's have said, you've gotten the bracket nesting wrong, and your incorrect code indentation is misleading you.
Advice ... if you want to avoid this kind of problem in the future:
Pay more attention to your code style in general, and particularly indentation. It makes your code easier for >>you<< to read.
Use an IDE ... or a smart editor that is capable of correctly indenting Java. And make sure that you make use of its auto-indenting functionality.
If possible, configure your IDE / editor to use space characters not TAB characters for code indentation. If your code has TAB characters in it, then it will look different (i.e. incorrectly indented) on different systems.
As shoover pointed out the } for the if (args.length == 1) statement was in the wrong place.
The new code is:
#SuppressWarnings("deprecation")
public boolean onCommand(CommandSender sender, Command cmd, String commandlabel, String[] args) {
Player p = (Player) sender;
if (cmd.getName().equalsIgnoreCase("jukebox")) {
if (args.length == 0) {
sender.sendMessage(ChatColor.GOLD + "** " + ChatColor.AQUA + "Jukebox version " + pdFile.getVersion() + ChatColor.GOLD + " **\n" + ChatColor.RED + "Usage: " + ChatColor.LIGHT_PURPLE + "/jukebox play (track)");
return true;
}
if (args.length == 1) {
if (args[0].equalsIgnoreCase("play")) {
String recordNames = "Stop, 13, Cat, Blocks, Chirp, Far, Mall, Mellohi, Stal, Strad, Ward, 11, Wait";
String regex = "\\[|\\]";
recordNames = recordNames.replaceAll(regex, "");
sender.sendMessage(ChatColor.AQUA + "Track selection: " + ChatColor.GREEN + recordNames + "\n" + ChatColor.AQUA + "Type " + ChatColor.LIGHT_PURPLE + "/jukebox play (track)" + ChatColor.AQUA + " to play a track.");
return true;
}
}
if (args.length > 1 && (args[0].equalsIgnoreCase("play"))) {
if (args[1].equalsIgnoreCase("13")) {
p.playEffect(p.getLocation(), Effect.RECORD_PLAY, 2256);
sender.sendMessage(ChatColor.AQUA + "Now playing " + ChatColor.GREEN + "13" + ChatColor.AQUA + ".");
return true;
}
else {
sender.sendMessage(ChatColor.AQUA + "Please enter a valid track name.");
return true;
}
}
}
return false;

Categories

Resources