0

Question is at bottom of code

import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.Scanner;

public class Encoder {

    public static void main(String[] args){

        try {
            //input scanner created
            Scanner sc = new Scanner(System.in);
            System.out.print("Enter the message you want to encode and hit enter: ");
            String text = sc.nextLine();
            // Encodes this String into a sequence of bytes using the named charset, storing the result into a new byte array.
            byte[] bytes = text.getBytes("US-ASCII");

             System.out.println("Your encoded message is: " + " " + Arrays.toString(bytes));


    } 
        catch (UnsupportedEncodingException e) {
            // catch block
            System.out.println("Wrong" + e);
        }

    } 

}

My output: Enter the message you want to encode and hit enter: Hello World! Your encoded message is: [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]

The Question: With the code that I have, is it possible to A) offset the values in the array (ex. offset[72] to [84]), and B) how would I do it.

andrewJames
  • 19,570
  • 8
  • 19
  • 51
Jaxle7
  • 1
  • `for (int i = 0; i < bytes.length; ++i) bytes[i] += 12;` –  Jun 18 '20 at 22:58
  • Thanks a ton, that worked almost perfectly. For some reason, I'm getting a negative value for the lowercase character "w" (-127). Everything else is comes out as it should. Any ideas? – Jaxle7 Jun 18 '20 at 23:35
  • For background: Take a look at the Java [primitive data types](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html) - especially `byte` "_It has a minimum value of -128 and a maximum value of 127 (inclusive)._". Also take a look at questions such as [this](https://stackoverflow.com/questions/17912640/byte-and-char-conversion-in-java), which discuss how to (and how not to) convert between `byte` and `char`. – andrewJames Jun 19 '20 at 13:51

0 Answers0