Domanda Please Help in Java Program

lokeshjoshi

Utente Iron
25 Marzo 2023
1
1
0
2
Hi all,

I am new to learning Java Programming language and am in my first year of engineering. i am writing a java program to create a new string taking first and last characters from two given strings. Here is my Code: here is the Code link

Java:
import java.lang.*;
 public class Exercise73 {
 public static void main(String[] args)
 {
    String str1 = "Java";
    String str2 = "";
    
    int length1 = str2.length();
    String result = "";
    result += (str1.length() >= 1) ? str1.charAt(0) : '#';
    result += (length2 >= 1) ? str2.charAt(length2-1) : '#';
    System.out.println(result);
 }
}

When I try to compile the code getting an error, can any one please help me in this?
 
Ultima modifica:
Hi, there are some errors. First the indentation of the code: the main must be indented with respect to the outer class. Then you used the "length2" variable without declaring or initializing it. Finally, you have erroneously associated "length1" with "str2", but this is not a real error: for code clarity, associate "length1" with "str1". You should do something like this:
Java:
import java.util.*;

public class Main {
    public static void main(String[] args) {
     
        // Variable declaration and initialization
        String str1 = "pizza";
        String str2 = "mandolino";
        String result = "";
        int length1 = str1.length();
        int length2 = str2.length();
     
        // Check conditions on strings
        if (length1 > 0){
            result += str1.charAt(0);
        } else {
            result += '#';
        }
     
        if (length2 > 0){
            result += str2.charAt(length2 - 1);
        } else {
            result += '#';
        }
     
        // Printout of the result
        System.out.println(result);
    }
}



Don't use the syntax abbreviation if you are a beginner and if you have any other doubts let us know. Bye ;)
 
  • Mi piace
Reazioni: lokeshjoshi