source code java
creds to chat gpt heheunknown
plain_text
2 years ago
2.6 kB
9
Indexable
import java.util.Scanner; // Importing Scanner class for user input public class Example { public static void main(String[] args) { // Basics of Java and input/output System.out.println("Hello, welcome to the Java example!"); // Relational operators and if...else statements Scanner scanner = new Scanner(System.in); System.out.print("Enter your age: "); int age = scanner.nextInt(); if (age >= 18) { System.out.println("You are an adult."); } else { System.out.println("You are a minor."); } // Logical operators and compound statements boolean isStudent = true; if (age >= 18 && isStudent) { System.out.println("You are an adult student."); } // Switch statement System.out.print("Enter a day (1-7): "); int day = scanner.nextInt(); switch (day) { case 1: System.out.println("Sunday"); break; case 2: System.out.println("Monday"); break; // ... cases for other days ... default: System.out.println("Invalid day"); } // For loop and array int[] numbers = {1, 2, 3, 4, 5}; System.out.println("Printing array elements using a for loop:"); for (int i = 0; i < numbers.length; i++) { System.out.print(numbers[i] + " "); } System.out.println(); // Move to the next line // While loop System.out.println("Printing array elements using a while loop:"); int index = 0; while (index < numbers.length) { System.out.print(numbers[index] + " "); index++; } System.out.println(); // Move to the next line // Creating a method int result = addNumbers(10, 20); System.out.println("Result of adding two numbers: " + result); // Calling a method and passing parameters by value int a = 5; int b = 7; swapValues(a, b); System.out.println("Values after swap - a: " + a + ", b: " + b); // File input/output (not covered in this basic example) } // Method to add two numbers private static int addNumbers(int x, int y) { return x + y; } // Method to swap values (not actually swapping due to Java's pass by value) private static void swapValues(int m, int n) { int temp = m; m = n; n = temp; } }
Editor is loading...
Leave a Comment