Click here to Skip to main content
15,884,388 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hello, how do I Input an integer (n), then output the first n characters of the phrase

for example, the input is 1 (option number), Hussain Omer (String name), 9 (index)
the output should be Hussain O (see how the first letters are kept and the nth letter is given afterward)

this is my code:

Java
import java.util.Scanner;
        public class Phrases{
        public static void main (String[]args){
        Scanner keyboard = new Scanner(System.in);
            int option = Integer.parseInt(keyboard.nextLine());
            String phrase = keyboard.nextLine();
                if (option == 1){
                    int x = keyboard.nextInt();
                        for (int y = 0; y < phrase.length(); y++){
                            char n = phrase.charAt(y);
                                if (y < phrase.length()-y) 
                                    System.out.print(n);
                                if (y == x - 1) 
                                    System.out.print(n);
                        }
                }


What I have tried:

The above code is what I tried
Posted
Updated 21-Apr-20 2:21am
v3
Comments
Patrice T 20-Apr-20 18:53pm    
What is the problem with this code ?
Maciej Los 21-Apr-20 2:30am    
I don't get you...
Why to force doors wide open? Take a look here: Substring in Java - javatpoint[^]
public class TestSubstring{
       public static void main(String args[]){
         String s="SachinTendulkar";
         System.out.println(s.substring(6));//Tendulkar
         System.out.println(s.substring(0,6));//Sachin
       }
      }
CHill60 21-Apr-20 6:49am    
That's a solution right there! ;-)
Maciej Los 21-Apr-20 8:24am    
You persuaded me to post solution ;)
Thank you, Caroline.

1 solution

Why to force doors wide open?

Take a look here: Substring in Java - javatpoint[^]
Java
public class TestSubstring{
       public static void main(String args[]){
         String s="SachinTendulkar";
         System.out.println(s.substring(6));//Tendulkar
         System.out.println(s.substring(0,6));//Sachin
       }
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900