Taking a user input string to form an array

198 Views Asked by At

I am trying to create an array that uses a user input string to form the base for the array. It's supposed to be an encryption program that takes the string the user enters and puts it in an array at the index 0, all the way down the column. For example, if I typed in car, the array would look like array[0][0] c, [1][0] a, [2][0] r. After the encryption, whatever car turns into would go into the second row, but for the life of me I can't even figure out how to create the first array.

So far my file looks like this:

public class Csci1301_hw3 
{   //Start of class
  
  public static void main(String[] args)
  
  {  //Start of Main Method
    String userinput;
    
    Scanner scan = new Scanner(System.in);
    System.out.println("Please enter a sentence you would like to encrypt.");
    userinput = scan.nextLine();
    
    char current;
    int arraylength = userinput.length();
    
    char[][] outputarray = new char [arraylength][];
    
    for (int index=0; index < arraylength; index++);
    {
      if (current.charAt(0) < userinput.charAt(0))
      current = userinput.charAt(0);
      outputarray[0][0] = current;
      current++;
    }

String userinput;

Scanner scan = new Scanner(System.in);
System.out.println("Please enter a sentence you would like to encrypt.");
userinput = scan.nextLine();

char current;
int arraylength = userinput.length();

char[][] outputarray = new char [arraylength][];

for (int index=0; index < arraylength; index++);
{
  if (current.charAt(0) < userinput.charAt(0))
  current = userinput.charAt(0);
  outputarray[0][0] = current;
  current++;
}

This is my first coding class so I am very new to this, but even after rewatching lectures, reading my textbook, or even going over my professor's examples, I am unable to figure this out. The closest I got was it would just print out null for the entire array no matter what I typed.

1

There are 1 best solutions below

5
On

I think there are a couple of things you might want to check, first your current variable,you should assign a value to it before using it in an if statement. second, I think you might want to consider using the index variable inside the if statement like:

userinput.charAt(index);

and in other places too. Because you want to go over all the chars in a string. the last thing I wasn't sure about is why incrementing the current variable?

update:

    String userInput;
    
    Scanner stdin = new Scanner(System.in);
    System.out.println("Please enter a sentence you would like to encrypt.");
    userInput = stdin.nextLine();
    
    int arraylength = userInput.length();
    
    char[][] outPutArray = new char [arraylength][2];
    
    for (int i = 0; i < arraylength; i++)
    {
        outPutArray[i][1] = userInput.charAt(i);
    }
    for (int i = 0; i< outPutArray.length; i++)
        System.out.print(outPutArray[i][1]);