Need help with school work...

Posts 1–5 of 5 · Page 1 of 1
Need help with school work...
Write a Java program to read in a line of text from keyboard. Then, act as follows (modifying the string each time):
If the user enters “n” shift all letters in the string forward 1 (A -> B, B -> C, etc.) and print the result.
If the user enters “p” shift all letters in the string backward 1 (A -> Z, B -> A, etc.) and print the result.
If the user enters anything else, exit the program.
I don't understand any of this, plz help me...
Do your work yourself. Use
import java.util.Scanner;
public class R{
public static void main(String args[]){
Scanner lineReader = new Scanner(System.in);
System.out.println("Enter any string");
String a = lineReader.nextLine();
System.out.println("Enter any integer");
int i = lineReader.nextInt();
}}
the code above is for accepting user inputs.

as for shifting the letters, use an array to store the letters and shift them with for loop.

here is for shifting to right
Code:
String letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
		char[] letterArray = letters.toCharArray(); //saves each letter to an array
		char[] shifted = new char[letters.length()]; //will store the new shifted letters
		
		for(int i = 0; i < letters.length(); i++){
			//shift right
			if( i != (letters.length()-1) )
				shifted[i] = letterArray[i+1];
			else shifted[i] = letterArray[0];
		}
		System.out.println( String.valueOf(shifted) );
Haven't programmed Java for a few years, but from what I remember char type have numeric value.
try
Code:
import java.util.Scanner;
public class MPGH{
public static Scanner reader = new Scanner(System.in);
     public static void main(String []args){
         System.out.println("enter a char");
         char c = reader.next().CharAt(0);
         while(c<'A'||c>'Z'&&c<'a'||c>'z')
           {
               System.out.println("wrong input, please enter a letter between a and z");
               c = reader.next().CharAt(0);
           }
         if(c>='A'&&c<='Z')
           c+=('a'-'A');                   
         if(c=='z')
           c='a';
         else
           c++;
         System.out.println(c);
     }
}
Quote Originally Posted by dkofek View Post
Haven't programmed Java for a few years, but from what I remember char type have numeric value.
try
Code:
import java.util.Scanner;
public class MPGH{
public static Scanner reader = new Scanner(System.in);
public static void main(String []args){
System.out.println("enter a char");
char c = reader.next().CharAt(0);
while(c<'A'||c>'Z'&&c<'a'||c>'z')
{
System.out.println("wrong input, please enter a letter between a and z");
c = reader.next().CharAt(0);
}
if(c>='A'&&c<='Z')
c+=('a'-'A');
if(c=='z')
c='a';
else
c++;
System.out.println(c);
}
}
this thread has been dead for years,look at the latest post
Posts 1–5 of 5 · Page 1 of 1

Post a Reply

Similar Threads

Tags for this Thread

None

Need help?