0% found this document useful (0 votes)
5 views13 pages

Java Scanner and Math Class Examples

The document discusses various utility classes in Java, including the Scanner, Math, and Integer classes. It explains their methods, constants, and provides examples of how to use them in code. Additionally, it introduces the concept of wrapper classes for primitive types and mentions class hierarchies in Java.

Uploaded by

carawa6255
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views13 pages

Java Scanner and Math Class Examples

The document discusses various utility classes in Java, including the Scanner, Math, and Integer classes. It explains their methods, constants, and provides examples of how to use them in code. Additionally, it introduces the concept of wrapper classes for primitive types and mentions class hierarchies in Java.

Uploaded by

carawa6255
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Scanner class

Example 2

public class ScanString


{
public static void main(String[] args)
{
String sample = "one two \tthree";
Scanner s = new Scanner(sample);
[Link]("<<<<"+sample+">>>>");
while ([Link]()){
String token = [Link]();
[Link](token);
}
[Link]("<<<< end of tokens >>>>");
}
}

22
Math class

Math class is a utility class

•You cannot create an instance of Math


•All references to constants and methods will use the prefix Math.

•Contains constants, π and e


Names of these are PI and E
Java convention is to name constants using capital letters.

23
Math class

Methods
pow(…) Raise the first argument to the power
specified in second argument
e.g. [Link](x,3)
abs(…) Returns absolute value of its argument
max(…) Returns the larger of two int or
double arguments
min(…) Returns smaller …


many more

24
Math class

Example

1. Find the largest of 3 int values


As there is no object note the use of the prefix Math.

25
Math class

Example 1
public class FindMax

The larger of 3 integers is determined. The max method is used twice.

Scanner methods used:


[Link]() returns the larger of two values passed in as arguments

Math is a utility class with static methods.


Consider the statement:
[Link](j,k)

Two arguments, j and k, passed in to max

The method max

The Math class

26
Math class

Example 1

public class FindMax


{
public static void main(String[] args){
Scanner kb = new Scanner([Link]);
[Link](
"Please enter 3 int values");
int i = [Link](); Note how [Link](…) is used twice
int j = [Link]();
int k = [Link]();
int mx = [Link](i, [Link](j,k));
[Link]("largest is "+mx);
}
}

27
Integer class

Integer class is a utility class

•Many methods are static


you do not need an object of type Integer.
The prefix Integer. is used for these.

•Contains constants, MAX_VALUE and MIN_VALUE


Again … Java convention is to name constants using capital letters.

28
Integer class

Methods

max(…) Returns the larger of two int arguments


min(…) Returns smaller …
parseInt(…) Parses the string argument expecting that
argument to be a valid decimal integer.
Correction to notes: E.g. parseInt(" 23 ")
no spaces
Should be: E.g. parseInt("23")

to ensure there are no leading or trailing spaces


in a string one can use the trim() method
String xx = ...
xx = [Link]();

29
Integer class

Example

Read lines of text from [Link]


Each line is parsed according to the expected format:
<name of an item><comma><quantity as integer>

Examples of such lines:


monitor,45
laptop,55

30
Integer class

Example
public class TotalQuantity

Integer methods used:


parseInt(…) returns the integer represented by a character string

Integer is a utility class with static methods.


Consider the statement:
int qty = [Link](qtyAsString);

Int variable String containing an integer

The method parseInt

The Integer class

31
Integer class

If qtyAsString does not have a


Example 1 valid integer value the program
will terminate with an error
public class TotalQuantity
{
public static void main(String[] args)
{
Scanner kb = new Scanner([Link]);
int totalQty = 0;
for (int i = 0; i < 4; i++){
[Link]("Enter next line: ");
String line = [Link]();
int commaAt = [Link](",");
String qtyAsString = [Link](commaAt+1);
int qty = [Link](qtyAsString);
totalQty += qty;
}
[Link]("total = "+totalQty);
}
} 32
Wrapper classes

With similarity to the Integer class, there are classes for other types
… these types of classes are called wrapper classes.

These are called wrapper classes because you instantiate an object and
wrap a primitive value inside

Double
Boolean
Byte
Character
Float
Long
Short

33
Aside: Hierarchy of classes

A topic in ACS-1904 is class hierarchies. For example:

All classes are subclasses of Object

34

Common questions

Powered by AI

Before using Integer.parseInt(), which converts a string to an integer, it is important to use the trim method on the string to remove any leading or trailing whitespace. This ensures that the string solely contains the integer value, preventing NumberFormatException errors that occur when parseInt encounters unexpected characters. The trim method cleans the string, thus allowing for accurate parsing by Integer.parseInt().

The Math class in Java is a utility class, which means you cannot create an instance of it. All methods and constants in the Math class are static, meaning they are accessed using the class name as a prefix, such as Math.pow() or Math.PI. This design implies that methods in the Math class are readily available without the need to instantiate an object, optimizing both performance and usability for mathematical operations .

A class hierarchy organizes classes in a hierarchical tree structure, with the Object class as the root for all Java classes. This hierarchy illustrates inheritance relationships, aiding understanding of class extension and method inheritance. In relation to wrapper classes, this hierarchy shows how classes like Integer inherit from Object, enabling them to utilize polymorphism and be interchangeable with basic data types when object references are needed .

Wrapper classes in Java are classes that encapsulate a primitive data type in an object. They provide methods for converting between the primitive data type and a corresponding object. Common wrapper classes include Integer for int, Double for double, Boolean for boolean, and others. They allow primitive types to be used where only objects are expected, providing utilities and methods not available to primitive data types directly .

When parseInt encounters a non-numeric string, it throws a NumberFormatException, causing the program to terminate unless handled. Preemptive measures include validating that the string contains only valid numeric characters prior to parsing. Alternatively, exception handling mechanisms such as try-catch blocks can be implemented to catch and manage the exception gracefully, ensuring the program continues to execute .

The Scanner class processes tokens from a string by scanning it to find and return individual substrings divided by whitespace. By using Scanner's hasNext() method, the string is checked for remaining tokens, and next() retrieves these tokens iteratively. For instance, 'one two \tthree' would be tokenized into 'one', 'two', and 'three', allowing for organized processing and manipulation of the input data .

To find the largest among three integers using the Math class, the max method is applied recursively. First, the largest of the first two integers is determined using Math.max(i, j). Then, the result is compared with the third integer using Math.max(result, k), where result is the previously found maximum. This ensures that the maximum value from all three integer inputs is selected. This approach demonstrates how static methods in utility classes streamline operations without object instantiation .

To enhance the TotalQuantity program's robustness, incorporate validation checks and exception handling. For example, before using indexOf and substring, verify the line format by checking for the presence and correctness of the comma delimiter. Use try-catch blocks around parseInt to catch NumberFormatException if qtyAsString is invalid. Additionally, output helpful error messages for invalid inputs and skip processing them to prevent program termination .

Both the Math and Integer classes are utility classes in Java that contain static methods, meaning they do not require object instantiation. The Math class is focused on a wide range of mathematical operations, providing methods for arithmetic operations like pow, abs, and max. The Integer class, on the other hand, serves numerical operations specifically for integer data types, featuring methods like parseInt for converting strings to integers and max for comparing integer values. Math is more general-purpose for mathematical equations, while Integer deals with integer-specific tasks .

In Java, the Math class uses PI and E as constants to represent the mathematical constants π and e, respectively. According to Java conventions, these constants are declared in capital letters and are accessed using the Math class, such as Math.PI for π and Math.E for e .

You might also like