• No results found

Scanner, Arrays, Object Arrays, String Array and Dynamic Array

N/A
N/A
Protected

Academic year: 2020

Share "Scanner, Arrays, Object Arrays, String Array and Dynamic Array"

Copied!
27
0
0

Loading.... (view fulltext now)

Full text

(1)
(2)

Input using Scanner Object

Java Scanner class comes under the java.util package. Java has various ways to read input from the keyboard, the java.util.Scanner class is one of them.

Syntax to Declare object of Scanner class

Scanner scan = new Scanner(System.in);

Syntax to take input

Scannerobject.nextDatatype()

(3)

Example Scanner Object

import java.util.Scanner;

public class ScannerClassExample1 { public static void main(String args[])

{

System.out.println("---Enter Your Details--- "); Scanner in = new Scanner(System.in);

System.out.print("Enter your name: ");

String name = in.next(); or in.nextLine(); // String input System.out.println("Name: " + name);

System.out.print("Enter your age: "); int i = in.nextInt();

System.out.println("Age: " + i);

System.out.print("Enter your salary: "); double d = in.nextDouble();

System.out.println("Salary: " + d); in.close();

(4)

Arrays

Java array is an object the contains elements of similar data type. It is a data

structure where we store similar elements. We can store only fixed set of elements in a java array.

Array in java is index based, first element of the array is stored at 0 index.

Types of Array in java - There are two types of array.

(5)

Arrays

Syntax to Declare an Array in java

dataType[] arr = new datatype[size];

(or)

dataType arr[]= new datatype[size];

Example1

-class Testarray{

public static void main(String args[]){

int a[]=new int[5]; //declaration and instantiation a[0]=10;//initialization

a[1]=20; a[2]=70; a[3]=40; a[4]=50;

//printing array

for(int i=0;i<a.length;i++) //length is the property of array System.out.println(a[i]);

(6)

Arrays

Example-2

class Testarray1

{

public static void main(String args[])

{

int a[]={33,3,4,5};

//declaration, instantiation and initialization

//printing array

for(int i=0;i<a.length;i++)

//length is the property of array

(7)

Arrays

Example-3 Sum of array elements

class array_sum

{

public static void main(String args[])

{

int a[]={33,3,4,5};

//declaration, instantiation and initialization int sum=0;

//sum array

for(int i=0;i<a.length;i++)

//length is the property of array

sum=sum+a[i];

System.out.println(“Sum=“+sum);

}

(8)

Arrays

Example-4 search element in array

class array_sum

{

public static void main(String args[])

{

int a[]={33,3,4,5};

//declaration, instantiation and initialization int e;

//sum array

for(int i=0;i<a.length;i++)

//length is the property of array

sum=sum+a[i];

(9)

Pass Array to function

We can pass the java array to method so that we can reuse the same logic

on any array.

Syntax to declare function as array parameter

Returntype functionname (datatype array[])

{

}

Syntax to call function as pass array

(10)

Pass Array to function

Example-1 – function to sum array elements

Import java.util.Scanner; class sum_arr

{

int sumarr(int a[]) // function declaration and definition

{

int sum=0, I;

for(i=0;i<a.length;i++) sum=sum+a[i]; return(sum);

}

public static void main(String ar[]) {

int a[]=new int[5];

Scanner sc=new Scanner(System.in); for(i=0;i<5;i++)

a[i]=sc.nextInt();

int sum=sumarr(a); // function call

(11)

Pass Array to function

Example-2 – function to search element in array

Import java.util.Scanner; class search_arr

{

void sear_arr(int a[], int e) // function declaration and definition

{

int sum=0, I;

for(i=0;i<a.length;i++) {

if(e==a[i]) {

System.out.println (“Found”);

System.exit(0); // normal exit from program }

}

(12)

Pass Array to function

Example-2 continue – function to search element in array

public static void main(String ar[]) {

int a[]=new int[5];

Scanner sc=new Scanner(System.in); for(i=0;i<5;i++)

a[i]=sc.nextInt(); int e;

System.out.println(“Enter no to search :”); e=sc.nextInt();

sear_arr(a,e); // function call

(13)

Pass Array to function

Example-3 – function to find max element in 10 numbers

Import java.util.Scanner; class search_arr

{

int max_arr(int a[],) // function declaration and definition

{

int max=a[0], I;

for(i=0;i<a.length;i++) {

if(a[i]>max) {

max=a[i]; }

}

(14)

Pass Array to function

Example-3 continue – function to search element in array

public static void main(String ar[]) {

int a[]=new int[10];

Scanner sc=new Scanner(System.in); for(i=0;i<5;i++)

a[i]=sc.nextInt();

int max=max_arr(a); // function call

System.out.println(“Max no =“+max); }

(15)

String and String Methods

String is a sequence of characters. But in Java, a string is an

object that represents a sequence of characters.

Example

-String a=“amit”;

or

String s;

s=“amit”;

Methods

1.

length() – give the number of elements in array.

Example –

String s=“kiran”;

(16)

String Methods

2. charAt(index) – find the character at the specified index.

Example –

String s=“dit”;

System.out.println(s.charAt(1)); // display “I” (s[0] –d, s[1]- I, s[2]-t)

3. substring(int) – display all characters from specified index.

String s=“dehradun”;

System.out.println(s.substring(2)); //display “radun”

4. concat(string)- join string2 in string1

String s1=“abc”; //string1

String s2=“xyz”; //string2

S1.contact(s2);

(17)

String Methods

2. charAt(index) – find the character at the specified index.

Example –

String s=“dit”;

System.out.println(s.charAt(1)); // display “I” (s[0] –d, s[1]- I, s[2]-t)

3. substring(int) – display all characters from specified index.

String s=“dehradun”;

System.out.println(s.substring(2)); //display “radun”

4. concat(string)- join string2 in string1

String s1=“abc”; //string1

String s2=“xyz”; //string2

S1.contact(s2);

(18)

String Methods

5. indexof(string) - give - find the index of specified string.

Example –

String s=“dit”;

System.out.println(s.indexOf(“it”));

// display 1

6. equals(string) – will return true if string1 is equal to string2.

String s1=“dehradun”;

String s2=“dehra”;

System.out.println(s1.substring(s2)); //display false

7. equalsIgnoreCase(string)- will match string1 with string2 by ignoring

case.

String s1=“dit”; //string1

String s2=“DIT”; //string2

(19)

String Methods

8. compareTo(string) – compare string1 with string2.

Return 0 – if string1 =string2 Return <0 - if string1<string2

Return >0 if string1 is greater than string2

Example –

String s1=“dit”; String s2=“abc”;

If(s1.compareTo(s2))>0

System.out.println(“s1 is smaller than s2”); else

System.out.println(“s2 is smaller than s1”);

9. toLowerCase() – return string in lower case.

String s1=“DIT”;

String s2=s1.toLowerCase()l System.out.println(s2);

10. toUpperCase()- return string in upper case.

String s1=“dit”;

(20)

String Methods: Example

Write a program to compare two strings

-import java.util.Scanner; class compare_str

{

public static void main(String ar[]) {

Scanner sc=new Scanner(System.in); System.out.println("ENter 1st String :"); String s1=sc.next();

System.out.println("ENter 2nd String :"); String s2=sc.next();

if(s1.compareTo(s2)==0)

System.out.println("Strings are equal"); if(s1.compareTo(s2)>0)

System.out.println("Strings1 is greater than String2"); if(s1.compareTo(s2)<0)

(21)

String array

A Java String Array is an object that holds a fixed number of

String values.

Syntax –

String[] object =new String[size];

Or

String object[] =new String[size];

Example –

String name[]=new String[5];

name[0]=“Amit”;

(22)

String array

String array

initialization-String[] a1 = {"AAA", "BBB", "CCC", "DDD", "EEE"};

This array a1 will store 5 value from a1[0] to a1[4]

Example –

String[] a1 = {"Apple", "Banana", "Orange"};

for( int i = 0; i < a1.length; i++)

{

(23)

Dynamic array

Static array

-•

If the array is defined in such a way where, at the time of

declaration size is mentioned. It is called as static array.

Example – int a[]=new int[size];

Main drawback of this declaration is memory wastage.

Example –

Int a[]=new int[10];

a[0]=1;

a[1]=2;

In above example 2 to 8 rest elements are not stored but

memory is allocated, so wasted.

Total memory

waste-Let int takes 4 bytes for one

(24)

Dynamic array

Dynamic array

-•

If the array is defined in such a way where, at the time of

declaration size is not mentioned. It is called as dynamic array.

In java for dynamic array we use a class called as – ArrayList()

This class uses a package – import java.util.ArrayList

Syntax-ArrayList<Wrraper class /Class name> var=new ArrayList<>();

Example –

ArrayList<String> a1=new ArrayList<>();

ArrayList<Integer> a2=new ArrayList<>();

Wrapper Classes in Java. A Wrapper class is a class whose object

wraps or contains a primitive data types.

(25)

Dynamic array

import java.util.ArrayList;

class arraylist

{

public static void main(String ar[])

{

ArrayList<String> a1=new ArrayList<>();

a1.add("Garima");

a1.add("Reema");

System.out.println(a1);

// print all values

}

}

To print all

(26)

Dynamic array

Methods of ArrayList –

1.

add(value) – use to add new value in arraylist

2.

get(indexno) – use to display element store at the index no.

3.

add(indexno, value) – add value at particular indexno and existing value will

shift to next index.

Example –

ArrayList<String> a1=new ArrayList<>();

a1.add("Garima"); //a1[0]

a1.add("Reema"); // a1[1]

System.out.println(a1.get(0)); // print “garima”

a1.add(1,"Sonu"); // a1[1]=sonu

System.out.println(a1); // Garima, Sonu, Reema

4. remove(indexno) - remove value stored at the indexno.

(27)

Dynamic array

Methods of ArrayList –

5. clear() – remove all value from arraylist. Example

-import java.util.ArrayList; class arraylist

{

public static void main(String ar[]) {

ArrayList<String> a1=new ArrayList<>(); // store String values ArrayList<Integer> a2=new ArrayList<>(); // store integer values a1.add("Garima"); a1.add("Reema"); a1.add(1,"Sonu"); a2.add(1); a2.add(2); System.out.println(a1.get(0)); System.out.println(a1); a1.remove(0);

System.out.println("All values :"+a1); for(int i = 0; i < a1.size(); i++) {

References

Related documents

Some players just want to know where the bad guys are so they can shoot at them, while other players may take more of a back seat, spectating more during the game and enjoy- ing

Zde ovšem naše paralela končí. Je třeba se poučit, srovnat srovnatelné, ale zároveň si i uvědomit odlišný rozsah obou krizí a důvody, proč tomu tak je. Ne všechny

[r]

After sorting by the month variable the code then summarizes the data file for printing by using retained variables to store totals for each month of the year and outputting one

Description Registration Comments Tests number Shelf life, months Product number PREP-RAPID RU/IVD. DNA extraction from

The average value and loops into half with java array without size in java string object data items in java arrays using array.. Please check the country

La violencia y la corrupción en el país se han revertido contra los mismos habitantes y se ha salido del control de las élites políticas, que en un principio eran quienes