Converting string to integer class StringToInt { public static void main (String arg[]) { // Assume arg[0] is the input string int result = 0, pos; int.

Slides:



Advertisements
Similar presentations
AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
Advertisements

STRING AN EXAMPLE OF REFERENCE DATA TYPE. 2 Primitive Data Types  The eight Java primitive data types are:  byte  short  int  long  float  double.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 9 Strings.
J A V A SHASHI BHUSHAN. MAIN ISSUES Object Oriented Concepts Examples FAQs.
Wrappers: Java’s Wrapper Classes for the Primitives Types Steve Bossie.
Chapter 7 Strings F To process strings using the String class, the StringBuffer class, and the StringTokenizer class. F To use the String class to process.
Chapter 7 Strings F Processing strings using the String class, the StringBuffer class, and the StringTokenizer class. F Use the String class to process.
Hand Crafting your own program By Eric Davis for CS103.
BASIC JAVA. Hello World n // Hello world program public class MyFirstJavaProgram { public static void main(String args[]) { char c = 'H'; String s =
Primitive Data Types byte, short, int, long float, double char boolean Are all primitive data types. Primitive data types always start with a small letter.
Hello, world! Dissect HelloWorld.java Compile it Run it.
Computer Programming Lab(4).
Sorting numbers Arrange a list of n numbers a1, a2, a3,..., an in ascending order. A solution: Using Insertion sort. What is Insertion sort? Insertion.
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
Recursion & Collections API Recursion Revisited Programming Assignments using the Collections API.
Java Fundamentals Expanded SE1021 Dr. Mark L. Hornick 1.
Teach.NET Workshop Series Track 4: AP Computer Science with.NET and J#
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
1 Java Console I/O Introduction. 2 Java I/O You may have noticed that all the I/O that we have done has been output The reasons –Java I/O is based on.
The string data type String. String (in general) A string is a sequence of characters enclosed between the double quotes "..." Example: Each character.
Outline Character Strings Variables and Assignment Primitive Data Types Expressions Data Conversion Interactive Programs Graphics Applets Drawing Shapes.
Solving Recurrence Relations T(n)= 2T(n/2)+n = 2*(2T(n/4)+n/2)+n = 4*T(n/4) +2*n = 8*T(n/8) + 3*n = 2 (log n) * T(1) + (log n) * n = n * 1 + n log n O(n.
Chapter 7 Strings  Use the String class to process fixed strings.  Use the StringBuffer class to process flexible strings.  Use the StringTokenizer.
Zhen Jiang Dept. of Computer Science West Chester University West Chester, PA CSC141 Computer Science I 5/27/20161.
Chapter 7 Strings F Processing strings using the String class, the StringBuffer class, and the StringTokenizer class. F Use the String class to process.
Chapter 2 – Continued Basic Elements of Java. Chapter Objectives Type Conversion String Class Commonly Used String Methods Parsing Numeric Strings Commonly.
Chapter 2: Java Fundamentals Type conversion,String.
Java Fundamentals 5. Java Programming: From Problem Analysis to Program Design, Second Edition2 Parsing Numeric Strings  Integer, Float, and Double are.
An Introduction to Java – Part 1 Dylan Boltz. What is Java?  An object-oriented programming language  Developed and released by Sun in 1995  Designed.
CS177 Week2: Recitation Primitive data types and Strings with code examples.
Mixing integer and floating point numbers in an arithmetic operation.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
1 The String Class F Constructing a String: F Obtaining String length and Retrieving Individual Characters in a string F String Concatenation (concat)
CS 11 java track: lecture 2 This week: more on object-oriented programming (OOP) objects vs. primitive types creating new objects with new calling methods.
CONTENTS Wrapper Class Enumeration Garbage Collection Import static.
Operators in JAVA. Operator An operator is a symbol that operates on one or more arguments to produce a result. Java provides a rich set of operators.
FOR LOOP WALK THROUGH public class NestedFor { public static void main(String [] args) { for (int i = 1; i
By Mr. Muhammad Pervez Akhtar
1 Input/Output. 2 In Java input and output take place through I/O streams – An I/O stream represents an input source or output destination – Streams support.
CSC 298 Streams and files.
Chapter One Lesson Three DATA TYPES ©
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI CSCI N305 Characters and Strings Functions.
I/O Basics Java does provide strong, flexible support for I/O related to files and networks. Java’s console based interaction is limited since in real.
Files Review For output to a file: –FileOutputStream variable initialized to filename (String) and append/not append (boolean) –PrintWriter variable initialized.
1 Advanced Programming Examples Output. Show the exact output produced by the following code segment. char[,] pic = new char[6,6]; for (int i = 0; i
A Introduction to Computing II Lecture 1: Java Review Fall Session 2000.
A data type in a programming language is a set of data with values having predefined characteristics.data The language usually specifies:  the range.
CS0007: Introduction to Computer Programming Primitive Data Types and Arithmetic Operations.
Object Oriented Programming Lecture 2: BallWorld.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 7 Strings Chapter.
Introduction to Java E177 April 29, me. berkeley
using System; namespace Demo01 { class Program
Sum of natural numbers class SumOfNaturalNumbers {
2.5 Another Java Application: Adding Integers
Multiple variables can be created in one declaration
Chapter 2.
An Introduction to Java – Part I, language basics
Java so far Week 7.
class PrintOnetoTen { public static void main(String args[]) {
Factoring if/else code
Scope of variables class scopeofvars {
Dr. Sampath Jayarathna Cal Poly Pomona
Recursion Method calling itself (circular definition)
Lecture 22: Number Systems
Characters and Strings Functions
Factoring if/else code
CS 1054 Introduction to Programming in Java
More on iterations using
Presentation transcript:

Converting string to integer class StringToInt { public static void main (String arg[]) { // Assume arg[0] is the input string int result = 0, pos; int len = arg[0].length(); char c; for (pos = 0; pos < len; pos++) { c = arg[0].charAt(len-pos-1); if ((c >= ‘0’) && (c <= ‘9’)) { result += ((c-’0’)*Math.pow(10, pos)); } // continued in next slide

Converting string to integer else if ((c==‘-’) && (pos==len-1)) { result = -result; } else { System.out.println(“Invalid input: ” + arg[0]); break; } } // end for if (pos==len) { System.out.println(“Integer value: ” + result); }

valueOf public class ValueOfDemo { public static void main(String[] args) { //this program requires two arguments on the command line if (args.length == 2) { //convert strings to numbers float a = (Float.valueOf(args[0]) ).floatValue(); float b = (Float.valueOf(args[1]) ).floatValue(); //do some arithmetic System.out.println("a + b = " + (a + b) ); System.out.println("a - b = " + (a - b) ); System.out.println("a * b = " + (a * b) ); System.out.println("a / b = " + (a / b) ); System.out.println("a % b = " + (a % b) ); } else { System.out.println("This program requires two command-line arguments."); }

parseXXXX() Note: Each of the Number subclasses that wrap primitive numeric types also provides a parseXXXX() method (for example, parseFloat()) that can be used to convert strings to primitive numbers. Since a primitive type is returned instead of an object, the parseFloat() method is more direct than the valueOf() method. For example, in the ValueOfDemo program, we could use: float a = Float.parseFloat(args[0]); float b = Float.parseFloat(args[1]);

Converting Numbers to Strings There are several easy ways to convert a number to a string: int i;String s1 = "" + i; //Concatenate "i" with an empty string; //conversion is handled for you. or String s2 = String.valueOf(i); //The valueOf class method. Each of the Number subclasses includes a class method, toString(), that will convert its primitive type to a string. For example: int i;double d; String s3 = Integer.toString(i); String s4 = Double.toString(d);

ToStringDemo public class ToStringDemo { public static void main(String[] args) { double d = ; String s = Double.toString(d); int dot = s.indexOf('.'); System.out.println(dot + " digits before decimal point."); System.out.println( (s.length() - dot - 1) + " digits after decimal point."); } The output of this program is: 3 digits before decimal point. 2 digits after decimal point.

Reversing a string class StringReverse { public static void main (String arg[]) { // Assume that the input is arg[0] String reversed = “”; int pos; for (pos=arg[0].length()-1; pos >= 0; pos--) { reversed += arg[0].charAt(pos); } System.out.println (“Original: ” + arg[0] + “, Reversed: ” + reversed); }