I am writing a program that will give the Initials of the name(String) user gives as input.
I want to use the Space function while writing the name as the basis of the algorithm.
For eg:
<Firstname><space><Lastname>
taking the char once in a for loop and checking if there is a space in between, if there is it will print the charecter that was just before.
Can someone tell me how to implement this?
I'm trying this but getting one error.
Any help is dearly appreaciated..
P.S- i am new to java and finding it a lot intresting. Sorry if there is a big blunder in the coding
public class Initials {
public static void main(String[] args) {
String name = new String();
System.out.println("Enter your name: ");
Scanner input = new Scanner(System.in);
name = input.nextLine();
System.out.println("You entered : " + name);
String temp = new String(name.toUpperCase());
System.out.println(temp);
char c = name.charAt(0);
System.out.println(c);
for (int i = 1; i < name.length(); i++) {
char c = name.charAt(i);
if (c == '') {
System.out.println(name.charAt(i - 1));
}
}
}
}
EDIT:
Ok Finally got it. The algorithm is a lot fuzzy but its working and will try to do it next time with Substring..
for (int i = 1; i < temp.length(); i++) {
char c1 = temp.charAt(i);
if (c1 == ' ') {
System.out.print(temp.charAt(i + 1));
System.out.print(".");
}
}
Thanks a lot guys :)
This works for me
public static void main(String[] args) {
Pattern p = Pattern.compile("((^| )[A-Za-z])");
Matcher m = p.matcher("Some Persons Name");
String initials = "";
while (m.find()) {
initials += m.group().trim();
}
System.out.println(initials.toUpperCase());
}
Output:
run:
SPN
BUILD SUCCESSFUL (total time: 0 seconds)
Simply use a regex:
keep only characters that are following a whitespace
remove all remaining whitespace and finally
make it upper case:
" Foo Bar moo ".replaceAll("([^\\s])[^\\s]+", "$1").replaceAll("\\s", "").toUpperCase();
=> FBM
I will do something like this:
Remember, you only need the inicial characters
public staticvoid main (String[] args){
String name;
System.out.println("Enter your complete name");
Scanner input = new Scanner(System.in);
name = input.nextLine();
System.out.println("Your name is: "+name);
name=" "+name;
//spacebar before string starts to check the initials
String ini;
// we use ini to return the output
for (int i=0; i<name.length(); i++){
// sorry about the 3x&&, dont remember the use of trim, but you
// can check " your name complete" if " y"==true y is what you want
if (name.charAt(i)==" " && i+1 < name.length() && name.charAt(i+1)!=" "){
//if i+1==name.length() you will have an indexboundofexception
//add the initials
ini+=name.charAt(i+1);
}
}
//after getting "ync" => return "YNC"
return ini.toUpperCase();
}
If you care about performance (will run this method many times), the extra charAt(i+1) isn't needed and is relatively costly.
Also, it'll break on texts with double spaces, and will crash on names that end with a space.
This is a safer and faster version:
public String getInitials(String name) {
StringBuilder initials = new StringBuilder();
boolean addNext = true;
if (name != null) {
for (int i = 0; i < name.length(); i++) {
char c = name.charAt(i);
if (c == ' ' || c == '-' || c == '.') {
addNext = true;
} else if (addNext) {
initials.append(c);
addNext = false;
}
}
}
return initials.toString();
}
public String getInitials() {
String initials="";
String[] parts = getFullName().split(" ");
char initial;
for (int i=0; i<parts.length; i++){
initial=parts[i].charAt(0);
initials+=initial;
}
return(initials.toUpperCase());
}
Related
My code checks if a certain number of user inputted string have any repeated characters. For example, if I input the strings "google" "paper" and "water", the code returns "paper" and "water"; because "google" has two Os.
I have the code part down, but when printing, a space appears after the very last string that is output and I can't figure out how to get rid of it.
import java.util.Scanner;
import java.util.*;
class words{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number or words: ");
String[] words = new String[sc.nextInt()];
System.out.print("Enter the strings: ");
boolean truth = false;
for (int i = 0; i < words.length; i++) {
words[i] = sc.next();
}
for(int i=0;i<words.length;i++){
int j;
for(j=1;j<words[i].length();j++) {
if(words[i].charAt(j) == words[i].charAt(j-1)){
break;
}
}
if(j==words[i].length()){
truth = true;
System.out.print(words[i]+" ");
}
}
if(!truth){
System.out.println("NONE");
}
}
}
Functions Make Logic Readable
Move the logic to check for repeating characters into a function; I would take advantage of String.toCharArray() and the shorter array syntax. Like,
private static boolean repeatedChars(String s) {
if (s == null) {
return false;
}
char[] chars = s.toCharArray();
for (int i = 0; i < chars.length - 1; i++) {
if (chars[i] == chars[i + 1]) {
return true;
}
}
return false;
}
Then, you can use a lambda to filter your words based on them not having repeated characters and collect with Collectors.joining(CharSequence) like
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number or words: ");
String[] words = new String[sc.nextInt()];
System.out.print("Enter the strings: ");
for (int i = 0; i < words.length; i++) {
words[i] = sc.next();
}
System.out.println(Arrays.stream(words).filter(s -> !repeatedChars(s))
.collect(Collectors.joining(" ")));
And, if you need to display the NONE message you might re-use the Predicate<String> like
Predicate<String> pred = s -> !repeatedChars(s);
if (Arrays.stream(words).anyMatch(pred)) {
System.out.println(Arrays.stream(words).filter(pred).collect(Collectors.joining(" ")));
} else {
System.out.println("NONE");
}
There is an easy workaround for your problem. Instead of printing every word immediately if it does not have any continuous repetition, add it to a String variable with space at the end so that each word is separated by a space. After you run through your loop, you check if your flag is false and print NONE if it is false. If it is true, however, print the result string where you added everything with a .trim() at the end.
for (int i = 0; i < words.length; i++) {
words[i] = sc.next();
}
String result = ""; /*This is the string that holds all the strings that you need to print.*/
for(int i=0;i<words.length;i++){
int j;
for(j=1;j<words[i].length();j++) {
if(words[i].charAt(j) == words[i].charAt(j-1)){
break;
}
}
if(j==words[i].length()){
truth = true;
result = result + (words[i]+" ");
}
}
if(!truth){
System.out.println("NONE");
}
else{
System.out.println(result.trim()); /*The trim function removes any redundant space in the beginning and the end of the string.*/
}
Of-course doing it this way will waste a lot of Heap Memory but I guess this is for a small learning project. However, do look into StringBuilder on how to use it to avoid creating a lot of memory in the Heap!
It's hard to explain but I'm trying to create a program that only capitalizes the letter of every word that ends with a period, question mark, or exclamation point. I have managed to receive a result when inputting any of the marks but only when it is entered the second time. In other words I have to hit enter twice to get a result and I'm not sure why. I am still working on it on my own but I'm stuck at this problem.
import java.util.*;
public class SentenceCapitalizer
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.print("Input a sentence: ");
String line = keyboard.nextLine();
String wrong = keyboard.nextLine();
String[] check = {".!?"};
String upper_case_line="";
Scanner lineScan = new Scanner(line);
for (String sent : check)
{
if (sent.startsWith(wrong))
{
System.out.println("cant use .?!");
}
else
{
/* if (line.startsWith(" "))//if starts with space
System.out.println("good");
else
System.out.println("bad");
*/
//if (int i = 0; i < line.length; i++)
//{char c = line.chartAt(i);
while(lineScan.hasNext())
{
String word = lineScan.next();
upper_case_line += Character.toUpperCase(word.charAt(0)) +
word.substring(1) + " ";
}
System.out.println(upper_case_line.trim());
}
}
}
}
Solution
Hey just a quick solution for your question. Converts the string to character array and then checks the character array for '.!?' if it finds the value then it will make the next letter a capital!
public class SentenceCapitalizer {
public static void main(String[] args) {
//Scanner, Variable to hold ouput
Scanner keyboard = new Scanner(System.in);
System.out.print("Input a sentence: ");
String line = keyboard.nextLine();
//Char array, boolean to check for capital
char [] lineChars = line.toCharArray();
boolean needCapital = false;
//String to hold output
String output = "";
//Check for period in line
for (int i = 0; i < lineChars.length; i++) {
//Make sure first char is upper case
if (i == 0) {
lineChars[i] = Character.toUpperCase(lineChars[i]);
}
//Check for uppercase if char is not space
if (needCapital && Character.isLetter(lineChars[i])) {
lineChars[i] = Character.toUpperCase(lineChars[i]);
needCapital = false;
}
if (lineChars[i] == '.' || lineChars[i] == '?' || lineChars[i] == '!') {
needCapital = true;
}
//Add character to string
output += lineChars[i];
}
//Output string
System.out.println (output);
}
}
Following code basically replaces characters in a string with reverse characters in ABC..
Eg. if user inputs- AbC
Then result would be ZyX
My Problem is, if the input contains a space then it breaks the code and does not continue the execution.
import java.util.*;
public class HelloWorld{
int[] capitals = new int[26];
int[] smalls = new int[26];
public static void main(String []args){
HelloWorld rs=new HelloWorld();
rs.Initialize();
rs.Encode();
}
public void Encode()
{
Scanner reader = new Scanner(System.in);
System.out.println("Enter string: ");
String input = reader.next();
//System.out.println("User entered: " + input);
String newString="";
int pos=0;
for (int in = 0; in < input.length(); in++)
{
if(input.charAt(in) == ' ')
{
newString += " ";
}
else
{
if((int)input.charAt(in) >= 65 && (int)input.charAt(in) <= 90)
{
for(int i = 0; i< 26; i++) {
if((int)input.charAt(in) == capitals[i]) {
newString += (char)capitals[25-i];
}
}
}
else if((int)input.charAt(in)>=97 && (int)input.charAt(in) <= 122)
{
for(int i = 0; i< 26; i++) {
if((int)input.charAt(in) == smalls[i]) {
newString += (char)smalls[25-i];
}
}
}
else
{
if(input.charAt(in) == ' ')
newString += " ";
else
newString += input.charAt(in);
}
}
pos = 0;
}
System.out.println(newString);
}
public void Initialize()
{
int pos=0;
for (int i=65;i<=90;i++)
{
capitals[pos] = i;
smalls[pos]= i + 32;
pos++;
}
}
}
What wrong am I doing?
Calling Scanner.next()
Finds and returns the next complete token from this scanner.
Normally, a Scanner's token is delineated by the space character. From that same page:
The default whitespace delimiter used by a scanner is as recognized by Character.isWhitespace.
So when you call Scanner.next(), it's only reading up until the first space and, since you never read from it again, the rest of the input is discarded when the program ends.
If you want everything the user enters, use nextLine instead.
According to the Javadoc
next()
Finds and returns the next complete token from this scanner.
The space is a delimter, so the next token is always the first part of the string before the space character.
You can set up the delimter pattern as explained here:
http://docs.oracle.com/javase/7/docs/api/index.html
Given question is:
A string can contain only a, b or c. There cannot be 2 consecutive same character. First and last character cannot be same. Now given a string with ‘a’, ‘b’, ‘c’ or ‘?’. We need to find the string replacing ‘?’ that satisfy the above conditions. For multiple answer display lexicographically smallest string. For no answer possible display “Not Possible”.
import java.util.*;
class Replace {
public static void main(String args[]) {
char[] arr = { 'a', 'b', 'c' };
char Pre, Suc;
Scanner in = new Scanner(System.in);
String str = new String();
String str2 = new String();
System.out.println("Enter the String");
while (in.hasNextLine()) {
str = in.nextLine();
}
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == '?') {
Pre = str.charAt(i - 1);
Suc = str.charAt(i + 1);
for (int j = 0; j < 3; i++) {
while (arr[j] != Pre && arr[j] != Suc) {
str2 = str.substring(0, i) + arr[j]
+ str.substring(i + 1, (str.length() - 1));
}
}
}
}
System.out.println(str2);
}
}
The code is compiling without any errors. I still have to add a couple of things to the code as per question but I was trying to check if the code was correct so far but I am not getting any Output. Any tips/suggestions to improve the code is welcome.
The code Pre = str.charAt(i-1); and Suc = str.charAt(i+1); is problematic when "?" is the first/ last letter. It will cause then a java.lang.StringIndexOutOfBoundsException
At present you are not leaving the while-loop used for reading the input, hence System.out.println(str2); is never reached.
The problem is the program gets stuck in your while(in.hasNextLine()) { str = in.nextLine(); } loop. There is no exit condition. hasNextLine will block until a new line is entered. As per the Javadoc:
This method may block while waiting for input.
You need a condition to break the first while loop. When the user insert the input string he press enter, so the Scanner get the second input as an empty string. You could check the empty string and exit from the while loop.
import java.util.*;
class Replace
{
public static void main(String[] args)
{
char[] arr = {'a','b','c'};
char Pre,Suc;
Scanner in = new Scanner(System.in);
String str = new String();
String str2 = new String();
System.out.println("Enter the String");
while(in.hasNextLine())
{
if(str.isEmpty()) break;
str = in.nextLine();
}
for(int i=0;i<str.length();i++)
{
if(str.charAt(i)=='?')
{
Pre = str.charAt(i-1);
Suc = str.charAt(i+1);
for(int j=0;j<3;i++)
{
while(arr[j]!=Pre && arr[j]!=Suc)
{
str2 = str.substring(0,i)+arr[j]+str.substring(i+1,(str.length()-1));
}
}
}
}
System.out.println(str2);
}
}
I am new to java and I have been trying to solve a problem which I feel might have a simpler answer than my code.The problem was to print the initials of a user input name of any length along with the full surname.But this has to be done without any String.split() or arrays.I tried getting the user to input his name one word at a time, but is there any there a possible way to get the whole name at once and do as required.
My code is as follows:
import java.io.*;
public class Initials {
public static void main(String[]args)throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the number of words your name contains");
int n=Integer.parseInt(br.readLine());
String str="";
for(int x=1;x<=n-1;x++){
System.out.println("Enter your name's word number:"+" "+x);
String s=br.readLine();
String st=s.toUpperCase();
char ch=st.charAt(0);
str=str+ch+".";
}
System.out.println("Enter your surname");
String sur=br.readLine();
str=str+" "+sur.toUpperCase();
System.out.println(str);
}
}
Use a regular expression (namely (?<=\w)\w+(?=\s)):
String name = "John Paul Jones"; // read this from the user
System.out.println(name.replaceAll("(?<=\\w)\\w+(?=\\s)", "."));
J. P. Jones
No split(), no arrays :)
A little explanation: We essentially want to replace all letters of each word that is followed by a whitespace character except the first letter, with a . character. To match such words, we use (?<=\w)\w+(?=\s):
(?<=\w) is a positive lookbehind; it checks that a word-character exists at the start of the match but does not include it in the match itself. We have this component because we don't want to match the first character of each name, but rather all but the first (except for the last name, which we'll deal with shortly).
\w+ matches any continuous string of word characters; we use this to match the rest of the name.
(?=\s) is a positive lookahead; it checks that our match is followed by a whitespace character, but does not include it in the match itself. We include this component because we don't want to replace anything on the last name, which should not be followed by a whitespace character and hence should not match the regular expression.
Another way around---
import java.util.Scanner;
//a class that will print your output
class Initial {
public void Initials() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter Full name:");
String name = sc.nextLine();
int l = name.length();
int pos = 0;
for (int i = l - 1; i >= 0; i--) {
char ch = name.charAt(i);
if (ch == ' ') {
pos = i; //getting the last space before Surname
break;
}
}
System.out.print("The initials are: ");
System.out.print(name.charAt(0) + ".");//prints first name initial
// with dot
for (int x = 1; x < pos; x++) //finds midname initial
{
char ch = name.charAt(x);
if (ch == ' ') {
System.out.print(name.charAt(x + 1) + ".");
}
}
for (int i = pos; i < l; i++) { //for printing Surname
System.out.print(name.charAt(i));
}
}
}
public class Str {
public static void main(String[] args) {
Initial i = new Initial();
i.Initials();
}
}
//This code will work for any no. of words in the name
class Surnam {
public static void main(String name) {
name = " " + name;
int l=name.length(), p=0, m=0, r=0;
char y;
String word=" ", words=" ";
for(int i = 0; i = 0; i--) {
y=name.charAt(i);
if(y==' ') {
r=name.lastIndexOf(y); //extracting the last space of the string
word=name.substring(i,l); //extracting the surname
words=name.replace(word," "); //removing the surname break;
}
}
for (int i = 0; i <= r - 1; i++) {
char x=words.charAt(i);
if (x == ' ') {
System.out.print(words.charAt(i + 1) + "."); //Printing all initials before the surname with a dot
}
}
for (int i = l - 1; i >= 0; i--) {
char x=name.charAt(i);
if(x==' ') {
m=i;
name=name.substring(m,l); //extracting the surname
name=name.trim(); //removing all the spaces before the surname
System.out.print(name);
break;
}
}
}
}