Where did I go wrong with this cipher program? - java

I need to write a program that takes the first, middle, and last name of a person and encrypt it: each letter the user enters is shifted circularly by the selected key. For example, if the key is 1 and the original letter is ‘A’, then the encrypted letter will be ‘B’. If the key is 3 and the original letter is ‘b’, then the encrypted letter will be ‘e’. If the key is 3 and the original letter is ‘z’, then the encrypted letter will be ‘c’.
Here is my code:
import java.util.Scanner;
public class Cipher {
public static void main(String []main){
Scanner console = new Scanner(System.in);
System.out.print("Enter your first name: ");
String firstname = console.nextLine();
System.out.print("Enter your middle name: ");
String middlename = console.nextLine();
System.out.print("Enter your last name: ");
String lastname = console.nextLine();
System.out.print("enter the key ");
int N = console.nextInt();
String s = firstname + middlename + lastname;
System.out.print("your original name is "+ s);
String empty = "";
for( int i = 0; i<=s.length();i++){
if (s.charAt(i)!=' '){
System.out.print(empty ="" + s.charAt(i));
}
else{
System.out.print(empty +=s.charAt(i+N));
}
}
System.out.print("encrypted name is " + empty);
}
}
My problem seems to be in the loop, but I have no idea how to fix it.
What I am getting:
Enter your first name: a
Enter your middle name: b
Enter your last name: c
enter the key 2
your original name is abcaababcException in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 3
at java.lang.String.charAt(String.java:686)
at test1.test.main(test.java:19)
While what I should be getting for example is the following:
Enter your first name: a
Enter your middle name: b
Enter your last name: c
enter the key 2
your original name is abc
encrypted name is cde

Consider using this code instead of your last for-loop :
byte[] input = s.getBytes();
for (int i = 0; i < input.length; ++i) {
input[i]+= N;
}
String encrypted = new String(input);
System.out.print("encrypted name is " + encrypted);
Should be fine on ASCII symbol sets.

You cannot use this:
s.charAt(i+N)
Since it will access characters that are 'after' the string - you may use indices from 0 to s.length()

Related

How to collect names in a loop then use StringBuilder?

Have been up for hours trying to figure out how to add in these in a string array using user input and StringBuilder.
I have to in a loop collect names from user input (scanner).
when they enter a blank name stop looping. Then iterate over the attendee list to create the output string using StringBuilder.
only 1 name = Name .
2 names = Name 1 and name 2 . more then 2 names = name 1, name2, and name 3 . output should exactly match the way these are formatted with spaces, commas, and the "and".
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
StringBuilder sb = new StringBuilder();
sb.append("You have invited: ");
System.out.println("enter names.");
String attendee = keyboard.nextLine();
// receiving input
while (attendee != "") {
sb.append(attendee);
if (attendee == "") break;
}
System.out.println(sb);
for (int i = 0; i > sb.length(); i++) {
if (i == 0) {
keyboard.nextLine(); //consuming the <enter> from input above
sb.append(keyboard.nextLine());
i++;
} else if (i == 1) {
sb.append(keyboard.nextLine() + " and " + keyboard.nextLine());
System.out.println(sb);
} else if (i > 1) {
sb.append(keyboard.nextLine() + ", " + keyboard.nextLine() + ", and " + keyboard.nextLine());
System.out.println(sb);
}
}
}
There is a lot of errors in your code
you don't ask again in the while loop for a new value, so either you never get in (first empty string) or never get out (first not empty) also that isn't how you compare a string, that is an object, use .equals()
you may not call keyboard.nextLine() (getting input) in the loop where you build the output
names shouldn't be joined in the StringBuilder, then how would you build the output
So, make a nice loop that populates a list of String, then nicely concatenate the different parts to make the output
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
List<String> names = new ArrayList<>();
System.out.print("enter name: ");
String attendee = keyboard.nextLine();
while (!attendee.equals("")) {
names.add(attendee);
System.out.print("enter name: ");
attendee = keyboard.nextLine();
}
System.out.println(namesToString(names));
}
static String namesToString(List<String> names) {
List<String> firsts = names.subList(0, names.size() - 1);
String last = names.get(names.size() - 1);
if (names.size() == 1)
return "You have invited: " + last;
return "You have invited: " + String.join(", ", firsts) + " and " + last;
}
enter name: Patrick
enter name: Pierre
enter name: James
enter name: John
enter name:
You have invited: Patrick, Pierre, James and John
Full possibilities of outputs
System.out.println(namesToString(Arrays.asList("pierre")));
// You have invited: pierre
System.out.println(namesToString(Arrays.asList("pierre", "jean")));
// You have invited: pierre and jean
System.out.println(namesToString(Arrays.asList("pierre", "jean", "eude")));
// You have invited: pierre, jean and eude
System.out.println(namesToString(Arrays.asList("pierre", "jean", "eude", "john", "james")));
// You have invited: pierre, jean, eude, john and james

using first 2 letters of a first name and 4 letters of a last to create a username with a random number for example, Michael + Jackson= JackMi42

Good evening programmers, I am new to java and I am stuck on a coding question that is about using first 2 letters of a first name and 4 letters of a last to create a username with a random number for example, Michael + Jackson= JackMi42. If anyone can help me out I will really appreciate it. the application that I am using to do this is Eclipse IDE. Here is the code that I have created so far:
import java.util.Scanner;
public class FirstNameLastName {
/**In this step you put in a last name
*/
public static void main(String[] args) {
try (Scanner in = new Scanner(System.in)) {
System.out.println("Please enter your last name: ");
in.nextLine();
/**In this step you put in any first name
*/
System.out.println("Please enter your first name: ");
in.nextLine();
/**In this step you type in the four letters of the last name
*/
System.out.println("four letters of last name:");
String FourLetterOfLastName = in.nextLine();
/**In this step you type in the two letters of the first name
*/
System.out.println("two letters of first name:");
String TwoLetterOfFirstName = in.nextLine();
/**In this step you type in any number between 10 and 99
*/
System.out.println("random number between 10 and 99");
String randomnum = in.nextLine();
/**In this step you print out the four letter of last name +two letter of first name + a
* random number between 10 and 99.
* at then end it will print it out on the output section in the console section
*/
System.out.println(FourLetterOfLastName + TwoLetterOfFirstName + randomnum);
}
}
}
You can try this way:
import java.util.Scanner;
import java.util.concurrent.ThreadLocalRandom;
public class FirstNameLastName {
public static void main(String[] args) {
try (Scanner in = new Scanner(System.in)) {
System.out.println("Please enter your last name: ");
String lastName = in.nextLine();
System.out.println("Please enter your first name: ");
String firstName = in.nextLine();
String fourLetterOfLastName = lastName;
if(lastName.length() > 4) {
fourLetterOfLastName = lastName.substring(0, 4);
}
String twoLetterOfFirstName = firstName;
if(firstName.length() > 2) {
twoLetterOfFirstName = firstName.substring(0, 2);
}
String randomnum = String.valueOf(ThreadLocalRandom.current().nextInt(10, 100));
System.out.println(fourLetterOfLastName + twoLetterOfFirstName + randomnum);
}
}
}
Try looking into String.substring() method.
Example:
String fourLettersLastName = lastName.substring(0, 4);
// if lastName = Jackson, then fourLettersLastName = Jack
For the random number you can look at Math.random().
Example:
int randomNum = (int)(Math.random() * (max - min) + min);
// In your case, max = 99 and min = 10
// The (int) cast is needed because Math.random() returns a double
In the end you concatenate everything (using the '+' sign) and print out for the user. A tip in the future when playing with Strings in Java is to use StringBuilder.
Other thing I noticed is the variable named randomnum which is against Java naming conventions (and almost every programming language). The way is supposed to be named is using camelCase (in this case, randomNum). You should check this page for more info on this.

How can I loop console input for ONE variable with multiple answers to be printed?

For my homework problem, we enter number of students, then their names and numeric grades (0 - 100)
My problem is, I have to use a for loop for the number of students to enter their name and grade together. But if I do this I won't be able to separately print each name and grade.
I have a for loop that goes until the previously inputted number of students is reached, but this will not allow me to print all of the names and grades together at the end. The loop will ask for the students name and input, then the numeric grade and input. I cannot use arrays because we have not gotten to that point in our class so I will receive a 0 if I use them. I cannot use separate variables for each name and grade because the number of students is not a constant.
//loop input for all student names and their numeric grades
for(cntr = 0; cntr < numStudents; cntr++) {
System.out.print("Enter student name: ");
studentName = input.nextLine();
System.out.print("Enter " + studentName +"'s numeric grade: ");
numGrade = input.nextInt();
cleanUpStr = input.nextLine();
}
At the end I should be able to print each name followed by their grade.
Example:
Bob 50
bill 60
dill 90
Since you cannot use Array, List, or StringBuilder, you can simply append the typed in values to a String along with \n or a line terminator to move to the next line:
String names= "";
for(int cntr = 0; cntr < numStudents; cntr++) {
System.out.print("Enter student name: ");
studentName = input.nextLine();
System.out.print("Enter " + studentName +"'s numeric grade: ");
numGrade = input.nextInt();
cleanUpStr = input.nextLine();
names += studentName + " " + numGrade + "\n";
}
System.out.println(names);
Note I added a String names which appends studentName and numGrade each loop iteration.
Obviously there are better solutions if you were not constrained by the professor.
Example Run:
Enter student name: bob
Enter bob's numeric grade: 50
Enter student name: bill
Enter bill's numeric grade: 60
Enter student name: dill
Enter dill's numeric grade: 90
Enter student name: hill
Enter hill's numeric grade: 20
Enter student name: mill
Enter mill's numeric grade: 40
bob 50
bill 60
dill 90
hill 20
mill 40
You say that you can't use things you've not learned in class yet, which includes arrays, Lists, and other data types. So, logically, you have to think about other ways to collect the information such that you can print it at the end.
Since you're using Strings in your existing code, I will assume you have learned about Strings and are allowed to use them in your assignment. Since you print a String, then the solution would be to just keep collecting the student names and grades in a single stream as the user inputs it, and then, once you exit the for-loop, print it.
Now, the correct way to do this would be to use a StringBuilder. I personally never learned about StringBuilder in school so I think it unlikely it's on your list of things you are allowed to use, so this example will instead just concatenate (eg combine two strings).
First, you need to declare a String that will hold your output.
String output = "";
Notice it is initialized to an empty string, not null. This is because when you add two strings, if one is null then you'll get the word "null" randomly in your output.
The other important thing is that you have to declare this variable before the for-loop. Recall the scope of variables: anything you declare inside the for-loop is only available to you while you're inside of the for-loop; if you don't declare it outside of the loop, you won't be able to do concatenation at all.
Then in your for-loop, append the values to the string:
//loop input for all student names and their numeric grades
for(cntr = 0; cntr < numStudents; cntr++) {
studentName = input.nextLine();
// snip
numGrade = input.nextInt();
output += studentName + " " + numGrade + "\n";
}
(The \n is a newline, which will allow us to print each student's name and grade on a separate line.)
And then finally, outside of the for-loop, print the results:
System.out.println(output);
Now, for completeness' sake, the correct way of appending to a String within a loop is to use a StringBuilder:
StringBuilder sb = new StringBuilder();
for(cntr = 0; cntr < numStudents; cntr++) {
// snip
studentName = input.nextLine();
// snip
numGrade = input.nextInt();
sb.append(studentName).append(" ").append(String.valueOf(studentGrade)).append("\n");
// snip
}
System.out.println(sb.toString());
#Nexevis is correct. Here is a something that should be easy for a student to understand:
String studentsRecords = "";
int numStudents = 5;
int studentGrade;
String studentName;
for(int i = 0; i < numStudents; i++){
System.out.print("Enter student name: ");
studentName = input.nextLine();
studentsRecords = studentsRecords + "\n" + studentName;
System.out.print("Enter " + studentName +"'s numeric grade: ");
studentGrade = input.nextInt();
studentsRecords = studentsRecords + " " + studentGrade;
}
System.out.println(studentsRecords);
Use concatenation and the newline \n character

Java string inside string

Write a program that asks the user to enter two Strings, and prints the number of times that the second String appears within the first String. For example, if the first String is "banana" and the second is "an", the program prints 2.
Below is my code so far
public class Assignment4 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner answer = new Scanner(System.in);
//Prompt the user to enter a string
System.out.println("Enter a word:");
String input = answer.nextLine();
//Ask the user to enter a second String
//look at index method of string
System.out.println("Enter another word:");
String input2nd = answer.nextLine();
int counter = 0;
for(int i=0; i<input.length(); i++) {
if(input.charAt(i) == input2nd.charAt(0)) {
counter++;
}
}
System.out.println(input2nd + " appears " + counter + " times.");
When I type banana into first string, and second string is "an", the only thing come up is number 3, and it is for character a which appear 3 time, but not two as it suppose to only be 2 "an"
Consider this trick I learned years ago:
replace the searched word in the original word by emptychars...
get the diff between the length of both... searched chars and the original with replaced
divide that by the len of the searched word...
private static void searchString() {
Scanner answer = new Scanner(System.in);
// Prompt the user to enter a string
System.out.println("Enter a word:");
String input = answer.nextLine();
// Ask the user to enter a second String
// look at index method of string
System.out.println("Enter another word:");
String input2nd = answer.nextLine();
String a = input.replace(input2nd, "");
int counter = (input.length() - a.length()) / input2nd.length();
System.out.println(input2nd + " appears " + counter + " times.");
}
with the input banana and an will print 2

String index out of range error 7 [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
String index out of range: n
I'm writing a program to generate a username based off of a user's inputs (first, middle, and last names). I'm supposed to get the first character from each name(first, middle, and last) as well as the last character of the last name in order to generate a username. I've successfully wrote the program to generate the first character of each name, but when I tried to get my program to generate the last character of the last name I would get this error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 7
at java.lang.String.charAt(String.java:658)
at UsernameGenerator.main(UsernameGenerator.java:39)
Here is my code:
import java.util.Scanner;
/**
UsernameGenerator.java
Generates a username based on the users inputs.
#author: Evan Fravert
*/
public class UsernameGenerator {
/**
* Generates a username based on the users inputs.
*#param args command line argument
*/
public static void main(String[] args)
{ // abcde
String first;
String middle;
String last;
String password1;
String password2;
int randomNum;
randomNum = (int) (Math.random() * 1000) + 100;
Scanner userInput = new Scanner(System.in);
System.out.println("Please enter your first name:");
first = userInput.nextLine();
String firstLower = first.toLowerCase();
System.out.println("Please enter your middle name:");
middle = userInput.nextLine();
String middleLower = middle.toLowerCase();
System.out.println("Please enter your last name:");
last = userInput.nextLine();
int lastEnd = last.length();
String lastLower = last.toLowerCase();
System.out.println("Please enter your password:");
password1 = userInput.nextLine();
System.out.println("Please enter your password again:");
password2 = userInput.nextLine();
char firstLetter = firstLower.charAt(0);
char middleLetter = middleLower.charAt(0);
char lastLetter = lastLower.charAt(0);
char lastLast = lastLower.charAt(lastEnd);
if (first == null || first.length() <= 0) {
firstLetter = 'z';
}
else {
firstLetter = firstLower.charAt(0);
}
System.out.println("Your username is " + firstLetter + ""
+ middleLetter + "" + lastLetter + "" + "" + lastLast + "" + randomNum);
System.out.println("Your password is " + password1);
System.out.println("Welcome " + first + " " + middle + " " + last + "!");
}
}
Thanks in advance!
Java arrays are zero based, the last index is last.length() - 1
Try this:
char lastLast = lastLower.charAt(lastEnd-1);

Categories