-1

I tried recently to build an app that shows you a generated text using the first two letters from your firstname, and last two letters from lastname but it doesn't work.

import java.util.Scanner;
    public class HW2ex2 {
        public static void main (String[] args) {
            Scanner scan = new Scanner(System.in);
            
            String firstName, lastName, yourCNP;
    
            System.out.println("Enter your first name: ");
            firstName = scan.nextLine();
            System.out.println("Enter your last name: ");
            lastName = scan.nextLine();
            System.out.println("Enter your CNP: ");
            yourCNP = scan.nextLine();
    
            firstName = firstName.toLowerCase();
            lastName = lastName.toUpperCase();
            
            String firstPart = String.valueOf(firstName.charAt(0) + firstName.charAt(1));
        
            String secondPart = String.valueOf(lastName.charAt(lastName.length() - 2) + lastName.charAt(lastName.length() - 1));
    
            String password = firstPart + secondPart;
    
            System.out.println("Your password is: " + password);
    
            scan.close();
    
        }
    }
  • 1
    Welcome to Stack Overflow! This is a good opportunity for you to start familiarizing yourself with [using a debugger](https://stackoverflow.com/q/25385173/328193). When you step through the code in a debugger, which operation first produces an unexpected result? What were the values used in that operation? What was the result? What result was expected? Why? To learn more about this community and how we can help you, please start with the [tour] and read [ask] and its linked resources. – David Oct 18 '22 at 15:02

1 Answers1

1
String.valueOf(firstName.charAt(0) + firstName.charAt(1))

does something very different to what you expect. It first adds the two characters numerically based on their ASCII value: 'a' + 'a' = 97 + 97 = 194. The valueOf then simply converts that to a String: "194".

Rather than doing that you should use substring or use a trick to force string concatenation rather than integer addition:

"" + firstName.charAt(0) + firstName.charAt(1)

Identical logic for the secondPart obviously.

luk2302
  • 55,258
  • 23
  • 97
  • 137