Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP C C++ C# AWS W3.CSS HOW TO BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING INTRO TO HTML & CSS BASH RUST TOOLS

Java Tutorial

Java HOME Java Intro Java Get Started Java Syntax Java Output Java Comments Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Math Java Booleans Java If...Else Java Switch Java While Loop Java For Loop Java Break/Continue Java Arrays

Java Methods

Java Methods Java Method Challenge Java Method Parameters Java Method Overloading Java Scope Java Recursion

Java Classes

Java OOP Java Classes/Objects Java Class Attributes Java Class Methods Java Class Challenge Java Constructors Java this Keyword Java Modifiers Java Encapsulation Java Packages / API Java Inheritance Java Polymorphism Java super Keyword Java Inner Classes Java Abstraction Java Interface Java Anonymous Java OOP Visuals Java Enum Java User Input Java Date

Java Errors

Java Errors Java Debugging Java Exceptions Java Multiple Exceptions Java try-with-resources

Java Problem Solving

Java Problem Solving Java Build the Logic Java Test Cases

Java File Handling

Java Files Java Create Files Java Write Files Java Read Files Java Delete Files

Java I/O Streams

Java I/O Streams Java FileInputStream Java FileOutputStream Java BufferedReader Java BufferedWriter

Java Data Structures

Java Data Structures Java Collections Java List Java ArrayList Java LinkedList Java List Sorting Java Set Java HashSet Java TreeSet Java LinkedHashSet Java Map Java HashMap Java TreeMap Java LinkedHashMap Java Iterator Java Algorithms

Java Advanced

Java Wrapper Classes Java Generics Java Annotations Java RegEx Java Threads Java Lambda Java Optional Java Advanced Sorting

Java Projects

Java Projects

Java Cert

Java Certificate

Java How To's

Java How Tos

Java Examples

Java Examples Java Videos Java Compiler Java Exercises Java Quiz Java Code Challenges Java Practice Problems Java Server Java Syllabus Java Study Plan Java Interview Q&A

Java Reference

Java Reference Java Keywords ArrayList Methods Arrays Methods BufferedReader BufferedWriter Character Methods Collections Methods Comparator Methods Date and Time Enum Methods Errors & Exceptions File Methods FileInputStream FileOutputStream FileReader FileWriter HashMap Methods HashSet Methods Integer Methods Iterator Methods LinkedHashMap Methods LinkedHashSet Methods LinkedList Methods Math Methods Optional Methods Output Methods Random Methods RegEx Methods Scanner Methods String Methods StringBuilder Methods System Methods Thread Methods TreeMap Methods TreeSet Methods


Java Build the Logic


Share

What is Logic?

In the previous chapter, you learned the four steps of problem solving. For many beginners, step 2 is the hardest: you understand the problem, but you do not know what code to write.

The plan is called the logic of the program: the steps and decisions that turn the input into the output.

The good news: many problems are built from the same few building blocks. When you can spot them, the code is much easier to write.


The Building Blocks

A building block is a small piece of code that does one common job. You can use it again and again, in many different programs.

Each block below uses a loop to look at the values one at a time. With each value, it does one small job: count it, add it, compare it, or look for it. The words in the question tell you which block you need:

Block The problem asks... Code inside the loop
Count "How many ...?" if (p > 80) { count++; }
Sum "What is the total ...?" sum += p;
Max or Min "What is the highest ...?" if (p > max) { max = p; }
Search "Is there a ...?" if (p == 100) { found = true; }

This example uses all four blocks on the points of five players in a game:

Example

public class Main {
  public static void main(String[] args) {
    int[] points = {72, 95, 61, 88, 79};
    int count = 0;
    int sum = 0;
    int max = points[0];
    boolean found = false;

    for (int p : points) {
      if (p > 80) {    // Count
        count++;
      }
      sum += p;        // Sum
      if (p > max) {   // Max
        max = p;
      }
      if (p == 100) {  // Search
        found = true;
      }
    }

    System.out.println("More than 80 points: " + count);
    System.out.println("Total points: " + sum);
    System.out.println("Best score: " + max);
    System.out.println("Anyone with 100? " + found);
  }
}

Result:

More than 80 points: 2
Total points: 395
Best score: 95
Anyone with 100? false
Try it Yourself »

Which Block Do You Need?

Spotting the right block gets easier with practice. Try it now: for each question about the game, choose the block you need:

Question

Code


Explanation



Tips for Building Logic

  • Look for the question words: "how many" (Count), "total" (Sum), "highest" or "lowest" (Max or Min), and "is there" (Search).
  • Choose the start value first: count = 0, sum = 0, max = points[0] or found = false.
  • Many problems use more than one block. An average, for example, is a sum divided by the number of values.

Many of our Java Practice Problems are built from these blocks, like Sum of Numbers, Average Score and Min and Max.




Free account

Track your progress

XP earned 0 Day streak 0 Spaces 0 League —

New

Learn in Adventure Mode W3Schools Adventure App

Coding fundamentals as bite-sized lessons and challenges.

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.