My program is supposed to gets a phrase from the user then returns to the user an encrypted code of their choice (either ROT13 or ATBASH) of the phrase they entered. My code compiles and everything and lets the user input the required stuff but when they enter the phrase to be encrypted, nothing happens.. like the new encrypted code doesnt show up, and i dont know what wrong with it!
Please help! Thank you!
import java.io.*;
public class J4_1_EncryptionVer4
{
public static void main (String [] args) throws IOException
{
BufferedReader myInput = new BufferedReader (new InputStreamReader (System.in));//BufferedReader reads user input
//String array letterA[] is initialized
String [][] letterA = new String [][]{
{"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"},
{"N","O","P","Q","R","S","T","U","V","W","X","Y","Z","A","B","C","D","E","F","G","H","I","J","K","L","M"},
{"Z","Y","X","W","V","U","T","S","R","Q","P","O","N","M","L","K","J","I","H","G","F","E","D","C","B","A"},
};
System.out.println ("Enter '1' for ROT13 or '2' for ATBASH");//asks user to choose method
String numA = myInput.readLine();//reads user input and assigns it to string
int num = Integer.parseInt (numA);//converts string to integer
int a = 0;//int a is declared
if (num == 1){//if user enters 1
a = 1;//set a to 1
}
if (num == 2) {//end if//if user enters 2
a = 2;//set a to 2
}//end if
System.out.println ( a);
System.out.println(num);
System.out.println ("Please enter a phrase: ");//asks user to enter phrase
String message = myInput.readLine();//reads user input and assigns it to string
int x = 0; //declares int var x
System.out.println ("Your Encrypted code is: ");//prints out scentence
while (x < message.length())//while loop will run while x is less that the phrase length
{
String text = message.toUpperCase();//converts user input to upper case
String letter = Character.toString(text.charAt(x));//extracts character from string and assigns it to another string letter
x++;//increments x by 1 each time
for(int i=0; i<letterA.length; i++)//for loop declares int i = 0, will run while i is less than the the length of the array letterA, and i will increment by 1 each time
{
if(letter.equals(letterA[a][i]))//if the letter is equal to letterA[i]
{
System.out.print (letterA[a][i]);//print out the corresponding letter
break;//breaks from loop
}//end if
else if (letter.equals(" "))//else id the letter is equal to a space
{
System.out.print(" ");//prints out space
break;//breaks from loop
}//end else if
}//end for loop
}//end while loop
}//end main
}//end class
This doesn't work because letterA.length is 3, so your for loop only runs through 3 iterations, instead of 26.
I think you should change your for loop to
for (int i= 0; i < letterA[0].length ; i++ ) {
if (letter.equals(letterA[0][i]) {
System.out.print(letterA[a][i]);
break;
}
else {
// .........,.......
}
}
First use the first array as basis. Compare the letters then if they are equal then get the index of that letter to be used in encrypting
I'm using a bloody phone ryt now so I didn't really compile your code
Related
I want to print a letter instead of the index position using the indexOf(); method.
The requirement is that: Inputs a second string from the user. Outputs the character after the first instance of the string in the phrase. If the string is not in the phrase, outputs a statement to that effect. For example, the input is 3, upside down, d. The output should be "e", I got part of it working where it inputs an integer rather than a string of that particular position. How would I output a string?
else if (option == 3){
int first = 0;
String letter = keyboard.next();
first = phrase.indexOf(letter,1);
if (first == -1){
System.out.print("'"+letter+"' is not in '"+phrase+"'");
}
else {
System.out.print(first + 1);
}
}
String.charAt(index)
You can access a single character, or a letter, by caling método charAt() from String class
Example
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String phrase = keyboard.nextLine();
char firstLetter = phrase.charAt(0);
System.out.println("First Letter : " + firstLetter);
}
So, running this code, assuming the input is StackOverFlow, the output will be S
In your code I think doing the follow will work:
Your Code
String letter = keyboard.next();
first = letter.charAt(0);
That might help!
Based on those comments
So, what you want is print the first letter based on a letter the user
has input? For example, for the word Keyboard, and user inputs letter
'a' the first letter might be 'R'. Is that it? – Guerino Rodella
Yes, I have to combine both the indexOf(): method and the charAt():
method – Hussain123
The idea is get next letter based on user input letter.
I'm not sure I wunderstood it, but this is my shot
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String phrase = "keyboard";
String userInput = keyboard.nextLine();
boolean notContainsInputValue = !phrase.contains(userInput);
if (notContainsInputValue) {
System.out.println("The input value doesn't exists");
return;
}
char firstLetter = userInput.charAt(0);
int desiredIndex = 0;
for (int i = 0; i < phrase.length(); i++) {
if (phrase.charAt(i) == firstLetter) {
desiredIndex = i;
break;
}
}
System.out.println("The index for your input letter is: " + desiredIndex);
System.out.println("Next letter based on input value is: " + phrase.charAt(desiredIndex + 1));
}
The Output
The index for your input letter is: 5
Next letter based on input value is: r
Hope that helps you.
I understand how to count the occurrences of specific characters in a string. What I am struggling is printing "The specific character is at location x, y, z". If I place the text within the loop that tests for location, the text is printed multiple times. I do not want that to happen.
There are other constraints as well. I must keep the program basic, and I am limited to using the charAt() and string.lenghth() functions. The program should only exit when the user enters "-1". When the user enters the string, the program should read through the characters, output the location of the specific characters, and then prompt the user to enter a new string. I am also struggling with allowing the user to enter a new string and running the loop again.
Here is the code I have so far
import java.util.Scanner;
public class GimmeAW {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the Line\nEntering -1 exits the program")
String aLine;
aLine = input.nextLine();
char one = aLine.charAt(0);
char two = aLine.charAt(1);
if (one == '-' && two == '1') {
System.out.println("System Exit");
System.exit(1);
}
for (int i = 0; i < aLine.length(); i++) {
if (aLine.charAt(i) == 'w' || aLine.charAt(i) == 't') {
int location = i;
System.out.print(" " + i);
}
}
}
To avoid printing the msg multiple times, just keep the msg outside of the counting loop and print it once for each character ...
char[] ch = {'w', 't'}; // characters to count
int l = aLine.length();
for(int i = 0; i < ch.length; i++) {
System.out.print("The character " + ch[i] + " is at locations ");
// searching
for(int j = 0; j < l; j++) {
if(aLine.charAt(j) == ch[i]) {
System.out.print(j + " ");
}
}
System.out.println();
}
And you can put all the code you want to repeat inside a do-while loop and run it until the user wants to.
String choice = "yes";
do {
// code
// want to repeat ??
choice = in.nextLine();
} while(choice.equals("yes"));
So, I am very new at coding but have a college assignment to create a Word Manipulator. I am supposed to get a string and an INT from the user and invert every Nth word, according to the int input.
I am following steps and am stuck with this error at line 38 (the start of my last FOR LOOP). The compiler is giving me an Not an Statement Error in this line but I cant see where I went wrong.
Could someone gimme a light, please?
ps: I am not allowed to use Token or inverse().
import java.util.Scanner;
public class assignment3 {
public static void main(String[] args) {
// BOTH INPUTS WERE TAKEN
Scanner input = new Scanner (System.in);
String stringInput;
int intInput;
System.out.println("Please enter a sentence");
stringInput = input.nextLine();
System.out.println("Please enter an integer from 1 to 10. \n We will invert every word in that position for you!");
intInput = input.nextInt();
int counter = 1;
// ALL CHARS NOW ARE LOWERCASE
String lowerCaseVersion = stringInput.toLowerCase();
// SPLIT THE STRING INTO ARRAY OF WORDS
String [] arrayOfWords = null;
String delimiter = " ";
arrayOfWords = lowerCaseVersion.split(delimiter);
for(int i=0; i< arrayOfWords.length; i++){
System.out.println(arrayOfWords[i]);
// THIS RETURNS AN ARRAY WITH ALL THE WORDS FROM THE INPUT
}
// IF THE INTEGER INPUT IS BIGGER THAN THE STRING.LENGTH, OUTPUT A MESSAGE
// THIS PART IS WORKING BUT I MIGHT WANT TO PUT IT IN A LOOP AND ASK FOR INPUT AGAIN
if (intInput > arrayOfWords.length){
System.out.println("There are not enough words in your sentence!");
}
// NOW I NEED TO REVERSE EVERY NTH WORD BASED ON THE USER INPUT
//THIS IS WHERE THE ERROR OCCURS
for(int i=(intInput-1); i<arrayOfWords.length; (i+intInput)){
char invertedWord[] = new char[arrayOfWords.length()];
for(int i=0; i < arrayOfWords.length();i++){
ch[i]=arrayOfWords.charAt(i);
}
for(int i=s.length()-1;i>=0;i--){
System.out.print(invertedWord[i]);
}
}
}
}
(i+intInput) isn't a statement. That's like saying 12. Perhaps you mean i=i+intInput or i+=intInput which assigns a value to a variable
well, for one thing, i dont see "s" (from s.length()) initiated anywhere in your code.
I am working on a program where user can input random numbers and when user give -1 the loop will break and the entered numbers will be displayed
Example:
Enter a Number: 32
Enter next Number: 1243
Enter next Number: 123
Enter next Number: 76
Enter next Number: -1
Thank You. You have entered 32, 1243, 123, 76
Now whatever number is entered it will be displayed in ascending order
----Ascending order -----
[32,76,123,1243]
Now i have completed the following but the to get exact result the user need to enter
->0032
->0076
->0123
->1243
Then i am getting the exact result
[0032, 0076, 0123, 1234]
Then only my sorting is working fine otherwise it is like
[ 123, 1243, 32, 72]
Now how to solve this ?
package Testx;
import java.util.Arrays;
import java.util.Scanner;
public class Test7Ctr{
public static void main(String[] args)
{
// TODO Auto-generated method stub
Scanner user = new Scanner(System.in);
String user_input = "";
String holdv="";
String holdvx="";
String ascend="";
//AsveNd(user_input);
try
{
int b =0;
do
{
System.out.print("Enter next number:");
user_input = user.nextLine();
int x= Integer.valueOf(user_input);
if (x != -1)
{
holdv=user_input;
holdvx+=holdv+",";
ascend+=holdv+" ";
b++;
}
else
{
System.out.println("THANK YOU FOR ENTERING= "+holdvx);
break;
}
}
while(b <= 100);
{
}
String[] numbers=ascend.split("\\s");
for(String numb:numbers)
{
int intarray[] = new int[numbers.length];
Arrays.sort(numbers);
//break;
}
System.out.println("---Ascending order---");
System.out.println(Arrays.toString(numbers));
}
catch(Exception e)
{
}
}
}
You are sorting strings rather than numbers. This makes your sort work in lexicographic order instead of plain ascending order.
So to fix your problem, simply add Integers and not Strings. You can even parse a String to an Integer using Integer.parseInt().
Also, there is no need to call sort every time you insert a new number, but just once in the end. That adds a lot of overhead to your process.
You can get the proper integer sorting with the following:
String[] numbers = ascend.split("\\s");
int intarray[] = new int[numbers.length];
int i = 0;
for (String numb : numbers)
{
// convert the String to an int
intarray[i++] = Integer.parseInt(numb);
}
Arrays.sort(intarray); // sort the int array, not the String array
System.out.println("---Ascending order---");
System.out.println(Arrays.toString(intarray));
Side Note:
Your do/while loop would be better written as:
int x = 0;
do
{
System.out.print("Enter next number:");
user_input = user.nextLine();
x = Integer.valueOf(user_input);
if (x != -1)
{
holdv = user_input;
holdvx += holdv + ",";
ascend += holdv + " ";
}
} while (x != -1);
System.out.println("THANK YOU FOR ENTERING= " + holdvx);
You don't need the int b
You don't need the else statement in the loop. Just have the loop terminate when x is -1.
Also, you had an empty block after the while (...); That is not doing anything. The while portion of a do/while loop has no body.
You are sorting the "Strings" and not the "numbers". Scan those inputs as number, put them to a dynamic list (and not a static sized array) and then sort the list of numbers (and not of string)
In my program below - I have 2 classes and PalindromeTester is supposed to refer to the method findPalindrome in Palindrome. However, what is happening is that the value passed to the findPalindrome method is always returning a Entered string is not a palindrome, even when I test Strings such as level or mom or dad or madam.
Could some suggest a improvement? i'm quite sure that i think its my findPalindrome method that isn't examining the string right. I think its the method but if anyone sees anything else feel free to suggest. It takes the second to last character and tries to rebuild it, then compares it to the original string.
import java.util.Scanner;//import scanner class
public class PalindromeTester//class
{
public static void main(String args[])//main method
{
Scanner in = new Scanner(System.in); //scanner object
String palindrome = new String(); //string to accept user input
String end = new String("q"); //string to determine user quitting
for (int a = 0; a >= 0; a++){ //enter loop
System.out.println();
System.out.println("Enter a string to check if it is a palindrome"); //ask for initial string
System.out.println();
System.out.println("Continue entering strings until you are done. When you are done, enter q to quit."); //remind user to enter q to quit
palindrome = in.nextLine();//take in string input
Palindrome original = new Palindrome(palindrome); //palindrome object and passed palindrome to the constructor...but no value yet...so?
original = original.findPalindrome(); //call findPalindrome to determine if palindrome is a palindrome
if (palindrome.equalsIgnoreCase(end)) //if palindrome is q and since end is q and if they are equal, a=-2.
a = -2; //when incrementing the max value if ++ will be -1. since -1 is not >= to 0 then for loop exits.
System.out.println("Thanks for trying this program");
}
}
}
_____________________________________________________________
public class Palindrome {
String myPalindrome;
String myReverse;
public Palindrome(){
myPalindrome = new String("");
myReverse = new String("");
}
public Palindrome(String palindrome){
myPalindrome = palindrome;
}
public String findPalindrome (){
int length = myPalindrome.length();
for ( int i = length - 1 ; i >= 0 ; i-- )
myReverse = myReverse + myPalindrome.charAt(i);
if (myPalindrome.equals(myReverse))
System.out.println("Entered string is a palindrome.");
else
System.out.println("Entered string is not a palindrome.");
return ("");
}
}
Your code fails to initialize myReverse when the string constructor is called. So it gets initialized to null and later appended with the palindrome string. You need to fix it.
Having said that the above code cannot even compile and have many fundamental issues.