Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Create a program that gets a number from a user. This number should be from 1 to

ID: 3672886 • Letter: C

Question

Create a program that gets a number from a user. This number should be from 1 to 26. Then have the user input a phrase, with this phrase you want to add the number they entered and print out the new phrase.

Example 1:

User Input: 5

User Input                                                       Expected output

A                                                                                    F

B                                                                                    G

C                                                                                    H

Example 2:

User Input: 3

User Input                                                       Expected output

A                                                                      D

B                                                                      E

C                                                                     F

Example 3:

User Input: 2

User Input: hello

Expected output: jgnnq

Explanation / Answer


import java.util.Scanner;
public class AddToPhrase {

public static void main(String[] args) {
System.out.print("Enter a number: ");
int n = getIntInRange(1, 26);
System.out.print("Enter a phrase: ");
String phrase = getString();
String newPhrase = "";
for (int i = 0; i < phrase.length(); i++) {
char ch = phrase.charAt(i);
if ((ch >= 'a' && ch <= 'z')) {
int newCh = (int) ch + n;
if (newCh > 'z') {
newCh = newCh - 'z'+'a'-1;

}
ch = (char) newCh;
} else if (ch >= 'A' && ch <= 'Z') {
int newCh = (int) ch + n;
if (newCh > 'Z') {
newCh = newCh - 'Z'+'A'-1;
}
ch = (char) newCh;
}

newPhrase = newPhrase + ch;
}
  
System.out.println(newPhrase);
}

public static String getString() {
Scanner input = new Scanner(System.in);
return input.nextLine();
}

  
public static int getIntInRange(int low, int high) {
int num = 0;
do {
num = getInt();
if (num < low || num > high) {
System.out.println("Enter number between " + low + " and " + high);
}
} while (num < low || num > high);
return num;
}

public static int getInt() {
Scanner input = new Scanner(System.in);
int num = -1;
boolean good;
do {
good = true;
try {
num = input.nextInt();
} catch (Exception e) {
good = false;
input = new Scanner(System.in);
System.out.println("Enter numeric value: ");
}
} while (!good);
return num;
}
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote