Taking a user input string to form an array - java

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.

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]);

Related

Having trouble with figuring out how to create a nested loop with arrays

I'm currently having trouble defining the nested loop and arrays for the current problem:
Write a program that reads an integer, a list of words, and a character. The integer signifies how many words are in the list. The output of the program is every word in the list that contains the character at least once. For coding simplicity, follow each output word by a comma, even the last one. Add a new line to the end of the last output. Assume at least one word in the list will contain the given character. Assume that the list of words will always contain fewer than 20 words.
This is what I have so far
import java.util.Scanner;
public class labProgram {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String[] userList = new String[20];
int numElements = scnr.nextInt();
char userChar = scnr.next().charAt(0);
int i;
for(i = 0; i < userList.length(); ++i) {
userList[i] = scnr.next();
}
}
}
What steps should I take to define and loop this problem?
You need to loop through each word by performing adding an inner for loop that iterates through each character in word[i]. Inside of this inner loop, you can check to see if the current character matches the target character that you want.
//loops through the list of words
for(int i = 0; i < userList.length; i++){
boolean letterExists = false;
// inner for loop will iterate through each character in wordlist[i]
for(int j = 0; j < userList[i].length; j++) {
char currentLetter = userList.charAt(j);
if(currentLetter == userChar)
letterExists = true;
}
// print if the user exists
if(letterExists)
System.out.println(userList[i]);
}
You can exchange the order of some instruction to make the array as long as you wish.
Here an example:
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int numElements = scnr.nextInt(); // ask the user the elements of the array
String[] userList = new String[numElements]; // create the array
char userChar = scnr.next().charAt(0); // ask the user for the char to search
// adding the strings to the array
for(int i = 0; i < userList.length; ++i) {
userList[i] = scnr.next();
}
// searching the char in the strings and printing the matched strings
System.out.println("Matched Strings: ");
for (int i=0; i < userList.length; i++)
for (int j=0; j < userList[i].length(); j++)
if (Character.compare(userList[i].charAt(j), userChar) == 0) {
System.out.print(userList[i] + ",");
continue;
}
}
}
Consider also to not use the instruction continue, you can use a new array to store the matched strings instead.

How to loop string in decrement order?

Write a program that takes a string input from the user and then outputs the first character, then the first two, then the first three, etc until it prints the entire word. After going down to one letter, print the opposite back up to the full word.
I've gotten the first part done.
Scanner word = new Scanner(System.in);
System.out.println("Enter a word.");
String thing = word.next();
String rest = "";
for(int i=0;i< thing.length();i++){
String w = thing.substring(i,i+1);
rest += w;
System.out.println(rest);
}
This is what it should look like.
C
Co
Com
Comp
Compu
Comput
Compute
Computer
Computer
Compute
Comput
Compu
Comp
Com
Co
C
Strings in Java are indexed starting from 0, so the last character is indexed at length-1.
To iterate from the last character down to the first, the for loop would be for(int i = thing.length () - 1; i >= 0; i--).
Alternatively, recursion would be a simpler solution considering you already obtained the strings that should be printed in reverse.
static void f (String str, int n) {
if (n > str.length ()) return;
String temp = str.substring (0, n); // obtain the string
System.out.println (temp); // print
f (str, n + 1); // go to next substring
System.out.println (temp); // print after returning from the last obtainable substring
}
The function can now be called via f(thing, n);
You can try to implement two arrays, in the first you must split the String entered from the Scanner and in the second you must store the generated aux variable in each iteration of the first array, To finish you must iterate the second array in reverse.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a word: ");
String word = sc.next();
String[] array = word.split("");
int length = array.length;
String[] auxArray = new String[length];
String aux = "";
for (int i = 0; i < length; i++) {
aux += array[i];
auxArray[i] = aux;
System.out.println(aux);
}
for (int i = length - 1; i >= 0; i--) {
System.out.println(auxArray[i]);
}
}

user input to a Char Array

I am trying to create a program that takes a user's answer for a test and puts it in a char array, and then compares it to an array with the answers.
I have a problem with input the user's Answers into the char array. I keep getting an EE saying that in.nextLine(); - there is no line found and it throws a no such element exception.
import java.util.Scanner;
public class driverExam {
public static void main(String[] args) {
System.out.println("Driver's Test. Input your answers for the following
10 Q's. ");
System.out.println();
char[] testAnswers = {'B','D','A','A','C','A','B','A','C','D'};
int uA =9;
String userInput;
for (int i =0; i<uA;i++) {
Scanner in = new Scanner(System.in);
System.out.print("Question #"+(i+1)+": ");
userInput = in.nextLine();
in.close();
int len = userInput.length();
char[] userAnswers = new char [len];
for(int x =0;x<len;x++) {
userAnswers[i] = userInput.toUpperCase().charAt(i);
}
System.out.println(userAnswers);
}
System.out.println("Your answers have been recorded.");
System.out.println();
}
}
Shouldn't userAnswers array be of size 10?
Your program has quite redundant and unnecessary steps, according to me. So I have modified it to meet your need.
There is no need to put the "Scanner in...." inside the loop.
This loop is full of mistakes. Not discouraging, just saying.
for (int i =0; i<uA;i++)
{
Scanner in = new Scanner(System.in);//scanner inside loop
System.out.print("Question #"+(i+1)+": ");
userInput = in.nextLine();
in.close();//already mentioned by someone in the comment
int len = userInput.length();
char[] userAnswers = new char [len];//no need to declare array inside loop
for(int x =0;x<len;x++)
{
userAnswers[i] = userInput.toUpperCase().charAt(i);
}
}
System.out.println(userAnswers);//this will not print the array,it will print
//something like [I#8428 ,[ denotes 1D array,I integer,and the rest of it has
//some meaning too
Now here is the code which will get the work done
char[] testAnswers = {'B','D','A','A','C','A','B','A','C','D'};
int uA =testAnswers.length;//to find the length of testAnswers array i.e. 10
char[] userAnswers = new char [uA];
char userInput;
int i;
Scanner in = new Scanner(System.in);
for (i =0; i<uA;i++)
{
System.out.print("Question #"+(i+1)+": ");
userInput = Character.toUpperCase(in.next().charAt(0));
}
for(i=0;i<ua;i++)
{
System.out.println(userAnswers[i]);
}
System.out.println("Data has been recorded");
I am not demeaning, just trying to help.

Java Linear Search of Array with Multiple Key Matches

Trying to implement a program that does the following:
-Program that can be re-run by user input (while loop)
-Allows user to input a desired array size, creates an array of that size,
uses a for loop to enter elements into the array, and enter a desired key
from which to do a linear search method
I want to modify the linear search method to return, as an array, the index values of all the instances where the arrayName[i] == key value; this is the part where I'm getting stuck.
For example, if as the user I input 4 as array size; 1, 2, 2, 3 as the elements; 2 as the desired key for the linear search, then it would print the array {1, 2} as the indices where the key matched the element value.
Here's my code so far:
import java.util.Scanner; //Imports Scanner from java.util package
public class LinearSearch2 {
public static void main (String[] args) {
//Creates Scanner object for user to input string whether to run program
Scanner input1 = new Scanner(System.in);
System.out.print("Run linear search on an array? ");
System.out.print("(Y = Yes; Type any other character to exit program): ");
String s = input1.next();
char runProgram = s.charAt(0);
/*While loop (this allows for re-running the program with a different
set of inputs in the same run depending on the string Scanner object
input...see while loop-continuation condition below)*/
while (runProgram == 'y' || runProgram == 'Y') {
//Creates another Scanner object for entering the array size as integer
Scanner input2 = new Scanner(System.in);
//Scans in user input of array size
System.out.print("Enter desired array size: ");
int arraySize = input2.nextInt();
//Creates array based on size input
double [] numberArray = new double[arraySize];
//Creates another Scanner object for entering the array numbers as doubles
Scanner input3 = new Scanner(System.in);
//Loop to read in input numbers into created array
for (int i = 0; i < numberArray.length; i++) {
System.out.print("Enter a number: ");
numberArray[i] = input3.nextDouble();
}
//Creates another Scanner object for entering the key as a doubles
Scanner input4 = new Scanner(System.in);
//Scans in user desired key
System.out.print("Enter desired key: ");
double arrayKey = input4.nextDouble();
//Invokes linear search method
int [] keyIndices = linearSearch(numberArray,arrayKey);
//Prints keyIndices array
for (int i = 0; i < keyIndices.length; i++) {
System.out.print(keyIndices[i] + " ");
}
//Requests if user would like to re-run the program
System.out.println("Do another linear search on an array? ");
System.out.print("(Y = Yes; Type any other character to exit program): ");
//Takes new result of string scanner object to determine if to run the program again or exit
String s2 = input1.next();
runProgram = s2.charAt(0);
}
}
//Revised linear search method
public static int [] linearSearch(double[] list, double key) {
int [] resultKeyIndices = new int[];
for (int i = 0; i < list.length; i++) {
if (key == list[i]){
return i;
}
}
return -1;
}
}
The problem is to allocate an array of the right size (number of matches). This solution uses a large array and resize it at the end:
public static int [] linearSearch(double[] list, double key) {
int[] indices = int[list.length];
int n = 0;
for (int i = 0; i < list.length; i++) {
if (key == list[i]){
îndices[n++] = i;
}
}
int[] result = new int[n];
for (int i = 0; i < n; ++i) {
result[i] = indices[i];
}
return result;
}

Sorting names entered by the user in alphabetical order according to the last name

I have completed most of the code by myself (with the help of a bit of Googling) but I have run into an unexpected problem. First-off, I have to sort a user entered list of names in aplhabetical order of their last names using selection sort. Here is my code:
import java.util.*;
class Name_Sort
{
public static void main (String args[])
{
Scanner in = new Scanner (System.in);
System.out.print ("Enter the number of names you wish to enter: ");
int n = in.nextInt();
String ar[] = new String [n];
for (int i = 0; i<ar.length; i++)
{
System.out.print("Please enter the name: ");
ar[i]= in.nextLine();
}
String temp;
for (int b = 0; b<n; b++)
{
for (int j=b+1; j<n; j++)
{
if ((compareLastNames(ar[b], ar[j]))>0)
{
temp = ar[b];
ar[b] = ar[j];
ar[j] = temp;
}
}
}
System.out.println ("The names sorted in alphabetical order are: ");
for (int a = 0; a<n; a++)
System.out.print (ar[a]+"\t");
}
private static int compareLastNames(String a, String b)
{
int index_a = a.lastIndexOf(" ");
String surname_a = a.substring(index_a);
int index_b = b.lastIndexOf(" ");
String surname_b = b.substring(index_b);
int lastNameCmp = surname_a.compareToIgnoreCase(surname_b);
return lastNameCmp;
}
}
The problem (I think) is arising when I'm taking the names from the user, specifically, this part:
Scanner in = new Scanner (System.in);
System.out.print ("Enter the number of names you wish to enter: ");
int n = in.nextInt();
String ar[] = new String [n]; //Array to store the names in.
for (int i = 0; i<ar.length; i++)
{
System.out.println("Please enter the name: ");
ar[i]= in.nextLine();
}
The output on the terminal window of BlueJ shows up as
Name_Sort.main({ });
Enter the number of names you wish to enter: 5
Please enter the name:
Please enter the name:
That is not what it's supposed to display. What could I be doing wrong? I've pondered over it for a while, but nothing comes to mind.
And, even if I do move forward and enter a few names despite the error above, I get another error in this part of my code here:
private static int compareLastNames(String a, String b)
{
int index_a = a.lastIndexOf(" ");
String surname_a = a.substring(index_a);// This is the line the compiler highlights.
int index_b = b.lastIndexOf(" ");
String surname_b = b.substring(index_b);
int lastNameCmp = surname_a.compareToIgnoreCase(surname_b);
return lastNameCmp;
}
the error is :
java.lang.StringIndexOutOfBoundsException: String index out of range: -1 (injava.lang.String)
Does this mean that the white-space character " " is not present? But why?
This is a screenshot of the terminal window:
http://imgur.com/l7yf7Xn
The thing is, if I just initialize the array with the names first (and not take any input from the user) the codes runs fine and produces the desired result. Any help please?
Also, since I know some people here are very particular about this, yes, this is a homework assignment, yes, I did do all of the code by myself, I googled on how to sort the names in alphabetical order as I couldn't exactly code out the original idea I had.
Which was comparing the ASCII values of each character of two surnames to see which should come first. Like: if((int) surname1.charAt(0)>(int) surname2.charAt(0)) then surname2 should come before surname1, else if they both have the same first character, take the second character and so on.
Thanks for taking the time to read this.
The problem is with the in.nextInt() command it only reads the int value. So when you continue reading with in.nextLine() you receive the "\n" Enter key. So to get around this you will have to add an extra in.nextLine() before going into the loop. Or, use another scanner.
int n = in.nextInt();
String ar[] = new String [n]; //Array to store the names in.
in.nextLine(); // < --- an extra next Line
for (int i = 0; i<ar.length; i++)
{
System.out.println("Please enter the name: ");
ar[i]= in.nextLine();
}

Categories