1 / 43

JAVA Programcılığı 2.1.1

JAVA Programcılığı 2.1.1. Ali R+ SARAL. Ders Planı 2.1.1. Arrays Strings Operating on Strings Joining Strings Comparing Strings Checking the Start and End of a String Sequencing Strings. Arrays Diziler. Array Variables Dizi Değişkenler.

Télécharger la présentation

JAVA Programcılığı 2.1.1

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. JAVA Programcılığı 2.1.1 Ali R+ SARAL

  2. Ders Planı 2.1.1 • Arrays • Strings • Operating on Strings Joining Strings Comparing Strings Checking the Start and End of a String Sequencing Strings

  3. Arrays Diziler • .

  4. Array VariablesDizi Değişkenler • int[] primes; // Declare an integer array variable • int primes[]; // Declare an integer array variable

  5. Defining an Array Bir Dizi Tanımlamak • primes = new int[10]; // Define an array of 10 integers • int [ ] primes = new int[10]; • double[] myArray = new double[100];

  6. Defining an Array Bir Dizi Tanımlamak

  7. The Length of an ArrayBir Dizinin Uzunluğu • myArray.length

  8. Accessing Array ElementsDizi Elemanlarına Erişim • As I mentioned earlier, you refer to an element of an array by using the array name followed by the element’s • index value enclosed between square brackets. • double X = myarray[11];

  9. Reusing Array VariablesDizi Değişkenleri Yeniden Kullanım • int[] primes = new int[10]; // Allocate an array of 10 integer elements • primes = new int[50]; // Allocate an array of 50 integer elements

  10. Initializing Arrays Dizilere İlk Değer Verilişi • int[] primes = {2, 3, 5, 7, 11, 13, 17}; // An array of 7 elements • int[] primes = new int[100]; • primes[0] = 2; • primes[1] = 3; • double[] data = new double[50]; // An array of 50 values of type double • for(int i = 0 ; i<data.length ; i++) { // i from 0 to data.length-1 • data[i] = 1.0; • }

  11. Using a Utility Method to Initialize an ArrayBir Diziye Otomatik Olarak Değer Vermek • Arrays.fill(data, 1.0); // Fill all elements of data with 1.0 • import java.util.Arrays; • java.util.Arrays.fill(data, 1.0); // Fill all elements of data with 1.0

  12. Using a Utility Method to Initialize an ArrayBir Diziye Otomatik Olarak Değer Vermek Of course, because fill() is a static method in the Arrays class, you could import the method name into your source file: • import static java.util.Arrays.fill; • Now you can call the method with the name unadorned with the class name: • fill(data, 1.0); // Fill all elements of data with 1.0

  13. Initializing an Array Variable Bir Dizi Değişkenine İlk Değer Vermek • long[] even = {2L, 4L, 6L, 8L, 10L}; • long[] value = even;

  14. Using ArraysDizileri Nasıl Kullanırız? • double[] samples = new double[50]; // An array of 50 double values • for(int i = 0; i < samples.length; i++) { samples[i] = 100.0*Math.random(); // Generate random values } • double result = (samples[10]*samples[0] – Math.sqrt(samples[49]))/samples[29];

  15. Using ArraysDizileri Nasıl Kullanırız? • double average = 0.0; // Variable to hold the average • for(int i = 0; i < samples.length; i++) { average += samples[i]; // Sum all the elements } • average /= samples.length; // Divide by the total number of elements

  16. Using the Collection-Based for Loop with an Array • double average = 0.0; // Variable to hold the average • for(double value : samples) { average += value; // Sum all the elements • } • average /= samples.length; // Divide by the total number of elements

  17. EXAMPLE - Try It Out Even More Primes import static java.lang.Math.ceil; import static java.lang.Math.sqrt; public class MorePrimes { public static void main(String[] args) { long[] primes = new long[20]; // Array to store primes primes[0] = 2L; // Seed the first prime primes[1] = 3L; // and the second int count = 2; // Count of primes found – up to now, // which is also the array index long number = 5L; // Next integer to be tested outer:

  18. EXAMPLE - Try It Out Even More Primes for( ; count < primes.length; number += 2L) { // The maximum divisor we need to try is square root of number long limit = (long)ceil(sqrt((double)number)); // Divide by all the primes we have up to limit for(int i = 1; i < count && primes[i] <= limit; i++) { if(number%primes[i] == 0L) { // Is it an exact divisor? continue outer; // Yes, so try the next number } } primes[count++] = number; // We got one! } for(long n : primes) { System.out.println(n); // Output all the primes } } }

  19. Arrays of Arrays Dizilerden Oluşan Diziler • float[][] temperature = new float[10][365]; • float [][] temperature; // Declare the array variable • temperature = new float[10][365]; // Create the array

  20. EXAMPLE - Try It Out The Weather Fanatic public class WeatherFan { public static void main(String[] args) { float[][] temperature = new float[10][365]; // Temperature array // Generate random temperatures for(int i = 0; i<temperature.length; i++) { for(int j = 0; j < temperature[i].length; j++) { temperature[i][j] = (float)(45.0*Math.random() – 10.0); } }

  21. EXAMPLE - Try It Out The Weather Fanatic // Calculate the average per location for(int i = 0; i<temperature.length; i++) { float average = 0.0f; // Place to store the average for(int j = 0; j < temperature[i].length; j++) { average += temperature[i][j]; } // Output the average temperature for the current location System.out.println(“Average temperature at location “ + (i+1) + “ = “ + average/(float)temperature[i].length); } } }

  22. Arrays of Arrays of Varying LengthDeğişken Uzunlukta Dizilerden Oluşan Diziler • float[][] samples; // Declare an array of arrays • samples = new float[6][]; // Define 6 elements, each is an array • samples[2] = new float[6]; // The 3rd array has 6 elements • samples[5] = new float[101]; // The 6th array has 101 elements

  23. Multidimensional Arrays Çok Boyutlu Diziler • long[][][] beans = new long[5][10][30]; • long[][][] beans = new long[3][][]; // Three two-dimensional arrays • beans[0] = new long[4][]; • beans[1] = new long[2][]; • beans[2] = new long[5][]; • for(int i = 0; i<beans.length; i++) // Vary over 1st dimension • for(int j = 0; j<beans[i].length; j++) // Vary over 2nd dimension • beans[i][j] = new long[(int)(1.0 + 6.0*Math.random())];

  24. Arrays of Characters Harf Dizileri • char[] message = new char[50]; • java.util.Arrays.fill(message, ‘ ‘); // Store a space in every element • char[] vowels = { ‘a’, ‘e’, ‘i’, ‘o’, ‘u’}; • char[] sign = {‘F’, ‘l’, ‘u’, ‘e’, ‘n’, ‘t’, ‘ ‘, • ‘G’, ‘i’, ‘b’, ‘b’, ‘e’, ‘r’, ‘i’, ‘s’, ‘h’, ‘ ‘, • ‘s’, ‘p’, ‘o’, ‘k’, ‘e’, ‘n’, ‘ ‘, • ‘h’, ‘e’, ‘r’, ‘e’};

  25. Strings Sözcükler • .

  26. String LiteralsSözcüklerin Yazılışı • “This is a string literal!” • System.out.println(“This is \na string constant!”);

  27. Creating String Objects • String myString = “My inaugural string”; • myString = “Strings can be knotty”; • String anyString; // Uninitialized String variable • String anyString = null; // String variable that doesn’t reference a string • if(anyString == null) { • System.out.println(“anyString does not refer to anything!”); • } • String message = “Only the mediocre are always at their best”; • Message=null;

  28. Creating String ObjectsSözcük Nesnelerinin Oluşturuluşu

  29. Arrays of StringsSözcük Dizileri • String[] names = new String[5]; • public static void main(String[] args) { • // Code for method... • } • String[] colors = {“red”, “orange”, “yellow”, “green”, “blue”, “indigo”, violet”};

  30. EXAMPLE - Try It Out Twinkle, Twinkle, Lucky Star public class LuckyStars { public static void main(String[] args) { String[] stars = { “Robert Redford” , “Marilyn Monroe”, “Boris Karloff” , “Lassie”, “Hopalong Cassidy”, “Trigger” }; System.out.println(“Your lucky star for today is “ + stars[(int)(stars.length*Math.random())]); } }

  31. Operations on Strings - Joining StringsSözcükler Üzerinde İşlemler - Yapıştırma • myString = “The quick brown fox” + “ jumps over the lazy dog”; • String date = “31st “; • String month = “December”; • String lastDay = date + month; // Result is “31st December” • String phrase = “Too many”; • phrase += “ cooks spoil the broth”;

  32. EXAMPLE - Try It Out String Concatenation public class JoinStrings { public static void main(String[] args) { String firstString = “Many “; String secondString = “hands “; String thirdString = “make light work”; String myString; // Variable to store results // Join three strings and store the result myString = firstString + secondString + thirdString; System.out.println(myString); // Convert an integer to String and join with two other strings int numHands = 99; myString = numHands + “ “ + secondString + thirdString; System.out.println(myString); // Combining a string and integers myString = “fifty five is “ + 5 + 5; System.out.println(myString); // Combining integers and a string myString = 5 + 5 + “ is ten”; System.out.println(myString); } }

  33. Comparing StringsSözcüklerin Karşılaştırılışı • To compare values stored in variables of the primitive types for equality, you use the == operator. • This does not apply to String objects (or any other objects). The expression string1 == string2 will check whether the two String variables refer to the same string. If they reference separate strings, this expression will have the value false, regardless of whether or not the strings happen to be identical.

  34. EXAMPLE - Try It Out Two Strings, Identical but Not the Same public class MatchStrings { public static void main(String[] args) { String string1 = “Too many “; String string2 = “cooks”; String string3 = “Too many cooks”; // Make string1 and string3 refer to separate strings that are identical string1 += string2; // Display the contents of the strings System.out.println(“Test 1”); System.out.println(“string3 is now: “ + string3); System.out.println(“string1 is now: “ + string1); if(string1 == string3) // Now test for identity System.out.println(“string1 == string3 is true.” + “ string1 and string3 point to the same string”); else System.out.println(“string1 == string3 is false.” + “ string1 and string3 do not point to the same string”);

  35. EXAMPLE - Try It Out Two Strings, Identical but Not the Same // Now make string1 and string3 refer to the same string string3 = string1; // Display the contents of the strings System.out.println(“\n\nTest 2”); System.out.println(“string3 is now: “ + string3); System.out.println(“string1 is now: “ + string1); if(string1 == string3) // Now test for identity System.out.println(“string1 == string3 is true.” + “ string1 and string3 point to the same string”); else System.out.println(“string1 == string3 is false.” + “ string1 and string3 do not point to the same string”); } }

  36. Comparing Strings for EqualitySözcüklerin Eşitlik Karşılaştırılışı • if(string1.equals(string3)) { System.out.println(“string1.equals(string3) is true.” + “ so strings are equal.”); } • if(string3.equals(string1)) { System.out.println(“string3.equals(string1) is true.” + “ so strings are equal.”); }

  37. EXAMPLE - Try It Out String Identity public class MatchStrings2 { public static void main(String[] args) { String string1 = “Too many “; String string2 = “cooks”; String string3 = “Too many cooks”; // Make string1 and string3 refer to separate strings that are identical string1 += string2; // Display the contents of the strings System.out.println(“Test 1”); System.out.println(“string3 is now: “ + string3); System.out.println(“string1 is now: “ + string1); if(string1.equals(string3)) { // Now test for equality System.out.println(“string1.equals(string3) is true.” + “ so strings are equal.”); } else { System.out.println(“string1.equals(string3) is false.” + “ so strings are not equal.”); }

  38. EXAMPLE - Try It Out String Identity // Now make string1 and string3 refer to strings differing in case string3 = “TOO many cooks”; // Display the contents of the strings System.out.println(“\n\nTest 2”); System.out.println(“string3 is now: “ + string3); System.out.println(“string1 is now: “ + string1); if(string1.equals(string3)) { // Compare for equality System.out.println(“string1.equals(string3) is true “ + “ so strings are equal.”); } else { System.out.println(“string1.equals(string3) is false” + “ so strings are not equal.”); } if(string1.equalsIgnoreCase(string3)) { // Compare, ignoring case System.out.println(“string1.equalsIgnoreCase(string3) is true” +“ so strings are equal ignoring case.”); } else { System.out.println(“string1.equalsIgnoreCase(string3) is false” +“ so strings are different.”); } } }

  39. String Interning • String string1 = “Too many “; • String string2 = “cooks”; • String string3 = “Too many cooks”; • // Make string1 and string3 refer to separate strings that are identical • string1 += string2; • string1 = string1.intern(); // Intern string1 • The intern() method will check the string referenced by string1 against all the String objects currently • in existence. If it already exists, the current object will be discarded, and string1 will contain a • reference to the existing object encapsulating the same string.

  40. Checking the Start and End of a String Bir Sözcüğün Başlangıç ve Son Kontrolü • String string1 = “Too many cooks”; • if(string1.startsWith(“Too”)) { • System.out.println(“The string does start with \”Too\” too!”); • } • string1.endsWith(“cooks”)

  41. Sequencing StringsSözcükleri Dizmek • string1.compareTo(string2) will return a positive value as a result of comparing the fifth characters in the strings: the ‘d’ in string1 with the ‘c’ in string2. • the longer string is greater than the shorter string, so “catamaran” is greater than “cat”.

  42. EXAMPLE - Try It Out Ordering Strings public class SequenceStrings { public static void main(String[] args) { // Strings to be compared String string1 = “A”; String string2 = “To”; String string3 = “Z”; // Strings for use in output String string1Out = “\”” + string1 + “\””; // string1 with quotes String string2Out = “\”” + string2 + “\””; // string2 with quotes String string3Out = “\”” + string3 + “\””; // string3 with quotes // Compare string1 with string3 if(string1.compareTo(string3) < 0) { System.out.println(string1Out + “ is less than “ + string3Out); } else { if(string1.compareTo(string3) > 0) { System.out.println(string1Out +“ is greater than “+ string3Out); } else { System.out.println(string1Out + “ is equal to “ + string3Out); } }

  43. EXAMPLE - Try It Out Ordering Strings // Compare string2 with string1 if(string2.compareTo(string1) < 0) { System.out.println(string2Out + “ is less than “ + string1Out); } else { if(string2.compareTo(string1) > 0) { System.out.println(string2Out + “ is greater than “ + string1Out); } else { System.out.println(string2Out + “ is equal to “ + string1Out); } } } }

More Related