GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Tutorials
  • My W3Schools
  • W3Schools app iOS & Android NEW
  • Spaces
  • Get Certified
  • Plus
  • Practice
  • Campus (previously Academy)
  • Logout
  • 
  • 
  • 
  • 
  • Sign in

This view

  • Original page
  • New address

GeezerVison is showing www.w3schools.com — Java Problem Solving

Menu
Search field
×
See More  
NEW W3Schools app iOS & Android Start the adventure
Sign In
★ +1 Spaces Upgrade Paid Courses Spaces Upgrade Paid Courses
   ❮     
     ❯   
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
Syntax Statements Code Challenge
Java Output
Print Text Print Numbers Code Challenge
Java Comments Java Variables
Variables Print Variables Multiple Variables Identifiers Constants (Final) Real-Life Examples Code Challenge
Java Data Types
Data Types Numbers Booleans Characters Real-Life Example Non-primitive Types The var Keyword Code Challenge
Java Type Casting Java Operators
Operators Arithmetic Assignment Comparison Logical Precedence Code Challenge
Java Strings
Strings Concatenation Numbers and Strings Special Characters StringBuilder Code Challenge
Java Math Java Booleans
Booleans Real-Life Example Code Challenge
Java If...Else
if else else if Short Hand If...Else Nested If Logical Operators Real-Life Examples Code Challenge
Java Switch
Switch Code Challenge
Java While Loop
While Loop Do/While Loop Real-Life Examples Code Challenge
Java For Loop
For Loop Nested Loops For-Each Loop Real-Life Examples Code Challenge
Java Break/Continue Java Arrays
Arrays Loop Through an Array Real-Life Examples Multidimensional Arrays Code Challenge

Java Methods

Java Methods Java Method Challenge Java Method Parameters
Parameters Return Values Code Challenge
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
Access Modifiers Non-Access 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
Enums Enum Constructor
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 Projects

Java Projects

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 Cert

Java Certificate

Java How To's

Java How Tos
How Tos Add Two Numbers Swap Two Variables Even or Odd Number Reverse a Number Positive or Negative Square Root Area of Rectangle Celsius to Fahrenheit Sum of Digits Check Armstrong Num Random Number Count Words Count Vowels in a String Remove Vowels Count Digits in a String Reverse a String Palindrome Check Check Anagram Convert String to Array Remove Whitespace Count Character Frequency Sum of Array Elements Find Array Average Sort an Array Find Smallest Element Find Largest Element Second Largest Array Min and Max Array Merge Two Arrays Remove Duplicates Find Duplicates Shuffle an Array Factorial of a Number Fibonacci Sequence Find GCD Check Prime Number ArrayList Loop HashMap Loop Loop Through an Enum

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
assert abstract boolean break byte case catch char class continue const default do double else enum exports extends final finally float for goto if implements import instanceof int interface long module native new package private protected public return requires short static strictfp super switch synchronized this throw throws transient try var void volatile while
ArrayList Methods
add() addAll() clear() clone() contains ensureCapacity() forEach() get() indexOf() isEmpty() iterator() lastIndexOf() listIterator() remove() removeAll() removeIf() replaceAll() retainAll() set() size() sort() spliterator() subList() toArray() trimToSize()
Arrays Methods
compare() copyOf() deepEquals() equals() sort() fill() mismatch() length
BufferedReader
close() mark() markSupported() read() readLine() ready() reset() skip() lines() transferTo()
BufferedWriter
close() flush() newLine() write() append()
Character Methods
compare() getNumericValue() isAlphabetic() isDigit() isLetter() isLetterOrDigit() isLowerCase() isUpperCase() isWhitespace() toLowerCase() toString() toUpperCase() valueOf()
Collections Methods
sort() binarySearch() reverse() reverseOrder() shuffle() swap() frequency() max() min() disjoint() copy() fill() replaceAll() unmodifiableList() unmodifiableSet() unmodifiableMap()
Comparator Methods
compare() comparing() comparingInt() naturalOrder() reversed() reverseOrder() thenComparing() compareTo()
Date and Time
now() of() parse() getYear() getMonthValue() getMonth() getDayOfMonth() getDayOfWeek() plusDays() minusDays() plusMonths() plusYears() isBefore() isAfter() isLeapYear() lengthOfMonth() format() now() of() getHour() getMinute() plusHours() plusMinutes() now() of() toLocalDate() toLocalTime() format() ofPattern() format()
Enum Methods
compareTo() name() ordinal() toString() valueOf() values()
Errors & Exceptions
ArithmeticException ArrayIndexOutOfBoundsException ClassFormatError ClassNotFoundException ConcurrentModificationException FileNotFoundException IncompatibleClassChangeError InputMismatchException InterruptedException InvalidClassException IOException NegativeArraySizeException NoClassDefFoundError NoSuchFieldException NoSuchMethodException NullPointerException NumberFormatException RuntimeException StringIndexOutOfBoundsException TypeNotPresentException IllegalArgumentException IllegalStateException
File Methods
createNewFile() delete() exists() canRead() canWrite() isFile() isDirectory() length() getName() getAbsolutePath() getPath() getParent() list() listFiles() mkdir() mkdirs() renameTo() setReadOnly() setWritable() setReadable() setExecutable() canExecute()
FileInputStream
available() close() read() skip() getFD() getChannel()
FileOutputStream
close() flush() write() getFD() getChannel()
FileReader
read() ready() skip() close() mark() reset() markSupported() getEncoding() transferTo()
FileWriter
write() append() flush() close() getEncoding()
HashMap Methods
clear() clone() compute() computeIfAbsent() computeIfPresent() containsKey() containsValue() entrySet() forEach() get() getOrDefault() isEmpty() keySet() merge() put() putAll() putIfAbsent() remove() replace() replaceAll() size() values()
HashSet Methods
add() addAll() clear() clone() contains() isEmpty() iterator() remove() removeAll() size() spliterator() toArray()
Integer Methods
compare() compareTo() equals() intValue() max() min() parseInt() sum() toBinaryString() toHexString() toOctalString() toString() valueOf() MAX_VALUE MIN_VALUE
Iterator Methods
hasNext() next() remove()
LinkedHashMap Methods
clear() clone() compute() computeIfAbsent() computeIfPresent() containsKey() containsValue() entrySet() forEach() get() getOrDefault() isEmpty() keySet() merge() put() putAll() putIfAbsent() remove() replace() replaceAll() size() values()
LinkedHashSet Methods
add() addAll() clear() clone() contains() isEmpty() iterator() remove() removeAll() size() spliterator() toArray()
LinkedList Methods
add() addAll() addFirst() addLast() clear() clone() contains descendingIterator() element() forEach() get() getFirst() getLast() indexOf() isEmpty() iterator() lastIndexOf() listIterator() offer() offerFirst() offerLast() peek() peekFirst() peekLast() poll() pollFirst() pollLast() pop() push() remove() removeAll() removeFirst() removeFirstOccurrence() removeIf() removeLast() removeLastOccurrence() replaceAll() retainAll() set() size() sort() spliterator() subList() toArray()
Math Methods
abs() acos() addExact() asin() atan() atan2() cbrt() ceil() copySign() cos() cosh() decrementExact() exp() expm1() floor() floorDiv() floorMod() getExponent() hypot() IEEEremainder() incrementExact() log() log10() log1p() max() min() multiplyExact() negateExact() nextAfter() nextDown() nextUp() pow() random() rint() round() scalb() signum() sin() sinh() sqrt() subtractExact() tan() tanh() toDegrees() toIntExact() toRadians() ulp()
Optional Methods
empty() filter() flatMap() get() ifPresent() isPresent() map() of() ofNullable() orElse() orElseGet() orElseThrow()
Output Methods
print() printf() println()
Random Methods
ints() nextBoolean() nextDouble() nextFloat() nextGaussian() nextInt() nextLong() setSeed()
RegEx Methods
compile() flags() matcher() matches() pattern() quote() split() end() find() group() groupCount() lookingAt() matches() replaceAll() replaceFirst() reset() start()
Scanner Methods
close() delimiter() findInLine() findWithinHorizon() hasNext() hasNextBoolean() hasNextByte() hasNextDouble() hasNextFloat() hasNextInt() hasNextLine() hasNextLong() hasNextShort() locale() next() nextBoolean() nextByte() nextDouble() nextFloat() nextInt() nextLine() nextLong() nextShort() radix() reset() useDelimiter() useLocale() useRadix()
String Methods
charAt() codePointAt() codePointBefore() codePointCount() compareTo() compareToIgnoreCase() concat() contains() contentEquals() copyValueOf() endsWith() equals() equalsIgnoreCase() format() getBytes() getChars() hashCode() indexOf() intern() isEmpty() join() lastIndexOf() length() matches() offsetByCodePoints() regionMatches() replace() replaceAll() replaceFirst() split() startsWith() subSequence() substring() toCharArray() toLowerCase() toString() toUpperCase() trim() valueOf()
StringBuilder Methods
append() appendCodePoint() capacity() charAt() codePointAt() codePointBefore() codePointCount() delete() deleteCharAt() ensureCapacity() getChars() indexOf() insert() lastIndexOf() length() offsetByCodePoints() replace() reverse() setCharAt() setLength() subSequence() substring() toString() trimToSize()
System Methods
currentTimeMillis() nanoTime() exit() gc() getProperty() getProperties() setProperty() clearProperty() arraycopy() identityHashCode() lineSeparator() getenv() in out err
Thread Methods
currentThread() getName() getPriority() interrupt() isAlive() isInterrupted() join() run() setName() setPriority() sleep() start()
TreeMap Methods
firstKey() lastKey() firstEntry() lastEntry() floorKey() ceilingKey() lowerKey() higherKey() headMap() tailMap() subMap() pollFirstEntry() pollLastEntry() descendingMap() clear() clone() compute() computeIfAbsent() computeIfPresent() containsKey() containsValue() entrySet() forEach() get() getOrDefault() isEmpty() keySet() merge() put() putAll() putIfAbsent() remove() replace() replaceAll() size() values()
TreeSet Methods
first() last() floor() ceiling() lower() higher() headSet() tailSet() subSet() pollFirst() pollLast() descendingSet() add() addAll() clear() clone() contains() isEmpty() iterator() remove() removeAll() size() spliterator() toArray()



Java Problem Solving


Share

What is Problem Solving?

You now know a lot of Java: variables, operators, conditions, loops, arrays and methods. The next step is to use them to solve problems.

A problem tells you what a program must do, but not how. So where do you start? Most programmers use four steps:

  1. Understand the problem
  2. Plan the solution
  3. Write the code
  4. Test the code

In this chapter, we use the four steps to solve one of our Java Practice Problems, from start to finish. Then it is your turn to solve it in our practice editor.


The Problem

This problem is called Celsius to Fahrenheit. Celsius and Fahrenheit are two ways to measure temperature. Here is the problem:

Read a temperature in Celsius from input.

Use this formula: fahrenheit = celsius * 9/5 + 32

Print the result like this: 25 Celsius = 77.0 Fahrenheit

You do not need to know how to convert temperatures. The problem gives you the formula, and your job is to turn it into code. Many problems work like this.


Step 1: Understand the Problem

Before you write any code, find out what goes in, and what must come out:

  • Input: a whole number, the temperature in Celsius. For example 25.
  • Output: one line of text, exactly like 25 Celsius = 77.0 Fahrenheit.

Then solve the example by hand. Put 25 into the formula, and calculate from left to right: 25 * 9 is 225, 225 / 5 is 45, and 45 + 32 is 77. That matches the 77.0 in the example output.

If you can solve the problem by hand, you know what the program must do.


Step 2: Plan the Solution

Write the steps in plain words, before you write any Java code. This is called pseudocode (code written in plain words, that no computer can run):

read celsius
fahrenheit = celsius * 9 / 5 + 32
print the text: celsius Celsius = fahrenheit Fahrenheit

Each line is one small job. Now you only need to turn each line into Java code.


Step 3: Write the Code

Turn each line of the plan into Java. To keep it simple, we put the temperature directly in the code, instead of reading it from input:

Example

public class Main {
  public static void main(String[] args) {
    int celsius = 25;
    double fahrenheit = celsius * 9 / 5 + 32;
    System.out.println(celsius + " Celsius = " + fahrenheit + " Fahrenheit");
  }
}

Result:

25 Celsius = 77.0 Fahrenheit
Try it Yourself »

fahrenheit is a double, so Java prints it with a decimal: 77.0. The output is exactly what the problem asks for. Are we done? Not yet!


Step 4: Test the Code

One correct answer does not mean that the program always works. Test it with more temperatures, where you know the right answer.

Choose a temperature below, and follow it through the program:

Code


Inside the program

Output

Expected

Explanation

The program passes four tests, but fails with 37. In Java, an int divided by an int gives an int, and the decimals are cut off (see Arithmetic Operators).

Why did the other tests not find the bug? Because 225, 0, 900 and -360 can all be divided by 5 with nothing left over. That is why you should test many different values.


Fix and Test Again

To fix the bug, write 9.0 instead of 9. Now Java uses decimal division, and keeps the decimals.

It is also a good idea to put the code in a method. Then you can test all the temperatures in one run:

Example

public class Main {
  static void convert(int celsius) {
    double fahrenheit = celsius * 9.0 / 5 + 32;
    System.out.println(celsius + " Celsius = " + fahrenheit + " Fahrenheit");
  }

  public static void main(String[] args) {
    convert(25);
    convert(0);
    convert(100);
    convert(-40);
    convert(37);
  }
}

Result:

25 Celsius = 77.0 Fahrenheit
0 Celsius = 32.0 Fahrenheit
100 Celsius = 212.0 Fahrenheit
-40 Celsius = -40.0 Fahrenheit
37 Celsius = 98.6 Fahrenheit
Try it Yourself »

All five tests pass now, also 37.



Your Turn

Now solve Celsius to Fahrenheit yourself, in our practice editor. The starter code already reads the temperature from input, with a Scanner (see User Input). You write the rest.

When you press Submit, your program is checked with several temperatures. You will learn how this works in the Test Cases chapter.

Practice Problem

Celsius to Fahrenheit

Convert a temperature from Celsius to Fahrenheit.

Write the program in our online editor. Press Submit, and see how many of the test cases your code passes. No installation needed!

Solve the Problem
import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int celsius = Integer.parseInt(sc.nextLine().trim());

    // Calculate fahrenheit
    
  }
}

Tips for Solving Problems

  • Read the problem twice, and find the input and the output.
  • Solve one example by hand, before you write any code.
  • Test more than the example. Also try 0, negative numbers, and values that give decimals.
  • If the output is wrong, print your variables to see what they contain (see Debugging).



★ +1
Sign in to track progress
W3Schools Full Access - your next career move

REMOVE ADS

This way to the W3Schools Adventure app
Learn more about Adventure Mode›

Free account

Track your progress

XP earned 0 Day streak 0 Spaces 0 League —
Sign in to track progress

New

Learn in Adventure Mode W3Schools Adventure App

Coding fundamentals as bite-sized lessons and challenges.

PLUS
SPACES
GET CERTIFIED
FOR TEACHERS
PRACTICE
CONTACT US
×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]

Top Tutorials
HTML Tutorial
CSS Tutorial
JavaScript Tutorial
How To Tutorial
SQL Tutorial
Python Tutorial
W3.CSS Tutorial
Bootstrap Tutorial
PHP Tutorial
Java Tutorial
C++ Tutorial
jQuery Tutorial
Top References
HTML Reference
CSS Reference
JavaScript Reference
SQL Reference
Python Reference
W3.CSS Reference
Bootstrap Reference
PHP Reference
HTML Colors
Java Reference
AngularJS Reference
jQuery Reference
Top Examples
HTML Examples
CSS Examples
JavaScript Examples
How To Examples
SQL Examples
Python Examples
W3.CSS Examples
Bootstrap Examples
PHP Examples
Java Examples
XML Examples
jQuery Examples
Get Certified
HTML Certificate
CSS Certificate
JavaScript Certificate
Front End Certificate
SQL Certificate
Python Certificate
PHP Certificate
jQuery Certificate
Java Certificate
C++ Certificate
C# Certificate
XML Certificate
   
FORUM ABOUT CAMPUS
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.









You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.