moving the characters in a text string a specified number of positions - java

I am new in programming and I am trying to write a program that moves the characters in a text string a specified number of positions.
The program must include a method whose inputs will be a text string (type String) and the number of positions (type int). The output will be a string with characters shifted.
For example, moving 4 positions:
rabbit eats a carrot
it eats a carrotrabb
Now I have this partial code. I can erase first characters but I don't know how to put them to the end of this text. How can i make it?
public static void main(String[] args) {
System.out.println("enter the text: ");
Scanner cti = new Scanner(System.in);
String a = cti.nextLine();
System.out.println("enter number of positions= ");
int b = cti.nextInt();
char firstLetter = a.charAt(0);
b--;
a = a.substring(b);
String m = a + firstLetter ;
System.out.println("now it is "+ m);
}

If you use regex, it's just one line:
return str.replaceAll("^(.{" + n + "})(.*)", "$2$1");

import java.util.*;
public class JavaApplication5 {
public static void main(String[] args) {
System.out.println("enter the text: ");
Scanner cti = new Scanner(System.in);
String a = cti.nextLine();
System.out.println("enter number of positions= ");
int b = cti.nextInt();
String firstPart = a.substring(0,b); // line 1
b--;
a = a.substring(b);
String m = a + firstPart ; // line 2
System.out.println("now it is "+ m);
}
}
See the changes above in statement marked with comment line 1 and line 2.
In line 1, we are getting the first part of string and in line 2, adding at the end of second string part.

public String foo(String s, int n) {
String s2 = s.substring(0, n);
s = s.substring(n) + s2;
return s;
}
you can put a few validations on this, like null string or n is less than s.length() etc.

It is better to use modulus operator to calculate number of shifts. When initial number of shift is more than string length. Check this :
public String shift(String string,int n){
int nshift = string.length() < n ? n%string.length() : n ;
String a = string.substring(0,nshift);
return string.substring(nshift) + a ;
}

One more version. All the work is essentially done in 1 line here:
String result = new StringBuilder(a).delete(0, b).append(a.substring(0,b)).toString();
Anyway, the full code is:
import java.util.*;
public class ShiftLetters {
public static void main(String[] args) {
System.out.print("enter the text: ");
Scanner cti = new Scanner(System.in);
String a = cti.nextLine();
System.out.print("Enter number of positions: ");
int b = cti.nextInt();
String result = new StringBuilder(a).delete(0, b).append(a.substring(0,b)).toString();
System.out.println(result);
}
}
Also, you might want to be more accurate with your indentation style to improve readability.

Related

How can I get my output to be separated by commas based on user input from scanner?

I have a class which takes keyboard input, how could I go about making it so that it can take multiple double and char inputs on one line e.g. 1 2 a a a to then get the output:
"1","2","a","a","a" by splitting it into separate strings? this is what I've done so far:
public class MyInputInfo implements Comparable <MyInputInfo> {
public static double numeric;
public static char symbol;
public MyInputInfo(double numeric, char symbol) {
this.numeric = numeric;
this.symbol = symbol;
}
public static char getSymbol() {
int asciiValue = 97;
for (int i = asciiValue; i <= 122; i++) {
String convertedChar = Character.toString ((char) i);
System.out.println (convertedChar);
}
return symbol;
}
#Override
public int compareTo(MyInputInfo o) {
if (this.numeric < o.numeric) {
return 1;
} else if (this.getSymbol( ) < o.getSymbol ( )) {
return -1;
} else {
return 0;
}
}
#Override
public String toString() {
return "Numeric " + numeric + " Symbol " + symbol;
}
}
the class im working on right now
import java.util.*;
public class MyKeyboardInput {
public static void main(String[] args) {
Scanner s = new Scanner (System.in);
MyInputInfo.numeric = s.nextDouble();
MyInputInfo.symbol = s.next ( ).charAt (0);
System.out.println (MyInputInfo.numeric+ "," + MyInputInfo.symbol);
}
}
I'm new to java so apologies for coming off as slow. All help is appreciated!
There are two options:
Obtain numbers and chars in predictable order
Obtain numbers and chars in random order
Obtain numbers and chars in predictable order
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number of iterations: ");
int count = scanner.nextInt();
StringBuilder buffer = new StringBuilder();
for (int i = 0; i < count; i++) {
System.out.print("\nEnter a floating point number: ");
buffer.append(scanner.nextDouble() + " ");
System.out.print("\nEnter a character: ");
buffer.append(scanner.next().charAt(0) + " ");
}
scanner.close();
String output = buffer.toString().trim().replaceAll(" ", ", ");
System.out.println(output);
}
If you enter 1 a 2 b 3 c 4 d 5 e, the output will look like this
1.0, a, 2.0, b, 3.0, c, 4.0, d, 5.0, e
It's really that simple. The key is to use StringBuilder to "stage" the input and then convert all of the individual inputs into a single String output. To make it easier to remove the last comma, I just separated the entries by spaces, trimmed the string to remove the last space, and then prepended the remaining spaces with a comma.
Obtain numbers and chars in random order
This solution is similar, but in this case, just capture the input as a String and then figure out if the input is numeric or not. If it is not numeric, then it is a character.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number of iterations: ");
int count = scanner.nextInt();
StringBuilder buffer = new StringBuilder();
for (int i = 0; i < count; i++) {
System.out.print("\nEnter a number or character: ");
String s = scanner.next();
try {
Double num = Double.parseDouble(s);
buffer.append(num + " ");
} catch (NumberFormatException nfe) {
buffer.append(s.charAt(0) + " ");
}
}
scanner.close();
String output = buffer.toString().trim().replaceAll(" ", ", ");
System.out.println(output);
}
Caveats
You need to figure out what to do when something like "character" is provided as input. As you can see in the code, the code captures only charAt(0). This might or might not be correct for your use. But, this is typically how it is portrayed on the web how to get character from Scanner in Java.
Also, there is no error handling on the first solution if the input is not a number. You could try to prompt again if the character entered is not a number. Likewise, when prompted to enter a character, what happens if the input is a number? You will need to tweak the code to do what you want. With the second approach, you don't have to worry about this.

Trying to write code that calculates the average length of words in a sentence

The code needs to have a method averageLength with the parameter String s. The method needs to return, as a double value, the average length of the words in s. Assuming s consists of only words separated by single blanks, without any leading or trailing blanks. I have a code below that finds the average length of words but it doesn't have the method averageLength:
import java.util.Scanner;
class main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Please type in your sentence, then press enter: ");
String words = sc.nextLine();
int count = 0;
double sum = 0;
double average = 0;
sc = new Scanner(words);
while (sc.hasNext()) {
String userInput = sc.next();
double charNum = userInput.length();
sum = charNum + sum;
count++;
if (count > 0) {
average = sum / count;
}
}
System.out.println("Average word length = " + average);
}
}
First, declare a method that returns a double and accepts a parameter of String
private static double returnAverageLength(String sentence){
With the help of the split() method, we split the sentence into words
String [] words = sentence.split(" ");
With a for loop we count all characters of the sentence
for(int i=0;i<words.length;i++){
countCharacters+= words[i].length();
}
And we return the average result
return countCharacters / words.length;
Full code
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Write sentence");
String s = scanner.nextLine();
double average = returnAverageLength(s);
System.out.println("AVERAGE IS " + average);
}
private static double returnAverageLength(String sentence){
String [] words = sentence.split(" ");
double countCharacters = 0;
for(int i=0;i<words.length;i++){
countCharacters+= words[i].length();
}
return countCharacters / words.length;
}
}
OUTPUT
Write sentence
Hello From Stackoverflow
AVERAGE IS 7.33
Since Java 8 you can use DoubleStream#average method for this purpose:
public static double averageLength(String words) {
return Arrays
// split a string into an array of
// words by spaces, returns Stream<String>
.stream(words.split(" "))
// take a word's length, returns DoubleStream
.mapToDouble(String::length)
// returns OptionalDouble
.average()
// if a value is not present, returns 0.0
.orElse(0.0D);
}
public static void main(String[] args) {
String words = "Not all questions benefit from including code " +
"but if your problem is with code you've written you " +
"should include some But don't just copy in your entire " +
"program Not only is this likely to get you in trouble " +
"if you're posting your employer's code it likely includes " +
"a lot of irrelevant details that readers will need to " +
"ignore when trying to reproduce the problem";
System.out.println(averageLength(words)); // 4.671875
}
See also: Sort semantic versions in a given array as a string

How do I return the second instance of a substring in Java?

I'm making a function that returns the second occurrence of a character the user inputs. The problem is that it's not printing anything. I remember hearing something about using a nested for loop for it but I don't know. Here's the program; the function I'm having problems with is the last one.
import javax.swing.JOptionPane;
public class IntroToWHILELoops
{
public static void main(String[] args)
{
//Thiis section tests the first method
String myString = GetAndStoreInput();
System.out.println(myString);
//This section tests the second method
System.out.println("Enter a character to search for --> ");
String searchChar = System.console().readLine();
int position = SecondCharPosition(myString,searchChar);
System.out.println("The second position of " +searchChar +" is " +position);
}
//This method keeps getting input from the user until a "X" or "x" is entered
//It then stores the input in a string.
public static String GetAndStoreInput()
{
String input;
String sentence = "";
input = JOptionPane.showInputDialog("Enter something (press x to stop)");
while(!input.equals("x") && !input.equals("X") ){
System.out.println(input);
sentence = sentence + input;
input = JOptionPane.showInputDialog("Enter something else (press x to stop)");
}
return sentence;
}
//Given a string, this method returns the position of the second occurrence of a given character.
//If the character occurs less than 2 times it returns -1.
public static int SecondCharPosition(String str, String Charr)
{
String sentence = str;
int count = 1;
int position = 0;
int i = 0;
while(count < 10){
if(sentence.substring(i,i+1).equals(Charr)){
count++;
}
if(count == 2){
position = i;
}
}
return position;
}
}
#Tyler - Hope this helps you.
import java.util.Scanner;
import javax.swing.*;
class Scratch {
public static void main(String[] args) {
// Thiis section tests the first method
String myString = GetAndStoreInput();
System.out.println(myString);
// This section tests the second method
System.out.println("Enter a character to search for --> ");
final Scanner in = new Scanner(System.in);
String searchChar = in.next();
int position = SecondCharPosition(myString, searchChar);
System.out.println("The second position of " + searchChar + " is " + position);
}
// This method keeps getting input from the user until a "X" or "x" is entered
// It then stores the input in a string.
public static String GetAndStoreInput() {
String input;
String sentence = "";
input = JOptionPane.showInputDialog("Enter something (press x to stop)");
while (!input.equals("x") && !input.equals("X")) {
System.out.println(input);
sentence = sentence + input;
input = JOptionPane.showInputDialog("Enter something else (press x to stop)");
}
return sentence;
}
// Given a string, this method returns the position of the second occurrence of a given character.
// If the character occurs less than 2 times it returns -1.
public static int SecondCharPosition(String str, String Charr) {
int count = 0;
int position = 0;
for (int i = 0; i < str.length(); i++) {
if (String.valueOf(str.charAt(i)).equals(Charr))
count++;
if (count == 2) {
position = i;
break;
}
}
return position;
}
}

Taking a string and modifying it with an integer

Being fairly new to Java, I have an exercise where the user will be asked to enter a word. Next, they will be asked to enter a number. Then the program will modify the word by taking the number and implementing it to change the string. For example, if the word "Hello" was entered, and the integer entered was the number "3", it will take each character in the string (Hello) and move them each 3 letters down in the alphabet, which would then make the output word "Khoor". I recently learned about method replacing (.replace) in the same chapter as this question but it seems like having to clarify every single letter with a replace would be too lengthy. This is what I have so far.
public class Lab03Exercise7 {
public static void main(String [] args)
{
// Prompt user to enter a string
System.out.print("Enter a word");
// Import Java scanner
Scanner input = new Scanner( System.in );
int numberinput;
String wordinput = input.nextLine();
// Prompt user to enter an integer
System.out.print( "Enter a number");
numberinput = input.nextInt();
}
}
You can do it as follows:
import java.io.IOException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
Scanner input = new Scanner(System.in);
System.out.print("Enter a word: ");
String wordInput = input.nextLine();
System.out.print("Enter a number: ");
int numberInput = input.nextInt();
StringBuilder updatedStr = new StringBuilder();
for (char c : wordInput.toCharArray()) {
updatedStr.append((char) (c + numberInput));
}
System.out.println("Updated string: " + updatedStr);
}
}
Explanation: Break the word into an array of characters and iterate through the array. During iteration, add the number to the character and append the updated character to a StringBuilder object. Note that you can add an integer to a char value but you need to cast it before appending to the StringBuilder object.
You can use something like this:
final StringBuilder sb = new StringBuilder();
for(int i = 0 ; i < wordinput.length(); i++) {
final char currentChar = wordinput.charAt(i);
sb.append((char)(currentChar + numberinput));
}
System.out.println(sb.toString());
So basically, we're going character by character and adding the shift that you've got from the user. here I don't handle the edge cases - where we need to rotate after z / Z
In general, this algorithm called Caesar Cipher and you can get some more info about it here: https://www.geeksforgeeks.org/caesar-cipher-in-cryptography/
As highlighted by #maio290' comment you have to use the ascii table to solve your problem, differentiating between lowercase characters and uppercase characters. Starting from the assumption we have a 26 chars alphabet (a-z and A-Z) in the example we are translating the chars of three positions so we will have for example:
"Hello" will be translated to "Khoor"
"zed" will be translated to "chg"
In the case of z char it will be translated to c, I'm posting an example explaining the situation:
public class Caesar {
public static String encode(String original, int k) {
char[] arr = original.toCharArray();
StringBuilder encoded = new StringBuilder();
for (char ch : arr) {
char initialCharacter = Character.isLowerCase(ch) ? 'a' : 'A';
int dec = ((int)(ch - initialCharacter) + k) % 26;
encoded.append((char)(dec + initialCharacter));
}
return encoded.toString();
}
public static void main(String[] args) {
System.out.println(encode("Hello", 3)); //<-- will print Khoor
System.out.println(encode("zed", 3)); //<-- will print chg
}
}
You have to transform your char to int and after retransform it to char , differentiating between lowercase chars and uppercase chars and assuming an alphabet of 26 chars , for further details see the ascii table.
I believe this is gonna help to solve your problem. Just do not forget to handle it after 122(letter z). You can check the ASCII table here (https://theasciicode.com.ar/)
public static void main(String[] args) throws Exception {
String word = "word";
char[] arr = word.toCharArray();
int count=0;
for (char c : arr) {
//!!Handle if the sum is bigger than 122 (letter z), you need to do some easy math.
arr[count] = (char) (((int)c) + 3);
count++;
}
String newWord = new String(arr);
}

Accept 5 names and print the longest name?

I want to the longest name for 5 given names. I think I should use compareTo() method or length()?
Output must be like this :
enter 5 names :
Joey
Mark
Catherine
Zachery
Foster
Longest name is Catherine.
What method should I use and how? This is my code so far:
Scanner x = new Scanner(System.in);
String name = ""
System.out.print("Enter 5 names");
name = x.nextLine();
name2 = x.nextLine();
name3 = x.nextLine();
name4 = x.nextLine();
name5 = x.nextLine();
if(name.compareTo(name2)>0) //is this method right?
.compareTo tells you which string comes first in lexicographic order (<0 if s1 < s2, 0 if s1==s2, >0 if s1>s2)
String s1 = "abc";
String s2 = "def";
s1.compareTo(s2) < 0;
.length() returns the length of a string
s1.length()==3;
In your case, you need to compare based on length, so you need the latter. If it's only 5 names, you can take the first and assume it's the longest, and then read the others one by one by keeping the "longest so far" saved and comparing them as they come. After all, you only care about the longest.
If you wanted them to be sorted by length, while still keeping them all, you'd need to store them in some sort of collection (list, array), then sort it based on length.
The problem is easy enough, so I won't provide directly the code, try to grok it yourself, you can do it :)
import java.util.Scanner;
public class LenghtyName {
public static void main(String[] args) {
Scanner x = new Scanner(System.in);
/*
Instead of declaring 5 different String variable
just use String array with size = 5
*/
String[] names = new String[5];
System.out.print("Enter 5 names :");
names[0] = x.nextLine();
names[1] = x.nextLine();
names[2] = x.nextLine();
names[4] = x.nextLine();
names[5] = x.nextLine();
//Assume lenthyName as empty String
String lengthyName = "";
/*
Iterate over String array using for-each loop
*/
for (String name : names) {
/*
-Check null to avoid NullPointerException
-Trim the left and right blank space in name by #trim()
-Compare current name length with lengthyName if greater
replace the lengthyName by current name.
*/
if (name != null && name.trim().length() > lengthyName.length()) {
lengthyName = name;
}
}
/*
Print length name
*/
System.out.println("Longest name is " + lengthyName);
}
}
What about this?
Scanner in = new Scanner(System.in);
// no need to have 5 all over the code.
// Define it once to avoid "magic nubmers"
int namesCount = 5;
// fun fact: shortest name is always "". We don't have to use null
String longestName = "";
System.out.print("Enter " + nameCount + " names:");
for (int i=0; i< nameCount; i++){
// store new name from user
String candidate = in.readLine();
// is this one longer than the current longest?
if (longestName.length() < candidate.length()){
// found a longer name
longestName = candidate;
}
}
System.out.println("Longest name is " + longestName);
This gives up storing the names, as it seems you only use the longest one anyway. It also generalizes the number of names to iterate, and most importantly the variable names are meaningful names.
Here's a solution that should work:
public class LongestWord {
public static String getLongestString(String[] array) {
int maxLength = 0;
String longestString = null;
for (String s : array) {
if (s.length() > maxLength) {
maxLength = s.length();
longestString = s;
}
}
return longestString;
}
public static void main(String[] args) {
String[] toppings = {"Cheeddddddddddse", "Pepperoni", "Black Olivesddd"};
String longestString = getLongestString(toppings);
System.out.format("longest string: '%s'\n", longestString);
}
}
An easy way would be a for loop to read 5 names and find the length for largest name. Using the for loop avoids the creation of 5 deterrent string variables.
If you want to use those names later you can go for String array.
public static void main(String[] args) throws IOException {
Scanner x = new Scanner(System.in);
String name = "";
String maxName = "";
int maxLength = 0;
System.out.println("enter 5 name :");
for (int i = 0; i < 5; i++) { // read 5 names
name = x.nextLine();
if (maxLength < name.length()) { // check longest name
maxLength = name.length();
maxName = name; // store in temp variable to show
}
}
System.out.println("Longest name is " + maxName); // print largest name
}
Output:
enter 5 name :
raj
sita
gita
mukherjee
rita
Longest name is mukherjee
Here's a solution that should work with any number of entries:
Scanner x = new Scanner(System.in);
String name = "", temp="";
while (x.hasNextLine()){
temp = x.nextLine();
if (temp.length() > name.length()) name = temp;
}
System.out.println("Longest is " + name);
You'll need to Ctrl + Z to end the inputStream on Windows
this is my code for comparing 3 input strings by their length:
public static void main(String[] args) {
String string1 , string2 , string3;
Scanner input = new Scanner(System.in);
System.out.println("Enter three string names to compare");
string1 = input.nextLine();
string2 = input.nextLine();
string3 = input.nextLine();
if (string1.length()>string2.length()) {
if (string1.length() > string3.length())
System.out.println("String 1 has the longest length , length = "+string1.length());
}
if (string2.length()>string1.length()){
if(string2.length()>string3.length())
System.out.println("String 2 has the longest length , length = "+string2.length());
}
if (string3.length()>string1.length()) {
if (string3.length() > string2.length())
System.out.println("String 3 has the longest length , length = " + string3.length());
}
}
//SIMPLE JAVA SOLUTION
class GFG
{
String longest(String names[], int n)
{
String res="";
for(int i=0;i<n;i++)
{
if(res.length()<names[i].length())
{
res=names[i];
}
}
return res;
}
}

Categories

Resources