Trending March 2024 # Golang Program To Create An Enum Class # Suggested April 2024 # Top 3 Popular

You are reading the article Golang Program To Create An Enum Class updated in March 2024 on the website Moimoishop.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 Golang Program To Create An Enum Class

An enum combines related constants into a single type. Enums are a strong feature with many applications. However, compared to the majority of other programming languages, they are implemented very differently in Go. In this article, we’ll see how to use a predeclared identifiable iota to implement enums in Golang.

IOTA − Iota is an identifier that is used with constants and can make auto-increment number-based constant definitions simpler. The keyword “iota” stands for an integer constant that begins at zero.

Implementing Iota package main import "fmt" const ( c0 = iota + 1 c1 c2 ) func main() { fmt.Println(c0, c1, c2) } Output 1 2 3 Creating an Enum for Weekdays Algorithm

Step 1 − Import the fmt package that allows us to print anything on the screen.

Step 2 − create a new data type as Weekday to store the integer types for weekdays.

Step 3 − Declare related constants for each weekday starting with index 1.

Step 4 − Create a function to get the weekday as a string from the integer values provided.

Step 5 − creating a function to get the index of the enum.

Step 6 − calling the main() function.

Step 7 − initializing a Weekday type and storing a day in it.

Step 8 − print the corresponding weekday and index by calling the getWeekday() and getIndex() function respectively.

Example

In the following example, we are creating enum for weekdays.

package main import "fmt" type Weekday int const ( Sunday Weekday = iota + 1 Monday Tuesday Wednesday Thursday Friday Saturday ) func (w Weekday) getWeekday() string{ return [...]string{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"} [w-1] } func (w Weekday) getIndex() int { return int(w) } func main() { var weekday = Sunday fmt.Println(weekday) fmt.Println(weekday.getWeekday()) fmt.Println(weekday.getIndex()) } Output 1 Sunday 1 Creating an Enum for Direction Algorithm

STEP 1 − Import the fmt package that allows us to print anything.

STEP 2 − Create a new type Direction to store the integer types for direction starting from 1-7

STEP 3 − Declare constants for each direction as Direction and index the set of constants with iota. Note that the first direction i.e north is indexed as iota + 1 i.e 1 and the following directions will get the index as auto incremented values.

STEP 4 − Now we need to create functions to the Direction type. The first function returns the direction as the string and we have named this function as getDirection(). While the other function returns the integer value of enum index and we have named this function as getIndex().

STEP 5 − Now call the main() function this is the main starting point of the program from where the program gets executed.

STEP 6 − Creating a new variable of Direction type and storing one of the direction as value to it.

STEP 7 − Now we can print the direction as well as enum index corresponding to that direction by calling the getDirection() and getIndex() function respectively.

STEP 8 − Print the result returned by this function on the screen by using fmt.Println() function.

Example

In the following example we are creating an enum for direction

package main import "fmt" type Direction int const ( North Direction = iota + 1 East South West ) func (d Direction) getDirection() string { return [...]string{"North", "East", "South", "West"}[d-1] } func (d Direction) getIndex() int { return int(d) } func main() { var d Direction = West fmt.Println(d) fmt.Println(d.getDirection()) fmt.Println(d.getIndex()) } Output 4 West 4 Conclusion

We have successfully compiled and executed a golang program to create an enum class along with examples. we have created various functions to implement the logic of creating the enum class.

You're reading Golang Program To Create An Enum Class

Golang Program To Reverse A String Using Stacks

In this article, we will see how to reverse a string using stacks with Go Programming. A stack is a Last In First Out (LIFO) compliant data structure in Go. This implies that the first element to be eliminated will be the one that was most recently added to the stack. A doubly-linked list is implemented in the built-in Go package “container/list” and can be used to build a stack. Slices (dynamic arrays) are frequently used to implement stacks in Go, though. Let’s see how it’s executed using different set of examples.

Method 1: Converting the string to slice of runes

In this method, we will see how to reverse a string using stacks by converting the string to slice of runes. Runes are Go’s equivalent of characters thus it first slices the string into them before pushing each one into the stack. The next step is to remove each rune from the stack and add it to a fresh string. As a result, the original string is turned around. The reverse function is then used on a string by the main function, which prints both the original and the inverted string. Let’s see its execution.

Syntax func append(slice, element_1, element_2…, element_N) []T

The append function is used to add values to an array slice. It takes number of arguments. The first argument is the array to which we wish to add the values followed by the values to add. The function then returns the final slice of array containing all the values.

Algorithm

Step 1 − Create a package main and declare fmt(format package) package in the program where main produces executable Example:s and fmt helps in formatting input and output.

Step 2 − Create a function reverse and make a variable to store the reversed string and an empty stack to hold it.

Step 3 − Transform the input string taken into the function into a rune slice.

Step 4 − Push each rune from the slice onto the stack one at a time.

Step 5 − Pop each rune off the stack and add it to the inverted string as you go through the st ack.

Step 6 − Return the string that has been reversed as the result.

Step 7 − Call the function reverse from the main function with one argument of a string which is to be reversed.

Step 8 − The reversed string is printed on the console using fmt.Println() function where ln means new line.

Example

In the following example, we are going to reverse the strings by converting the strings to slices of runes.

package main import ( "fmt" ) func reverse(str string) string { runes := []rune(str) var stack []rune for _, v := range runes { stack = append(stack, v) } var reversed string reversed += string(stack[i]) } return reversed } func main() { original := "Hello, alexa!" fmt.Println("The original string given here is:", original) reversed := reverse(original) fmt.Println("The reversed string here is:", reversed) } Output The original string given here is: Hello, alexa! The reversed string here is: !axela ,olleH Method 2: Using stacks with the help of struct in example

In this method, we will use struct to reverse a string. The Stack struct, which implements the Push and Pop methods to add and remove items from the stack, is used in the aforementioned program. In the main function, each character from the input string is placed into the stack using a for loop after creating an instance of the Stack struct. Each character is taken off of the stack using a second for loop, added to a new string, and then printed as the inverted string. Let’s see its execution.

Algorithm

Step 1 − Create a package main and declare fmt(format package) package in the program where main produces executable Examples and fmt helps in formatting input and output.

Step 2 − Incorporate the Push and Pop functions into a struct called Stack to add and remove things from the stack, respectively.

Step 3 − Initialize a Stack struct instance in the main function and take a string that has to be reversed as an input.

Step 4 − Push each character of the input string onto the stack using the Push technique using a for loop.

Step 5 − Create a blank string with the name reversed.

Step 6 − Use a second for loop to add each character to the reversed string by using the Pop function to remove them from the stack.

Step 7 − Print the reversed string as an output using fmt.Println() function where ln means new line.

Step 8 − As we iterate through the string twice, once to place the character on the stack and once to pop it from the stack, the overall time complexity of this approach is O(n), where n is the length of the input string. Due to the use of a second stack to hold the characters, the space complexity of this technique is also O(n).

Example

In the following example, we are going to reverse the strings by using stacks with the help of struct in example

package main import "fmt" type Stack struct { items []rune } func (str *Stack) Push(item rune) { str.items = append(str.items, item) } func (str *Stack) Pop() rune { item := str.items[len(str.items)-1] str.items = str.items[:len(str.items)-1] return item } func main() { stack := &Stack{} str := "hello alexa" fmt.Println("The original string is:", str) for _, char := range str { stack.Push(char) } reversed := "" for i := 0; i < len(str); i++ { reversed += string(stack.Pop()) } fmt.Println("The reversed string is:") fmt.Println(reversed) } Output The original string is: hello alexa The reversed string is: axela olleh Conclusion

We executed the program of reversing a string using stack with the help of different examples. In the first example we converted the string to slice of runes and in the second method we used the struct to execute the function.

Golang Program To Reverse A Sentence Using Recursion

In this tutorial, we will learn how to reverse a sentence using recursion in Go Programming Language.

A Recursion is where a function calls itself by direct or indirect means. Every recursive function has a base case or base condition which is the final executable statement in recursion and halts further calls. The recursion continues until some condition is met to prevent it.

Below are two examples showing the two different type of recursion: direct and indirect.

Reverse a Sentence using Recursion by using Direct Recursion Method Syntax Func recursion() { recursion(); /* function calls itself */ } func main() { recursion(); } Algorithm

Step 1 − Import the package fmt

Step 2 − Create the function reversesentence ()

Step 3 − Use the if condition to execute the code

Step 4 − Recursive call of the function itself

Step 5 − Start the function main()

Step 6 − call the function reversesentence ()

Step 7 − Print the result using fmt.Print().

Example

Golang Program code to Reverse a Sentence using Recursion by using Direct Recursion Method.

package

main

import

“fmt”

func

reversesentence

(

input string

)

{

if

len

(

input

)

==

0

{

return

}

reversesentence

(

input

[

1

:

]

)

fmt

.

Print

(

string

(

input

[

0

]

)

)

}

func

main

(

)

{

fmt

.

Println

(

“GOLANG PROGRAM TO REVERSE A SENTENCE USING RECURSION”

)

fmt

.

Println

(

“Entered sentence =”

)

var

sentence string sentence

=

“Taylor Swift is the best”

fmt

.

Println

(

sentence

)

reversesentence

(

sentence

)

}

Output GOLANG PROGRAM TO REVERSE A SENTENCE USING RECURSION Entered sentence = Taylor Swift is the best tseb eht si tfiwS rolyaT Description of the Code

In the above program, we first declare the package main

We will use an if conditional statement which allows you to execute one block of code and if it is false then recursive call to the function itself

Reverse a Sentence using Recursion by using Indirect Recursion Method Syntax func recursion_1() { recursion_2() } func recursion_2(){ recursion_1() } func main() { recursion_1(); } Algorithm

Step 1 − Import the package fmt

Step 2 − Create the function reverse ()

Step 3 − Use the if condition to execute the code

Step 4 − Recursive call of the function reverse2()

Step 5 − Create the function reverse2()

Step 6 − Recursive call to the function reverse() indirectly)

Step 7 − Start the function main()

Step 8 − Call the function reverse()

Step 9 − Print the result on the screen using fmt.Print()

Example

Golang Program code to Reverse a Sentence Using Recursion by using Indirect Recursion Method

package

main

import

“fmt”

func

reverse

(

input string

)

{

if

len

(

input

)

==

0

{

return

}

reverse2

(

input

[

1

:

]

)

fmt

.

Print

(

string

(

input

[

0

]

)

)

}

func

reverse2

(

n string

)

{

if

len

(

n

)

==

0

{

return

}

reverse

(

n

[

1

:

]

)

fmt

.

Print

(

string

(

n

[

0

]

)

)

}

func

main

(

)

{

fmt

.

Println

(

“GOLANG PROGRAM TO REVERSE A SENTENCE USING RECURSION”

)

var

sentence string sentence

=

“Golang Solutions”

fmt

.

Println

(

“Entered Sentencen”

,

sentence

)

reverse2

(

sentence

)

}

Output GOLANG PROGRAM TO REVERSE A SENTENCE USING RECURSION Entered Sentence Golang Solutions snoituloS gnaloG Description of the Code

In the above program, we first declare the package main

We will use an if conditional statement which allows you to execute one block of code and if it is false then recursive call to the second function reverse2()

Next we create a function reverse2().Here recursive function call to the first function is made which calls the first function reverse () indirectly

Now start the function main().GO program execution starts with the function main()

Next we call the reverse() function to reverse a sentence.

And finally printing the reverse of the sentence on the screen using in-built function fmt.Print().This function is defined under the fmt package and it helps to write standard output.

Conclusion

In the above two examples we have successfully compiled and executed the Golang program code to reverse a sentence using recursion technique. We have shown direct and indirect type of recursion method. In the first example we have shown direct recursion method and in the second example we have shown indirect recursion method.

Golang Program To Demonstrate Begin And End Blocks

In this Go language article, we will write programs to demonstrate BEGIN and END blocks using sum of numbers, iteration and two variables.

Blocks are used to group the statements where the variables described in the block can only be used in that scope and not outside it. They also help in code readability

Algorithm

Step 1 − Create a package main and declare fmt(format package) package in the program where main produces executable codes and fmt helps in formatting input and output.

Step 2 − Create a main function and in this function create two begin and end blocks enclosed within curly braces.

Step 3 − In the first block take two numbers in two variables named a and b, add these numbers and assign them to c.

Step 4 − Print the c on the console using Printf function from fmt package.

Step 5 − In the second block take the name and age of a person and print it similarly like we did in last step.

Example 1

In this Example, we will create two begin and end blocks in the main function. In the first block we will print the sum of two numbers and in the second block we will print the name and age of a person.

package main import "fmt" func main() { { a := 10 b := 20 c := a + b fmt.Printf("The sum of %d and %d is %dn", a, b, c) } { name := "Ronit" age := 34 fmt.Printf("%s is %d years oldn", name, age) } } Output The sum of 10 and 20 is 30 Ronit is 34 years old Example 2

In this illustration, we will create two begin and end block and an anonymous function will be used to execute the begin and end chúng tôi the first block some statements will be executed whereas in the second block numbers will be printed using iteration.

package main import "fmt" func main() { func() { defer fmt.Println("This statement is executed last in the program") fmt.Println("This statement is executed first in the program") }() func() { for i := 1; i<= 6; i++ { defer fmt.Printf("%d ", i) } }() } Output This statement is executed first in the program This statement is executed last in the program 6 5 4 3 2 1 Example 3

In this Example, we will write a Go language program to demonstrate the BEGIN and END blocks using two variables a and b.

package main import "fmt" func main() { { a := 20 fmt.Println("Value of x inside begin block:", a) } { b := "Hello, alexa!" fmt.Println("Value of y inside begin block:", b) } } Output Value of x inside begin block: 20 Value of y inside begin block: Hello, alexa! Conclusion

We executed the program of demonstrating the begin and end blocks. In the first Example, we created two blocks and printed the output using the fmt package whereas in the second Example, we used defer keyword while printing the output of blocks and in the third Example, we used two variables to execute the program.

Java Program To Access All The Constant Defined In The Enum

After JDK version 5 java introduces the enumeration. It is a group of constants defined using the keyword ‘enum’. The final variables in java are somewhat similar to enumeration.

In this article, we will make a java program in which we define an enum class and try to access all the constant defined in the enum by using valueOf() and values() methods.

Enum

We use enum class when we need to define a fixed set of constants. For example, if we want to use the days of the week, planet names, names of all five vowels etc. Note that all the names of constants are declared in uppercase letters.

Although enum is a class type in java, we can’t instantiate it. Each constant defined in an enum is the instance of its enum type. It provides other functionalities of a class like we can create its instance variables, methods and constructors.

Syntax Enum enumeration_name { } Example enum Planet { EARTH, MARS, JUPYTER, NEPTUNE, SATURN, URANUS, VENUS; }

The above example illustrates how we can create an enum class. Name of the enum is Planet and the variables EARTH, MARS are its constants. By default, they are declared as public and static. These constants are self-typed because their type is defined by the enumeration in which they are defined. In this case, they are of Planet type.

Program to Access all Constant defined in the Enum

valueOf() and values() are the two predefined methods that will help us to get the values of constants defined in the list.

valueOf() − It returns the value of constant that is passed as argument.

values() − It returns an array that contains all the constants present in enum class.

Example 1

The following example demonstrates how we can get the constants by using valueOf() method &minuns;

enum Vibgyor { VIOLET, INDIGO, BLUE, GREEN, YELLOW, ORANGE, RED; } public class Main { public static void main(String[] args) { System.out.println("The color present in VIBGYOR: "); Vibgyor color = Vibgyor.ORANGE; System.out.println(color + " is present at index: " + color.ordinal()); Vibgyor colr = Vibgyor.valueOf("INDIGO"); System.out.println(colr); System.out.print(Vibgyor.valueOf("RED")); } } Output The color present in VIBGYOR: ORANGE is present at index: 5 INDIGO RED

In the above program, we have created an enum ‘Vibgyor’ with some constants. The two variables ‘color’ and ‘colr’ are the enumeration variable of type Vibgyor. Using these variables we have fetched the constants. Using valueOf() method we can get one item at a time. The ordinal() method is used here to access the index value of ORANGE. Indexing starts from 0. We can also access the constant without creating any variable.

Example 2

The following example demonstrates how we can get the constants by using values() method −

enum Vibgyor { VIOLET, INDIGO, BLUE, GREEN, YELLOW, ORANGE, RED; } public class Main { public static void main(String[] args) { System.out.println("The color present in VIBGYOR: "); for(Vibgyor color : Vibgyor.values()) { System.out.println(color); } } } Output The color present in VIBGYOR: VIOLET INDIGO BLUE GREEN YELLOW ORANGE RED

In the above program, we have accessed all the constants with a single for each loop. values() method can access multiple values at a time.

Conclusion

In this article, we have discussed enum and its methods. We have created java program to understand how we can access all the constants defined in the enum using values() and valueOf() methods.

Java Program To Create A Calculator

To create a calculator with Java Swings, try the following code −

Example import java.awt.Color; import java.awt.Container; import java.awt.FlowLayout; import javax.swing.JFrame; import javax.swing.JLabel; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JTextField;

public class SwingDemo extends JFrame implements ActionListener {    JButton one, two, three, four, five, six, seven, eight, nine, num0, add, sub, div, mult, equalto, exit, point, reset;    JTextField textField;    String s = "", ope = "";    int flag = 0;    double total1;    double input1, input2;    void total(double input1, double inout2, String ope) {       String total;       if (ope.equalsIgnoreCase("+")) {          total1 = input1 + input2;          total = Double.toString(total1);          textField.setText(total);       } else if (ope.equalsIgnoreCase("-")) {          total1 = input1 - input2;          total = Double.toString(total1);          textField.setText(total);       } else if (ope.equalsIgnoreCase("*")) {          total1 = input1 * input2;          total = Double.toString(total1);          textField.setText(total);       } else if (ope.equalsIgnoreCase("/")) {          total1 = input1 / input2;          total = Double.toString(total1);          textField.setText(total);       }          }    public SwingDemo() {       Container container = getContentPane();       container.setLayout(new FlowLayout());       JLabel jl = new JLabel(" My Demo Calculator ");       textField = new JTextField(15);       one = new JButton(" 1 ");       two = new JButton(" 2 ");       three = new JButton(" 3 ");       four = new JButton(" 4 ");       five = new JButton(" 5 ");       six = new JButton(" 6 ");       seven = new JButton(" 7 ");       eight = new JButton(" 8 ");       nine = new JButton(" 9 ");       num0 = new JButton(" 0 ");       add = new JButton(" + ");       sub = new JButton(" - ");       div = new JButton(" / ");       mult = new JButton(" * ");       equalto = new JButton(" = ");       exit = new JButton(" Exit ");       point = new JButton(" . ");       reset = new JButton("C");       reset.setBackground(Color.YELLOW);             one.addActionListener(this);       two.addActionListener(this);       three.addActionListener(this);       four.addActionListener(this);       five.addActionListener(this);       six.addActionListener(this);       seven.addActionListener(this);       eight.addActionListener(this);       nine.addActionListener(this);       num0.addActionListener(this);       add.addActionListener(this);       sub.addActionListener(this);       mult.addActionListener(this);       div.addActionListener(this);       equalto.addActionListener(this);       exit.addActionListener(this);       point.addActionListener(this);       reset.addActionListener(this);       container.add(jl);       container.add(textField);       container.add(one);       container.add(two);       container.add(three);       container.add(add);       container.add(four);       container.add(five);       container.add(six);       container.add(sub);       container.add(seven);       container.add(eight);       container.add(nine);       container.add(div);       container.add(num0);       container.add(point);       container.add(mult);       container.add(equalto);       container.add(reset);       container.add(exit);    }    public static void main(String arg[]) {       SwingDemo d = new SwingDemo();       d.setSize(260, 300);       d.setVisible(true);    }    public void actionPerformed(ActionEvent e) {       Object o = e.getSource();       if (o == one) {          textField.setText(s.concat("1"));          s = textField.getText();       } else if (o == two) {          textField.setText(s.concat("2"));          s = textField.getText();       } else if (o == three) {          textField.setText(s.concat("3"));          s = textField.getText();       } else if (o == four) {          textField.setText(s.concat("4"));          s = textField.getText();       } else if (o == five) {          textField.setText(s.concat("5"));          s = textField.getText();       } else if (o == six) {          textField.setText(s.concat("6"));          s = textField.getText();       } else if (o == seven) {          textField.setText(s.concat("7"));          s = textField.getText();       } else if (o == eight) {          textField.setText(s.concat("8"));          s = textField.getText();       } else if (o == nine) {          textField.setText(s.concat("9"));          s = textField.getText();       } else if (o == num0) {          textField.setText(s.concat("0"));          s = textField.getText();       } else if (o == add) {          textField.setText("");          input1 = Double.parseDouble(s);          System.out.println(input1);          s = "";          ope = "+";       } else if (o == sub) {          textField.setText("");          input1 = Double.parseDouble(s);          s = "";          ope = "-";       } else if (o == mult) {          textField.setText("");          input1 = Double.parseDouble(s);          s = "";          ope = "*";       } else if (o == div) {          textField.setText("");          input1 = Double.parseDouble(s);          s = "";          ope = "/";       } else if (o == equalto) {          if (flag == 0) {             input2 = Double.parseDouble(s);             total(input1, input2, ope);             flag = 1;          } else if (flag == 1) {             input2 = Double.parseDouble(s);             total(input1, input2, ope);          }          System.out.println(input1);       } else if (o == exit) {          System.exit(0);       } else if (o == point) {          textField.setText(s.concat("."));          s = textField.getText();       }       if (o == reset) {          textField.setText("");          s = textField.getText();          total1 = 0;       }    }

Update the detailed information about Golang Program To Create An Enum Class on the Moimoishop.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!