logo

תוכנית FizzBuzz ב-Java

FizzBuzz הוא משחק פופולרי בקרב ילדים. על ידי משחק זה, הילדים לומדים את החלוקה. עכשיו ה FizzBuzz המשחק הפך לשאלת תכנות פופולרית שנשאלת לעתים קרובות ב תכנות ג'אווה ראיונות. בחלק זה נלמד כיצד ליצור א תוכנית FizzBuzz ב-Java .

חוקי המשחק FizzBuzz

הכללים של משחק FizzBuzz הם פשוטים מאוד.

  • אמר קֶצֶף אם המספר מתחלק ב 3 .
  • אמר זִמזוּם אם המספר מתחלק ב 5 .
  • אמר FizzBuzz אם המספר מתחלק ב שניהם 3 ו-5.
  • החזר את מספר עצמו, אם המספר הוא לא ניתן לחלוקה לפי 3 ו-5.

הערה: במקום 3 ו-5, אתה יכול להשתמש גם במחלקים שונים (כמו 5 ו-7 וכו') ובמחרוזת (Fizz ו-Buzz).

בואו ליישם את הכללים לעיל בתוכנית Java.

תוכנית Java FizzBuzz

ישנן שתי דרכים ליצור תוכנית FizzBuzz ב-Java:

מה זה מאבן
  • שימוש ב-else-if Statement
  • משתמש ב-Java 8

שימוש במשפט else-if

בתוכנית הבאה, אנו קוראים מספר שלם (n) מהמשתמש שהוא הגבול העליון להדפסת Fizz או Buzz או FizzBuzz. לולאת for מתחילה מ-1 ופועלת עד לתנאי i<=n 3 5 becomes false. the else-if statement to check number is multiple of and or not.< p>

FizzBuzzExample1.java

 import java.util.Scanner; public class FizzBuzzExample1 { public static void main(String args[]) { //constructor of the scanner class Scanner sc = new Scanner(System.in); System.out.print(&apos;Enter the number: &apos;); //reads an integer from the user int n = sc.nextInt(); System.out.println(&apos;The Fizz, Buzz, and FizzBuzz numbers are: &apos;); //for loop executes until the condition i<=n 3 5 becomes false for (int i="1;" <="n;" i++) { returns true if both the conditions return (i%3="=0" && i%5="=0)" prints number is multiple of and system.out.print('fizzbuzz'); } executes condition else system.out.print('fizz'); (i%5="=0)" system.out.print('buzz'); itself not divisible by system.out.print(i); space system.out.print(','+' '); close scanner sc.close(); pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/java-tutorial/88/fizzbuzz-program-java.webp" alt="FizzBuzz Program in Java"> <h3>Using Java 8</h3> <p>Java 8 provides the <strong>IntStream</strong> interface. We have used the following two methods of the IntStream interface.</p> <p> <strong>rangeClosed() Method:</strong> It is the static method of the IntStream interface. It returns a sequential IntStream for the specified range.</p> <p> <strong>Syntax:</strong> </p> <pre> static IntStream rangeClosed(int startInclusive, int endInclusive) </pre> <p>The method parses two parameters:</p> <ul> <tr><td>startInclusive:</td> It is the initial value. </tr><tr><td>endInclusive:</td> The inclusive upper bound. </tr></ul> <h3>Using mapToObj() Method</h3> <p>The method performs an intermediate operation and returns an object-valued Stream consisting of the results of applying the given function to the elements of this stream.</p> <p> <strong>Syntax:</strong> </p> <pre> Stream mapToObj(IntFunction mapper) </pre> <p>The method parses a parameter <strong>mapper</strong> (of element type of new stream). It returns the new stream.</p> <p> <strong>FizzBuzzExample2.java</strong> </p> <pre> import java.util.*; import java.util.stream.IntStream; public class FizzBuzzExample2 { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.print(&apos;Enter the number:&apos;); //reads an integer from the user int num = sc.nextInt(); //the rangeClosed() method returns a sequential IntStream for the specified range of int elements //for-each iterate over the Stream and prints the elements IntStream.rangeClosed(1, num).mapToObj(i-&gt;i%3==0?(i%5==0? &apos;FizzBuzz &apos;:&apos;Fizz &apos;):(i%5==0? &apos;Buzz &apos;: i+&apos; &apos;)).forEach(System.out::print); //close the Scanner sc.close(); } } </pre> <p> <strong>Output:</strong> </p> <pre> Enter the number: 40 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 16 17 Fizz 19 Buzz Fizz 22 23 Fizz Buzz 26 Fizz 28 29 FizzBuzz 31 32 Fizz 34 Buzz Fizz 37 38 Fizz Buzz </pre> <p>Note that, in the above program the logic for FizzBuzz is adjusted into one line by using the <a href="/ternary-operator-java">ternary operator</a> . It reduces the line of code. We have printed <strong>Fizz</strong> if the number is multiple of 3, prints <strong>Buzz</strong> if the number is multiple of 5, prints <strong>FizzBuzz</strong> if the number is multiple of 3 and 5, else prints the <strong>number</strong> itself.</p> <hr></=n>

השיטה מנתחת שני פרמטרים:

    התחלה כולל:זה הערך ההתחלתי.לְרַבּוֹת:הגבול העליון הכולל.

שימוש בשיטת mapToObj()

השיטה מבצעת פעולת ביניים ומחזירה זרם בעל ערך אובייקט המורכב מתוצאות יישום הפונקציה הנתונה על האלמנטים של זרם זה.

תחביר:

 Stream mapToObj(IntFunction mapper) 

השיטה מנתחת פרמטר ממפה (מסוג אלמנט של זרם חדש). זה מחזיר את הזרם החדש.

FizzBuzzExample2.java

 import java.util.*; import java.util.stream.IntStream; public class FizzBuzzExample2 { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.print(&apos;Enter the number:&apos;); //reads an integer from the user int num = sc.nextInt(); //the rangeClosed() method returns a sequential IntStream for the specified range of int elements //for-each iterate over the Stream and prints the elements IntStream.rangeClosed(1, num).mapToObj(i-&gt;i%3==0?(i%5==0? &apos;FizzBuzz &apos;:&apos;Fizz &apos;):(i%5==0? &apos;Buzz &apos;: i+&apos; &apos;)).forEach(System.out::print); //close the Scanner sc.close(); } } 

תְפוּקָה:

קיצורי דרך עם כל הכותרות Excel
 Enter the number: 40 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 16 17 Fizz 19 Buzz Fizz 22 23 Fizz Buzz 26 Fizz 28 29 FizzBuzz 31 32 Fizz 34 Buzz Fizz 37 38 Fizz Buzz 

שימו לב שבתוכנית לעיל ההיגיון של FizzBuzz מותאם לשורה אחת על ידי שימוש ב- מפעיל שליש . זה מקטין את שורת הקוד. הדפסנו קֶצֶף אם המספר הוא כפולה של 3, מודפס זִמזוּם אם המספר הוא כפולה של 5, מודפס FizzBuzz אם המספר הוא כפול של 3 ו-5, אחרת מדפיס את ה מספר עצמו.