Last active
December 11, 2019 21:43
-
-
Save fmaylinch/c304943b2fb2c9db6dc76c59b766d7d6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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