Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@fmaylinch
Last active December 11, 2019 21:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fmaylinch/c304943b2fb2c9db6dc76c59b766d7d6 to your computer and use it in GitHub Desktop.
Save fmaylinch/c304943b2fb2c9db6dc76c59b766d7d6 to your computer and use it in GitHub Desktop.
import java.util.*;
public class Example {
// TODO: Exercise:
// Write a function that given a list of words and a number n, returns list of the words longer than n.
public static void main(String[] args) {
List<String> words;
words = new ArrayList<String>();
words.add("Vino");
words.add("Queso");
words.add("Uvas");
words.add("Manzana");
words.add("Ajo");
String longest = longestWord(words);
System.out.println("longest = " + longest);
System.out.println( listOfMoney(5) );
}
/** Returns a list like this ["1€", "2€", ... "n€"] */
public static List<String> listOfMoney(int n) {
List<String> result;
result = new ArrayList<String>(); // create an empty list
for (int i = 1; i <= n; i++) {
result.add(i + "€");
}
return result;
}
/** Returns the longest word */
public static String longestWord(List<String> words) {
String result = "";
for (String word : words) {
if (word.length() > result.length()) {
result = word;
}
}
return result;
}
public static void examples() {
Person p; // (local variable)
p = new Person();
p.name = "Ferran";
p.surname = "Maylinch";
p.age = 40;
String fullName = p.fullName();
System.out.println(fullName);
List<String> words;
words = new ArrayList<String>(); // Creates a new empty list
words.add("Vino");
words.add("Queso");
words.add("Uvas");
System.out.println("words = " + words);
System.out.println(words.get(1));
System.out.println("There are " + words.size() + " words");
int lastIndex = words.size() - 1;
System.out.println(words.get(lastIndex));
int i = 0;
while (i < words.size()) {
System.out.println("- " + words.get(i));
i += 1;
}
// fori
for (int j = 0; j < words.size(); j += 1) {
System.out.println("- " + words.get(j));
}
// iter
// for (TYPE x : list)
for (String word : words) {
System.out.println("+ " + word);
}
}
}
class Person {
// fields, properties (instance variables)
String name;
String surname;
int age;
// methods, functions
public String fullName() {
String result = name + surname;
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment