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);
}
}
Related
I want to use only charAt() and toUpperCase() function and capitalize the first letter of each word in a sentence.
Like make the letter capital, that is just after the space.
I tried with this following code.
import java.util.Scanner;
class firstscap
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("enter a sentence");
String s=sc.nextLine();
for(int i=0;i<s.length();i++)
{
char c=s.charAt(i);
if(Character.isSpaceChar(c))
{
char ch=s.charAt(++i);
ch=ch.toUpperCase();
}
}
System.out.println(s);
}
}
Several problems here.
s.charAt(n) gives you the n-th character of the String, not a pointer to the n-th character of the String. Changing that character does nothing to the String.
Also Strings are not mutable, which means you have no way to change them.
You can start build a new String from parts of the old String plus the Chars you have made uppercase.
You are capitalizing the characters but not storing them anywhere. I recommend you append all the characters to a StringBuilder*.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String s = sc.nextLine().trim(); // Input & omit leading/trailing whitespaces
StringBuilder sb = new StringBuilder();
// Append the first character, capitalized
if (s.length() >= 1) {
sb.append(Character.toUpperCase(s.charAt(0)));
}
// Start with character at index 1
for (int i = 1; i < s.length(); i++) {
char c = s.charAt(i);
if (Character.isSpaceChar(c)) {
sb.append(c).append(Character.toUpperCase(s.charAt(++i)));
} else {
sb.append(c);
}
}
s = sb.toString();
System.out.println(s);
}
}
A sample run:
Enter a sentence: hello world how are you?
Hello World How Are You?
* You can use String instead of StringBuilder but I recommend you use StringBuilder instead of String for such a case because repeated string concatenation in a loop creates additional as many instances of String as the number of concatenation. Check this discussion to learn more about it.
Strings are immutable, you can't modify them.
Consider building a new String for the result e.g by using StringBuilder.
In the following example, a boolean flag is used to know if the last character was a space .
Also we check if the current character is a letter before putting it to upper case, otherwise it makes no sense.
This will also prevent possible crashes if the line ends with a space (since index charAt(i+1) would crash):
public static void main(final String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("enter a sentence");
String s = sc.nextLine();
boolean wasSpace = false;
StringBuilder resultBuilder = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
Character c = s.charAt(i);
if (wasSpace && Character.isLetter(c)) {
resultBuilder.append(Character.toUpperCase(c));
} else {
resultBuilder.append(c);
}
wasSpace = Character.isSpaceChar(c);
}
System.out.println(resultBuilder.toString());
}
Note :
If you also want the first letter of the whole sentence to be capitalized, just initialize wasSpace to true .
import java.util.Scanner;
public class A {
public static void main(String args[]) {
Scanner obj = new Scanner(System.in);
System.out.println("Enter the string: ");
String a1 = (obj.nextLine()).trim();
String s1 = "";
char c2;
char arr[] = a1.toCharArray();
for (int i = 0; i <= a1.length() - 1; i++) {
if (Character.isSpaceChar(arr[i]) == true) {
++i;
c2 = Character.toUpperCase(a1.charAt(i));
s1 = s1 + " " + c2;
} else {
if (i == 0) {
c2 = Character.toUpperCase(a1.charAt(i));
s1 = s1 + "" + c2;
} else {
s1 = s1 + arr[i];
}
}
}
System.out.println(s1);
}
}
i am writing a program that must scramble a word. First I read in the word backwards using .reverse. Then I turned the string into a charArray.I am suppose to create a for loop to figure out if the First letter is "A" and if it is then i have to see if the next letter is not an "A". if its not then i am suppose to swap the two letters. If any of the two letters have a;ready been swapped than they cannot be swapped again.
Some examples are
Input: “TAN” Output: “ATN”
Input: “ALACTRIC” Output:“AALCTRIC”
Input: "Fork" Output:"Fork"
Here is my code so far: i cannot figure out what to put in the for loop. Thank you!
import java.util.Scanner;
public class scrambleWordRetry {
public static void main(String[] args)
{
}
public static String scramble( Random random, String inputString)
{
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a word to scramble.");
inputString = scan.nextLine();
char a[] = inputString.toCharArray();
for( int i=0 ; i<a.length-1 ; i++ )
{
}
return inputString;
}
}
I hope this code is useful for you
Scanner x = new Scanner(System.in);
String str = x.next();
System.out.println("Before Swapping" + str);
str = scramble(str);
System.out.println("After Swapping " + str);
}
public static String scramble(String inputString) {
char s[] = inputString.toCharArray();
for (int i = 1; i < s.length; i++) {
if (s[i] == 'A' || s[i] == 'a') {
char temp = s[i - 1];
s[i - 1] = s[i];
s[i] = temp;
}
}
return new String(s);
}
then if you input 'ALACTRIC' the output will be 'AALCTRIC',
'Tan = aTn',
'fork = fork'.
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
I have been trying to write a Java program which converts the first letter of every word of a string into a capital letter. Right now it looks like this:
package strings;
import java.util.Scanner;
public class small_cap {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the sentence");
String st = sc.next();
String str = " " + st;
int j = 0; char chr = ' ';
for (int i = 0; i < str.length(); i++){
j = i + 1;
chr = str.charAt(j);
if (chr == ' '){
char a = Character.toUpperCase(str.charAt(j));
str = str.replace(str.charAt(j), a);
}
else{
char a = Character.toLowerCase(str.charAt(j));
str = str.replace(str.charAt(j), a);
}
}
System.out.println(str);
}
}
Unfortunately I keep on getting the error:
java.lang.StringIndexOutOfBoundsException: String index out of range: 4
at java.lang.String.charAt(String.java:658)
at small_cap.main(small_cap.java:19)
I don't really see any fault in the code. Can someone please point out where I am going wrong?
You were using Scanner.next() rather then Scanner.nextLine() which will read the whole sentence rather then single word.
You are adding extra space in String. Don't know the big reason behind that. It can be done without it.
Let say the Input is : "abc def" which will become " abc def" after adding extra space. Length of string will become : 7
Now for loop will iterate from 0 to 6. But on i = 6 it will try to alter the element on 7th position (since you are doing j=i+1) which will cause string index out of range error.
You are using String.Replace which will replace all matching characters irrespective of their position.
import java.util.Scanner;
public class small_cap {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the sentence");
String st = sc.nextLine();
String str = " " + st;
int j = 0; char chr = ' ';
for (int i = 0; i < str.length()-1; i++){
j = i+1;
chr = str.charAt(i);
if (chr == ' '){
char a = Character.toUpperCase(str.charAt(j));
str = str.substring(0,j)+a+str.substring(j+1);
}
else{
char a = Character.toLowerCase(str.charAt(j));
str = str.substring(0,j)+a+str.substring(j+1);
}
}
System.out.println(str);
}
}
for (int i = 0; i < str.length(); i++){
j = i + 1;
When i reaches the last valid index length - 1, j will be equal to length, which is out of bounds.
I don't really see the point of the j variable to begin with - did you mean to use i somewhere else inside the loop as well, or should you just make your loop start from 1? Or did you perhaps mean to check the previous character by doing j = i - 1; (in that case make sure you don't read before index 0)
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());
}