Trending March 2024 # How File Handling Work In Scala With Eamples # Suggested April 2024 # Top 8 Popular

You are reading the article How File Handling Work In Scala With Eamples updated in March 2024 on the website Katfastfood.com. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested April 2024 How File Handling Work In Scala With Eamples

Introduction to Scala File

Scala file handling is quite similar to java. We can use a scala package or we can also use packages provided by java to handle files. We can create, read, write, and open a file in scala similarly we can do in other languages. Scala provides us various methods to create or read, write on file we just need to import proper packages to use those classes, methods, or interfaces. The file is a concept of strong and fetching of our data we can write any lines of data into the file.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Syntax:

val my_file = new File("your_file_name" )

The above syntax shows how we can create a file in our system. We just need to give the variable and file name by which we want to create the file in the system.

val myfile = new File("demo.txt" )

This will create a file in your system with a specified name.

How File handling work in Scala?

The purpose to use file is that we can easily store and retrieve our data from the file when needed. But to create a file and read from file we must have chúng tôi package import in our Scala Program because in scala we do not have any standards library for writing data to file so for that we need to use chúng tôi So in java file class, we can either pass a file name or a directory name where we want to create a file. This file class has so many different methods which are working internally to handle the file.

So if you want to create a file object we must follow the below steps;

var myfile = new File("file name")

In this, you can give your filename or directory name. This path can be relative or absolute. This file class also maintains the access permission issues when it comes to the security of files to prevent it from external use. Also, this Java File class is immutable that means once created cannot change.

It has many methods. Some are mentioned below:

String getAbsolutePath(): to get absolute path

boolean canExecute()

boolean exists() : File exists

boolean canWrite() : to write

boolean delete() : to delete

boolean equals(Object obj) : compare two objects

boolean canRead() : to read

In the scala, we have a chúng tôi package to handle file events. Also, we can use java package to achieve those same features. Let’s discuss them one by one. Now first we will see how we can write and create a file in scala.

Step 1: To create and write on a file;

import java.io._ val myfile = new File("demo.txt" ) This is the very basic step to start with.

Explanation: In the above line of code, we are creating a file object. File objects have this constructor in which we need to pass the file name. It will create one file with the specified name in the system.

Step 2: This file object is available in the chúng tôi package so we need to import it into our program in order to avoid any errors.

val pr = new PrintWriter(myfile)

Explanation: Now we are using PrintWriter object to parse our file. As the name suggests it has a write a method to write in a file. This is also available inside the chúng tôi package.

Step 3: For this, we need to parse our file into its constructor.

pr.write("We are writing to the file.")

Explanation: PrintWriter has this method to write in the file with specified content.

Step 4:

pr.close()

Explanation: In this step, we are just closing this object.

Below you can find the steps which are required to read data from a file:

val myfile = "demo.txt"

Explanation: In this step, we are just defining the name of the file from which we want to read data.

Step 2:

val src = Source.fromFile(myfile)

Explanation: Now this step is important because here we are using Source class to provide them the file and get the data of the file. It has one method called From File where we need to provide the filename from which we want to read.

Step 3:

for(line<-src.getLines){ println(line) }

Explanation: To read data we must require a for loop in order to iterate over each and every word of the file. Here we are creating an instance of the iterable file which can easily be iterated.

Step 4:

src.close()

Explanation: In this step, we are just closing the source object. It helps us prevent our data from external use.

Operation Create Write Write Method

Write New File() PrintWriter PrintWriter.write()

Operation Read To Get file To get file data

Read Filename Source.fromFile Get lines()

Packages to be imported:

Points to be remembered:

Example to Implement Scala File

Below are the examples of Scala File:

Example #1

In this example, we are creating, parsing, and writing to a file.

Code:

import java.io.File import java.io.PrintWriter object Main extends App{ val myfile = new File("I:\demo.txt" ) val myPrintWriter = new PrintWriter(myfile) myPrintWriter.write("This is our first content to write into a file.") myPrintWriter.close() }

Output:

Example #2

In this file, we are reading from the file that we have created previously. Please import chúng tôi to work.

Code:

import java.io.File import java.io.PrintWriter import scala.io.Source object Main extends App{ val myfile = "demo.txt" val src = Source.fromFile(myfile) while (src.hasNext) { println(src.next) } src.close() }

Output:

Conclusion

Files are used to store our data. In scala, we used two libraries to deal with file handling i.e. chúng tôi and chúng tôi Like any other programming language, we can create, read, and write into a file. The file got created on a particular location if given otherwise it will create into the user folder of our system.

Recommended Articles

This is a guide to Scala File. Here we discuss an introduction to Scala File, syntax, how does it work, examples with code and output. You can also go through our other related articles to learn more –

You're reading How File Handling Work In Scala With Eamples

How Does Split Function Work In Scala?

Definition of Scala Split

As the name suggest split is used to split the string in Scala. In a programming language, we have a requirement where we want to split our long string based on some regular expression or any special character, any character, space, ‘,’ (comma) for this purpose we have split method in Scala available. We can call this method on any string. After splitting the string, it will return us the array contain all the elements present inside it. The split function also divides the string into several parts. In the coming section, we will discuss more about the method and its usage in real life for a better understanding.

Start Your Free Software Development Course

Syntax:

This method is used to split our string in Scala. We can call this method on any string object. Let’s see the syntax for better understanding of the methods how we can use this while programming. See below;

1. With limit pass as a parameter

split(String regular_expression, int limit)

In the above syntax we are passing two parameters as the input in Scala. The first one is the regular expression and other one is limit.

2. Without limit param

split(String regular_expression)

In the above syntax, we are passing only one parameter the input for the split method without specifying the limit here. In the coming section, we will discuss more about its practice usage for better understanding and hands on.

How does Split Function Work in Scala?

As now we know that split function is used to split the string, We can split string based on some regular expression or any any special character or any substring we want to give. We can pass any expression there. We have two syntax for this method one is with specify the limit and another one is without specifying the limit for the split method. Limit parameter will limit the number of values in the array. Now we can discuss more about the method signature and their return type as well. Which are as follow see below;

split(String regular_expression): This method takes two parameter as the input. By using this parameter, we can specify the string by which we want to split our string. We can specify any character, substring, any regular expression also accepted here. The return type for this method is array only, it will return us new array containing the parameter after the split.

split(String regular_expression, int limit): This method is also used to split the string based on the regular expression. But this method takes two parameters as the input. The first parameter is the regularexpression on the basis of this string would be spitted. The second parameter about this we will discuss in detail see below;

limit: This parameter is used to specify the limit of values in the final array. In short, it just restricts our resultant array to some number only. Below we will see one practice example of how we can specify this parameter in the method see below;

Example:

split("hello", 5);

In this way we can specify the limit parameter in the split function, it will only limit the values inside the array to 5 here.

Example:

object Main extends App{ println("XXXXXXXX") var mystr = "samplestringcontinuestring" val finalresult = mystr.split("string") }

In the above lines of code, we are trying to split our string. First we are creating a string named as ‘mystr’, on this we are calling the split method. Inside the methods, we are mentioning ‘string’ as the split expression for our string. So whenever the ‘string’ word will appear in our variable it will split the string and divide them into several parts and skip that string. So in the above case output will be a sample, continue because we are splitting it on basis of the ‘string’ keyword.

In the same way we can specify the limit parameter to limit our output array. In this, if we limit our parameter as ‘1’ then only it will print the ‘sample’ string for us as the output.

Examples of Scala Split

In this example, we are trying to split our string in several parts. Here we are using the split function with and without the limit parameter, some of the string is split by using the substring, some based on the space, and limit is also applied here.

Example #1

Code:

object Main extends App{ println("Demo for split method in Scala !!! ") var mystr1 = "samplestringcontinuestring" var mystr2= "mystrytotestthesplit" var mystr3 = "demoexmapleto test" var mystr4 = "smaple string to test spilt method with limit" val finalresult1 = mystr1.split("the") val finalresult2 = mystr2.split("the") val finalresult3 = mystr3.split(" ") val finalresult4 = mystr4.split(" ", 5) println("Result for each string would be  ::") for ( r1 <-finalresult1 ) { println(r1) } println("*****************************") for ( r2 <-finalresult2 ) { println(r2) } println("*****************************") for ( r3 <-finalresult3 ) { println(r3) } println("*****************************") for ( r4 <-finalresult4 ) { println(r4) } }

Example #2

In this example we are using limit parameter with the split method here so this will restrict the resultant array also the value in the array will be limited here.

Code:

object Main extends App{ println("Demo for split method in Scala !!! ") var mystr1 = "samplestringcontinuestring" var mystr2= "mystrytotestthesplit" var mystr3 = "demoexmapleto test" var mystr4 = "sample string to test spilt method with limit" val finalresult1 = mystr1.split("the", 0) val finalresult2 = mystr2.split("the", 2) val finalresult3 = mystr3.split(" ", 1) val finalresult4 = mystr4.split(" ", 5) println("Result for each string would be  ::") for ( r1 <-finalresult1 ) { println(r1) } println("*****************************") for ( r2 <-finalresult2 ) { println(r2) } println("*****************************") for ( r3 <-finalresult3 ) { println(r3) } println("*****************************") for ( r4 <-finalresult4 ) { println(r4) } }

Output:

Conclusion

Split is used to divide the string into several parts containing inside an array because this function return us array as result. We can also limit our array elements by using the ‘limit’ parameter. Otherwise, it will just contain all the parameters from the string that has been spitted.

Recommended Articles

We hope that this EDUCBA information on “Scala Split” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

Working Of Scala Random With Examples

Introduction to Scala Random

The Scala Random function generates random numbers or characters in Scala. To generate the Random numbers over Scala, we use the Random process with Scala.util.Random class. The Random number generated can be anything,, be it Integer, Float, Double, or Char. This random no is important for various-level applications such as Validation. So it is used for the Random numbers generation in our Scala Application.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Syntax:

val r = scala.util.Random r: chúng tôi = [email protected] r.nextInt res1: Int = 1825881164 r.nextInt(100) res2: Int = 99 r.nextFloat res3: Float = 0.10983747 Working of Scala Random with Examples

This function takes up the random function to generate numbers for processing; it generally uses the Linear congruential generator; this algorithm works on choosing the random number. We can also select the range over which we want to generate the number over. We will see the random number generation with some examples.

Example #1

Code:

val r = scala.util.Random r: chúng tôi = [email protected] r.nextInt res0: Int = 2123631858 r.nextInt res1: Int = -737405300 r.nextInt res2: Int = 377538368

Every Time the code is run or this function is called we will get the set of different values in the usual pattern without following any rule or pattern. Even we can also set an inclusive as well as an exclusive limit for the random number we want to generate.

Note: By default, the inclusive limit is 0 so we can also set only the exclusive one.

r.nextInt(100) res3: Int = 64 r.nextInt(100) res4: Int = 91 r.nextInt(100) res5: Int = 39 r.nextInt(100) res6: Int = 38

Output:

Example #2

We can also select the Random Float value by the method chúng tôi the range will lie from 0.0 decimal value to 1. Let us check that with some example:

Code:

r.nextFloat res8: Float = 0.59556204 r.nextFloat res9: Float = 0.8322488 r.nextFloat res10: Float = 0.6295014 r.nextFloat res11: Float = 0.69067985 r.nextFloat res12: Float = 0.7225474 r.nextFloat res13: Float = 0.9606658 r.nextFloat res14: Float = 0.77049905

Same as Float we can also create random numbers for Double Values.

r.nextDouble res18: Double = 0.34614360601266014 r.nextDouble res19: Double = 0.38648718502076507 r.nextDouble res20: Double = 0.31311541536121046 r.nextDouble res21: Double = 0.7410149595118738

It also prints the values between 0 to 1. The Boolean value can also use the same Random value and yields result based on Boolean Values.

r.nextBoolean res15: Boolean = true r.nextBoolean res16: Boolean = false r.nextBoolean res17: Boolean = false

Output:

Example #3

Code:

r.nextPrintableChar res24: Char = K r.nextPrintableChar res25: Char = g r.nextPrintableChar res26: Char = k r.nextPrintableChar res27: Char = K r.nextPrintableChar res28: Char = ' r.nextPrintableChar res29: Char = t

So it prints all the CharatcersRandomly. It is possible that the same character or integer value can come many times; there is no rule for the numbers not to be repeated.

Note: This Random function is widely used for Pattern Verification, security applications like Captcha, and other things.

Output:

Example #4

We can also use the Random function over a distribution. One known function that works with it is the Gaussian function. The Gaussian Function takes the Random data over the Gaussian Distribution and prints data accordingly. It returns a random number with a mean of 0 and a deviation of 1. To change this Gaussian value, we need to provide that explicitly.

Code:

r.nextGaussian res35: Double = 1.301074019733114 r.nextGaussian res36: Double = 0.37365693728172494 r.nextGaussian res37: Double = -0.2868649145689896 r.nextGaussian res38: Double = 2.108673488282321

Output:

This is what it generates randomly over a Gaussian Distribution.

Example #5

We can also merge random functions and create a List or store them in the collection we want. Let us check that with Example:

Code:

for(i<- 0 to r.nextInt(4)) yield r.nextDouble res40: scala.collection.immutable.IndexedSeq[Double] = Vector(0.020069508131527525) for(i<- 0 to r.nextInt(4)) yield r.nextDouble res41: scala.collection.immutable.IndexedSeq[Double] = Vector(0.6992494049547558) for(i<- 0 to r.nextInt(10)) yield r.nextDouble res42: scala.collection.immutable.IndexedSeq[Double] = Vector(0.9844960499444084, 0.06772285166187964, 0.9797605964534618, 0.6239437080597234, 0.015670036830630618, 0.8530556031658404) for(i<- 0 to r.nextInt(10)) yield r.nextDouble res43: scala.collection.immutable.IndexedSeq[Double] = Vector(0.0775137969760199, 0.3150585897780521, 0.5429361580144657, 0.7427799136029297, 0.7595647379710992, 0.6097524030728557, 0.5555829149364843, 0.031480808153179884, 0.9486129909099824, 0.1519146584718376) for(i<- 0 to r.nextInt(10)) yield r.nextPrintableChar res44: scala.collection.immutable.IndexedSeq[Char] = Vector(Q, q, n, ", [, r, K, 0, B) for(i<- 0 to r.nextInt(10)) yield r.nextPrintableChar res45: scala.collection.immutable.IndexedSeq[Char] = Vector(%, ?) for(i<- 0 to r.nextInt(10)) yield r.nextPrintableChar res46: scala.collection.immutable.IndexedSeq[Char] = Vector(m, =) for(i<- 0 to r.nextInt(3)) yield r.nextPrintableChar res47: scala.collection.immutable.IndexedSeq[Char] = Vector(6) for(i<- 0 to r.nextInt(10)) yield r.nextPrintableChar res48: scala.collection.immutable.IndexedSeq[Char] = Vector([, =, V, !, Q, f, 9, E)

Here we can see how we merged the different functions of Random and generated results accordingly.

Output:

As a result, this function is used to generate random values throughout the Scala application that may be required repeatedly.

Conclusion

From the above article, we saw how we could use the Scala Random function to generate random values and use it over the Scala Application. We also saw the various type by which we can create a random number. So it is a very good and important method used in Scala Programming for various Scala works.

Recommended Articles

We hope that this EDUCBA information on “Scala Random” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

How Strlen() Function Work In Php With Examples

Introduction to PHP strlen()

A large set of built-in functions make it easier for the coder or the developer to deal with string-related operations in PHP. The strlen() is one of the popular functions we can say of the PHP string to get the length of the string. As its name has been formed by combining two words, str, and len, str refers to the word string, and the length is the length itself. This function will return the length of the given string. This can be used to get the length of the string of any substring whenever required in the program.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Syntax:

strlen(String)

strlen: It is the function itself.

String: This is the only parameter that takes as a string.

Return Type:

This returns the length of the string, and it will always be an Integer. There is nothing much with the syntax of this function.

How strlen() Function work in PHP?

Before moving ahead with the strlen, we must have a strong first upon which this function will be applied. It takes the string as a parameter and returns the length of that given string. We can use the characters, special characters, URL, numeric values, and special sequence characters as part of the given string.

The user of strlen ()

Code:

$string = "WELCOME TO INDIA"; echo "Lenght of the given String is: "; echo strlen($string);

The above line of code given the length output as 16 as ‘WELCOME TO INDIA’ contains 16 characters, including the spaces.

Use of strlen() with the special sequence character as a string

We should be careful while passing a string containing special sequence characters like n,t,r, etc. As we can see, we n the 2 characters, but it will be counted as one while we will pass this as a parameter with the strlen() function.

Code:

$string = "rHello"; // a string $length = strlen($string); // lenghtof the string

The above line of code gives the output as 6 rather than 7. If we replace with any other character, then we will see the length 7 as an output. This could be a bit tricky while coding in php using the string strlen() function.

Examples of PHP strlen()

Given below are the examples mentioned :

Example #1

Get the length of the given string.

Code:

<?php $string = "WELCOME TO INDIA"; $Length = strlen($string); echo "Length of the given String is: ".$Length;

Output:

As we can see, there is not much in using this function due to the simplicity of this string function. We can consider this function as one of the easiest functions of the PHP string in nature, passing the string as a parameter to get the length.

Example #2

Get the length of the given string after removing all the spaces from that string.

Code:

<?php $string = "WELCOME TO INDIA"; $lenght = strlen($string); echo "Actual string: ".$string; echo "nLength of the given String including space: ".$lenght; $stringAfterRemovedSpace = str_replace(" ","",$string); echo "nActual String with no spaces: ".$stringAfterRemovedSpace; echo "nLength of the given String excluding space: ".strlen($stringAfterRemovedSpace);

Output:

Example #3

An example program demonstrates the use of strlen() function with the string containing the special character and the escape character.

Code:

<?php $string = "n WELCOME TO INDIA"; $Length = strlen($string); echo "Length of the given String is: ".$Length;

Output:

In the above program, when we count the character, it will come up to 19 in the manual, but it the program output, we can see that the length is showing 18. The length is showing one character lesser just because n is being counted as one.

Example #4

Code:

<?php $string = "WELCOME TO INDIA"; $length = strlen($string); echo "Actual String: ".$string; echo "nLength: ".$length; echo "nReverse String: "; { echo $string[$i]; }

Output:

In the above example code, we can see that the reversing string in php comes up with various stages, which include the getting length of the string, too, because the length of the given string helps the developer of the coder to loop through the end to the first position of the string.

Example #5

Length of the string and length of the reverse string of the same.

Code:

<?php $string = "n WELCOME Home!!!"; $length = strlen($string); echo "Actual String: ".$string; echo "nLength: ".$length; echo "nReverse String: "; $reverseString = ""; { $reverseString .= $string[$i]; } echo $reverseString; echo "nLength of the Reverse String: ".strlen($reverseString);

Output:

Conclusion

Built-in function strlen() can be used to get the length of the string. A developer should be aware enough of the functioning of this function. For example, if n, t, etc. contains in a string, then this 2-character special sequence can be considered as one. This function can be used to get the length of a string to make the further required operations. If we are writing our own custom string reverse code, then we can use this function to calculate the actual length of the string.

Recommended Articles

This is a guide to PHP strlen(). Here we discuss the introduction to PHP strlen(), how this function works, and programming examples. You may also have a look at the following articles to learn more –

How Does Printf Function Work In Perl With Examples

Introduction to Perl printf

Web development, programming languages, Software testing & others

Syntax:

The Perl scripts have default keywords, functions and scalar variables that means the variable accepts only the single value. It can be any numbers, letters, characters, digits with operators, but the first character of the variable always must be the letter or symbol; like the underscore operator, it’s not a digit.

$ variable name = value; printf(" ", $variable name); ---some Perl script logics--- How does the printf Function Work in Perl?

The Perl script printf() method prints only the user datas with the specified format specifiers on the screen. Actually, the function prints only the values, which is interpreted using the List datas through via using some format specifiers with the current result as the output. The filehandle concept is used for more space in the printf function, which handles the errors and exceptions by using exception classes and modules but the printf() function that prints the outputs by using some format specifiers. Generally, the printf function used some properties which are related to their fields and attributes.

Like that this function as many of the properties are to be same as the print function in the script. That’s the way it shows the better output format, which has already related to their user inputs. This is more similar to the field specifiers with co-related to their text string format specifiers with some delimiters like comma, semi-colon, underscore etc. Using some Regular Expressions concepts, the user inputs are to be validated and evaluated at the back end codes, showing the output on the user screen.

Examples of Perl printf

Given below are the examples of Perl printf:

Example #1

Code:

$var = 1562.45; $strn = ("Welcome To My Domain"); printf("Hi user your input is $%6.3f and converted output is %snn", $var, $strn);

Output:

Explanation:

In the above example, we used two variables like $var and $strn, and both the variables are used with some formats like $var variable assigned values are only the float type of numbers so the decimal point of results to be expected once the given variable is executed on the script like that it will be printed on the user screen.

Same time the next variable $strn accepts only the string values like “Welcome to My domain”, so it’s a string format it specifies the user information’s the printf function which has passed the calls to the string and also the field is specified to the variables and then it will insert into the memory locations for separate positions.

Example #2

Code:

printf("Welcome To My Domain:n"); printf("'%7d'n", 7); printf("'%7d'n", 596903); printf("'%7d'n", -94758); printf("'%7d'n", -904685); printf("n"); printf("Have a Nice Day:n"); printf("'%-8d'n", 785); printf("'%-8d'n", 1023894785); printf("'%-8d'n", -923487568); printf("'%-8d'n", -1293475); printf("n"); printf("n"); printf("Thanks for your interest in our application:n"); printf("'%09d'n", 3); printf("'%09d'n", 223); printf("'%09d'n", 9234687); printf("'%09d'n", -9238747); printf("'%09d'n", -2390478); printf("'%04d'n", 23); printf("'%04d'n", 'Welcome'); printf("'%04d'n", 'Welcome34'); printf("'%04d'n", -9243747); printf("'%04d'n", -4590478); printf("'%02d'n", 'Tyujk'); printf("'%02d'n", 'udg 4857 sdhfg'); printf("'%02d'n", 9238747); printf("'%03d'n", -93476538747); printf("'%02d'n", -239754478);

Output:

Explanation:

In the second example, we have used the same printf function in different ways. We can pass the inputs in numbers that will be the integer, float, decimal, short, long and double; it can be any of the types passing into the function, and it is converted into the required output format.

Some formats will follow the rules and control the fields with some heights, widths, and even other fields like printing left-justified, right-justified and zero-filled numbers stored in the variables for calculating their functions and storages the memory locations. It accepts both positive and negative numbers followed by its signatures and its relevance to their usages.

Example #3 printf("'%4s'n", "Welcome"); printf("'%76s'n", "Welcome"); printf("'%-76s'n", "Welcome"); printf("Welcome To My Domainn"); printf("Have a Nice Dayn"); printf("kjadgvds hasjkgdf ashdjfh jsdhfhj ajsgn"); printf("WelcometTo My Domainn"); printf("jasg hsagdfj skjdfhk skdh shfj sjn"); printf("Welcomen To My Domainn"); printf("kjshdfj kjahksj nkjh 2734 shj2983 3974y kn"); printf("C:UsersKripya-PCDocumentsarticles\n"); printf("hsdfjg jhajs kjaskdj kjaksd jaskn"); printf("weh jkhj kawj kwejk jwlkl lkwqejkwlkqjlkn"); printf("'%.3f'nn", 873.974); printf("87v hk jskj oi3y khk38 i347 bi3748n"); printf("'%.5f'n", 873.975); printf("jdshj38 3784 3748687j he83sk 94n"); printf("'%6.4f'n", 748.28374); printf("u3928 oiwu498y bu4589 io349 b3974n"); printf("'%7.14f'n", 734.837495); printf("3749 yiwe b843 sekk48905 je48n"); printf("'%06.4f'n", 83.8346); printf("2638 hy3w8 j8939475 jbi34y8b wu4985b 3u984y bu498n"); printf("'%-6.3f'nn", 857.98374); printf("26837 hjkwehr234yv hj gu4 s h  jkh jkjkh 3987n"); printf("'%-5.25f'n", 8347958.892365);

Output:

Explanation:

In the printf() function, we used both numbers and string characters in various format specifiers, and even some comparison operators are used and called with the same reference names. Because the printf function used some operators allowed with string formats and it has generated the reports with formats and even though the formatted holds with the some numbers that can be called through with the help of some conversions.

And these conversions will used some operators like the % sign with the end of the characters even though the same number of characters are assigned through its conversions. Using some exponential notations is required for the printf function.

Conclusion

In conclusion, they must have some built-in methods for printing the outputs on the screen for each programming languages. Likewise, each method has its own attributes and properties for showing its results as much as needed from the user perspective. In Perl, the printf function used some format specifiers for displaying the outputs on the user screen.

Recommended Articles

This is a guide to Perl printf. Here we discuss the introduction; how does the printf function work in Perl? and examples, respectively. You may also have a look at the following articles to learn more –

How Do 3D Shapes Work In Javafx With Examples

Introduction to JavaFX 3D

The 3D shapes in JavaFX are geometrical figures that can be represented on the X, Y and Z planes simultaneously. X plane represents length or depth, Y plane represents the height and the Z plane represents width. General 3D shapes are Cube, Cuboid, Cylinder, Cone, Sphere, etc. 3D shapes are included in Shape3D class and all shapes are included in the Shape class (2D and 3D shapes). Shape3D is the base class of all shapes. Shape class is available within the scene. Shape package. We can make use of it by importing this package.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Create a 3-Dimensional Shape

Create the object for the required 3D shape.

Add all the required properties.

Add the 3D shape object reference to any JavaFX element like Group, VBox, HBox, Pane, etc.

Frequently Used Shapes

Below are the Frequently used shapes and their description

The cuboid is a three-dimensional shape with a length (depth), width, and height.

A cuboid has 3D shapes with length, height, and width. This is available in Box Box class is within javafx.scene.shape package.

2. Cylinder

The cylinder is a closed solid object that has 2 parallel circle bases on top and bottom.

A cylinder has height and radius properties. Each circle has the same radius. A cylinder is available inside Cylinder

This Cylinder class is available within the scene. shape package.

3. Sphere

The Sphere is a circle like structure, which have a set of points that are kept all are in the equal distance with “r” radius.

The sphere exists inside the Sphere

This Sphere class is available within the scene. shape package.

Constructors

Box(): It creates the Box object with a new keyword.

Cylinder(): It creates the Cylinder object with a new keyword.

Sphere(): It creates the Sphere object with a new keyword.

Importance Cull Face Property

Culling means remove the improperly aligned parts of the 3D or 2D object shapes. By applying this cull property we can make these parts not visible in the shape view area. We can set cull face property by setCullFace(CullFace.Type)

This method consisting of 3 arguments:

NONE: This is the default property. It does not have any cull face.

FRONT: All the front face polygon parts are removed.

BACK: All the back facing polygon parts are removed.

Frequently Used Methods

setRadius(double r): It sets the radius.

setTranslateX(int x): It sets the horizontal location of this view relative to the left position.

setTranslateY(int y): It sets the vertical location of this view relative to the right position.

setTranslateZ(int z): It sets either horizontal or vertical location of this view relative either left to the right position.

setWidth(double w): It sets the width.

setHeight(double h): It sets the height.

setDepth(doubled): It sets the depth.

setMaterial(): It is used to set the rendering of the shape.

How do 3D Shapes work in JavaFX?

1. Accessing JavaFX features user-defined class must extend Application. Creating Cuboid or Sphere or Cylinder etc class is 1st This classes can be created by using the new keyword.

Syntax #1

Box cuboidRef=new Box();

Or

Sphere sphereRef=new Sphere();

Or

Cylinder cylinderRef=new Cylinder();

2. Creating a Group element is the 2nd It is used to add the canvas object.

Syntax #2

Group groupRef = new Group(cuboidRef or sphereRef or cylinderRef );

3. 3rd step is creating Scene for apply show method on to it.

Syntax #3

Scene screen = new Scene(groupRef, length, width);

4. Adding Scene reference screen to the Stage object reference is 4th Adding output screen to Stage. We will get this stage object reference from the start predefined JavaFX method.

stage.setScene(screen);

5. 5th step is showing output to the end-user by applying the show () method on the scene object.

Syntax #5

stage.show(); Examples to Implement JavaFX 3D

Below are the examples:

Example #1

Sphere with Green background-color

Code:

package com.shapes; import javafx.application.Application; import javafx.scene.Camera; import javafx.scene.Group; import javafx.scene.PerspectiveCamera; import javafx.scene.Scene; import javafx.scene.input.KeyEvent; import javafx.scene.paint.Color; import javafx.scene.shape.Sphere; import javafx.stage.Stage; public class SphereDemo extends Application { @Override public void start(Stage outputStageObject) { outputStageObject.setTitle("Sphere Demo"); Sphere sphereObject = new Sphere(50); Group groupObject = new Group(); groupObject.getChildren().add(sphereObject); Camera perspectiveCamera = new PerspectiveCamera(); Scene sceneObject = new Scene(groupObject, 500, 500); sceneObject.setFill(Color.GREEN); sceneObject.setCamera(perspectiveCamera); sphereObject.translateXProperty().set(500 / 2); sphereObject.translateYProperty().set(500 / 2); switch (eventHandler.getCode()) { case A: sphereObject.translateZProperty().set(sphereObject.getTranslateZ() + 300); break; case B: sphereObject.translateZProperty().set(sphereObject.getTranslateZ() - 300); break; } }); outputStageObject.setScene(sceneObject); outputStageObject.show(); } public static void main(String[] args) { launch(args); } }

Output:

Example #2

User-Defined Triangle

package com.shapes; import javafx.animation.Animation; import javafx.animation.RotateTransition; import javafx.application.Application; import javafx.scene.Group; import javafx.scene.PerspectiveCamera; import javafx.scene.PointLight; import javafx.scene.Scene; import javafx.scene.paint.Color; import javafx.scene.shape.MeshView; import javafx.scene.shape.TriangleMesh; import javafx.scene.transform.Rotate; import javafx.stage.Stage; import javafx.util.Duration; public class UserDefinedShapes extends Application { public MeshView createMeshView() { float[] allPoints = { 50, 0, 0, 45, 10, 0, 55, 10, 0 }; float[] coordinatesValues = { 0.5f, 0.5f, 0.0f, 1.0f, 1.0f, 1.0f }; int[] faceValues = { 0, 0, 2, 2, 1, 1, 0, 0, 1, 1, 2, 2 }; TriangleMesh mesh = new TriangleMesh(); mesh.getPoints().addAll(allPoints); mesh.getTexCoords().addAll(coordinatesValues); mesh.getFaces().addAll(faceValues); MeshView meshView = new MeshView(); meshView.setMesh(mesh); return meshView; } @Override public void start(Stage stageOutObject) { stageOutObject.setTitle("Triangle Movable 3D Demo"); MeshView createMeshView = this.createMeshView(); createMeshView.setTranslateX(100); createMeshView.setTranslateY(150); createMeshView.setTranslateZ(500); createMeshView.setScaleX(11.0); createMeshView.setScaleY(11.0); createMeshView.setScaleZ(11.0); PerspectiveCamera cameraPerspective = new PerspectiveCamera(false); cameraPerspective.setTranslateX(100); cameraPerspective.setTranslateY(-150); cameraPerspective.setTranslateZ(500); RotateTransition rotateShape = new RotateTransition(Duration.seconds(3), cameraPerspective); rotateShape.setCycleCount(Animation.INDEFINITE); rotateShape.setFromAngle(-40); rotateShape.setToAngle(40); rotateShape.setAutoReverse(true); rotateShape.setAxis(Rotate.Y_AXIS); rotateShape.play(); PointLight colorLight1 = new PointLight(); colorLight1.setColor(Color.CHARTREUSE); colorLight1.setTranslateX(350); colorLight1.setTranslateY(250); colorLight1.setTranslateZ(500); PointLight colorLight2 = new PointLight(); colorLight2.setColor(Color.GREEN); colorLight2.setTranslateX(300); colorLight2.setTranslateY(250); colorLight2.setTranslateZ(550); Group groupObject = new Group(createMeshView, colorLight1, colorLight2); groupObject.setRotationAxis(Rotate.Y_AXIS); groupObject.setRotate(90); Scene scene = new Scene(groupObject, 450, 400, true); scene.setCamera(cameraPerspective); stageOutObject.setScene(scene); stageOutObject.show(); } public static void main(String[] args) { Application.launch(args); } }

Output:

Example #3

Cylinder

Code:

package com.shapes; import javafx.application.Application; import javafx.scene.Group; import javafx.scene.PerspectiveCamera; import javafx.scene.Scene; import javafx.scene.paint.Color; import javafx.scene.shape.Cylinder; import javafx.stage.Stage; public class CylinderDemo extends Application { @Override public void start(Stage outputStageObject) throws Exception { outputStageObject.setTitle("Cylinder 3D Demo"); Cylinder cylinderObject = new Cylinder(); cylinderObject.setRadius(65); cylinderObject.setHeight(200); cylinderObject.setTranslateX(200); cylinderObject.setTranslateY(140); PerspectiveCamera perspectveCamera = new PerspectiveCamera(); perspectveCamera.setTranslateX(10); perspectveCamera.setTranslateY(10); perspectveCamera.setTranslateZ(30); Group groupObject = new Group(); groupObject.getChildren().addAll(cylinderObject); Scene scene = new Scene(groupObject, 400, 300, Color.DARKORCHID); scene.setCamera(perspectveCamera); outputStageObject.setScene(scene); outputStageObject.show(); } public static void main(String[] args) { launch(args); } }

Output:

Conclusion

JavaFX 3D shapes are existed within javafx.scene.Shape class. Cylinder, Cuboid, Sphere, 3d triangle, etc. have come into 3-dimensional shapes. These 3D shapes are used in Space applications, civil engineering applications, aviation applications, etc.

Recommended Articles

This is a guide to JavaFX 3D. Here we discuss 3-dimensional shape, constructors, how JavaFX 3D work, and examples to implement for better understanding. You can also go through our other related articles to learn more –

Update the detailed information about How File Handling Work In Scala With Eamples on the Katfastfood.com website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!