Using charAt method, won't add them as an Int, and wont print as string. Will explain better

后端 未结 4 1250
旧时难觅i
旧时难觅i 2021-01-27 17:58

Alright, so here is my code:

import java.util.Scanner;

public class CarRental {

    public static String model;
    public static int letternum;
    public st         


        
相关标签:
4条回答
  • 2021-01-27 18:05
    public static String model;
    public static int letternum;
    public static String plate;
    public static String letter;
    public static int total;              
    public static String alphabet = "abcdefghijklmnopqrstuvwxyz";
    
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
    
        //System.out.println("Car Model:");
        //model = input.nextLine();
        System.out.println("License Plate: ");
        plate = input.nextLine();
    
        char one = plate.charAt(0);
        char two = plate.charAt(1);
        char three = plate.charAt(2);
        total = Integer.parseInt(one) + Integer.parseInt(two) + Integer.parseInt(three);
        letternum = total % 24;
    
        char letter = alphabet.charAt(letternum);
    
        System.out.println("" + letter + total);
    
    }
    

    you forgot to cast it to integer

    0 讨论(0)
  • 2021-01-27 18:06

    Change these lines:

    int one = (int) plate.charAt(0);
    int two = (int) plate.charAt(1);
    int three = (int) plate.charAt(2);
    

    This will give you the actual ASCII values for the characters.

    If you want something else, you'll have to subtract a constant from each of the values, as jonhopkins illustrated in his comment.

    Subtract 64 to get A = 1, B = 2, etc.

    I see your problem.

    The algorithm is to take the ASCII values of the first 3 characters and add them to the number (the last 3 characters).

    Also, you have to divide by 6 to get the letters A - E. You're dividing by 24.

    0 讨论(0)
  • 2021-01-27 18:11

    You want to take the second part of the string (with the three numbers) and add it to your total. You can take that value with:

    Integer.parseInt(plate.split(" ")[1])

    0 讨论(0)
  • 2021-01-27 18:22

    If you add the 229 value that you to the 607 in the license plate, you get the 836 number you say you're supposed to get, so it looks like your total variable is right, but you just need to add it to the number from the input.

    The stuff everyone else is saying about shifting the ASCII values is for when you're determining the first character in the output.

    0 讨论(0)
提交回复
热议问题