how to append without using buffer or append method? - java

/*
* Compares user input and checks whether they are anagrams
*
*/
import java.util.Scanner;
public class Anagram
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter first sentence: ");
String s1 = sc.nextLine();
System.out.print("Enter second sentence: ");
String s2 = sc.nextLine();
s1.toLowerCase();
String new1 = "";
for( char ch = 'a'; ch <= 'z'; ch++){
int i;
for(i = 0; i <s1.length(); i++){
if(ch == s1.charAt(i)){
System.out.print(ch + " are the letters of " + s1 + " in order ");
break;
}
}
}
s2.toLowerCase();
String new2 = new String();
for( char ch2 = 'a'; ch2 <= 'z'; ch2++){
int i2;
for(i2 = 0; i2 <s2.length(); i2++){
if(ch2 == s2.charAt(i2)){
System.out.print(ch2 + " are the letters of " + s2 + " in order ");
break;
}
}
}
}
}
In reference to my question before to which this is the proper way of doing the homework everything works fine except im having trouble creating a new string and passing all the chars to the new string. However this has to be done without using stringbuffer or append() is that possible?

You can use + operator that concatenates strings. But I think it is not the purpose of homework. It seems that you are expected to create char array and then create string using this array.
But that's it, man. If it is a homework you have now enough tips. Do it yourself and welcome to Stackoverflow.

Related

How to resolve the following program with a for loop into producing an appropriate output?

The following Java program is supposed to manipulate a string input by the user in such a way that the user will decide which character needs to be replaced with another and just the last character from the string should be replaced. Example if the user enters the string "OYOVESTER" and decides to replace "O" with "L", the program should output the following result: "OYLVESTER" (notice that only the last "O" was replaced with "L")
NOTE: YOU CANNOT USE BREAK COMMAND TO STOP THE LOOP. IT IS PROHIBITED.
import java.util.Scanner;
public class StringFun {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the string to be manipulated");
String inString = keyboard.nextLine();
String outString = "";
//Replace Last
System.out.println("Enter the character to replace");
char oldCharF = keyboard.next().charAt(0);
System.out.println("Enter the new character");
char newCharF = keyboard.next().charAt(0);
int count = 0; // variable that tracks number of letter occurrences
for(int index = inString.length() - 1;index >= 0;index--) {
if(inString.charAt(index) == oldCharF && count < 1){
outString = newCharF + outString;
outString = outString + inString.substring(0,index);
count++;
}
if (count < 1) {
outString = outString + inString.charAt(index);
}
}
System.out.print("The new sentence is: "+outString);
}
}
I keep getting the following output which is incorrect:
Enter the string to be manipulated
OYOVESTER
Enter the character to replace
O
Enter the new character
L
The new sentence is: LRETSEVOY
There are many simpler ways to achieve your requirement but I hope you have to demonstrate this with loops (without breaks)
Then you can use some thing like this :
boolean skip = false;
for (int index = inString.length() - 1; index >= 0; index--) {
if (!skip && inString.charAt(index) == oldCharF) {
outString = newCharF + outString;
skip = true;
}
else {
outString = inString.charAt(index) + outString;
}
}
PS : Using String concatenation inside loops is not recommended since
every String concatenation copies the whole String, usually it is preferable to
replace it with explicit calls to StringBuilder.append() or StringBuffer.append()
No break command seems like a weird condition. You could just a boolean value, and other methods, to break the loop when you need. Why not do something like this?
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the string to be manipulated");
String word = keyboard.nextLine();
//Replace Last
System.out.println("Enter the character to replace");
char oldCharF = keyboard.next().charAt(0);
System.out.println("Enter the new character");
char newCharF = keyboard.next().charAt(0);
int index = word.lastIndexOf(oldCharF);
if(index > 1){
word = word.substring(0,index) + newCharF + word.substring(index+1);
}
System.out.println("The new sentence is: " + word);
}

java program to count the number of words that starts with capital letters

I want to write a program that count the number of words that starts with capital letters. It only count no. Of capital letter not word try this line
"Hi hOw are yOu"
According to my code output will be 3
But their is only 1 word that starts with capital letter that is 'Hi'...so how can I solve these problem..Please help me with this.
import java.util.*;
class Cap
{
public static void main(String m[])
{
Scanner in=new Scanner(System.in);
String s=new String();
System.out.println("Enter a line:");
s=in.nextLine();
char c;
int ct=0;
for(int i=0;i<s.length();i++)
{
c=s.charAt(i);
if(c>=65 && c<=90)
{
ct++;
}
}
System.out.println("total number of words start with capital letters are :"+ct);
}
}
You should better use scanner.next();, which returns the token up to white space in other way a word.Now, you can check the first character of String returned by next() is in uppercase or not.
For statement This is StackOverflow you will have three tokens, This, is and StackOverflow and you can use String.charAt(0) on this String.
Moreover, you can simply use Character.isUpperCase method to check whether character is in upper case or not.
import java.util.*;
public class program_6
{
public static void main(String[] args)
{
String s1;
Scanner scan = new Scanner(System.in);
System.out.println("Enter the string... ");
s1 = scan.nextLine();
int count=0,i=0,n;
n = s1.length();
System.out.println("Size of the string is... " + n );
if ( null == s1 || s1.isEmpty())
{
System.out.println("Text empty");
}
else
{
if( Character.isUpperCase(s1.charAt(0) ))
{
count++;
}
for (i=1 ; i<n ; i++)
{
if ( Character.isWhitespace(s1.charAt(i-1)) && Character.isUpperCase(s1.charAt(i) ) )
{
count++;
}
}
}
System.out.println("Number of the word wich starts with capital latter... " + count );
}
}
Currently you are counting all the capital letters that are entered.
What you want to do is split the line on space and check only for the first letter if it is capital.
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
String s;
System.out.println("Enter a line:");
s=in.nextLine();
int ct=0;
for(String str: s.split(" ")) {
if(str.charAt(0)>=65 && str.charAt(0)<=90)
{
ct++;
}
}
System.out.println("total number of words start with capital letters are :"+ct);
}
You are comparing each character.Instead you can add a space at the begining of the string and check each character after space if it is in uppercase.
Scanner in = new Scanner(System. in );
String s = new String();
System.out.println("Enter a line:");
s = " " + in .nextLine().trim();
char c;
int ct = 0;
for (int i = 1; i < s.length(); i++) {
c = s.charAt(i);
if (c >= 65 && c <= 90 && s.charAt(i - 1) == 32) {
ct++;
}
}
System.out.println("total number of words start with capital letters are :" + ct);
DEMO
or better use scanner.next() as said by TAsk
Try this:
Scanner in = new Scanner(System.in);
String s = new String();
System.out.println("Enter a line:");
s = in.nextLine();
char c;
int ct = 0;
for (int i = 0; i < s.length(); i++) {
c = s.charAt(i);
if (Character.isUpperCase(c)
&& (i == 0 || Character.isWhitespace(s.charAt(i - 1)))) {
ct++;
}
}
System.out
.println("total number of words start with capital letters are :"
+ ct);
First of all we check on the first position whether it is starts with capital letter or not and it is only for the string which starts with capital letter... If yes then the count will be incremented. Next condition( Which is used for string which start with blank space or any other string) will check that left position must have blank space to start new word and the character must be capital to increment the count variable...
import java.util.*;
public class program_6
{
public static void main(String[] args)
{
String s1;
Scanner scan = new Scanner(System.in);
System.out.println("Enter the string... ");
s1 = scan.nextLine();
int count=0,i=0,n;
n = s1.length();
System.out.println("Size of the string is... " + n );
if ( null == s1 || s1.isEmpty())
{
System.out.println("Text empty");
}
else
{
if( Character.isUpperCase(s1.charAt(0) ))
{
count++;
}
for (i=1 ; i<n ; i++)
{
if ( Character.isWhitespace(s1.charAt(i-1)) && Character.isUpperCase(s1.charAt(i) ) )
{
count++;
}
}
}
System.out.println("Number of the word wich starts with capital letter... " + count );
}
}

Print Words In String Backwards

So I'm having a bit of trouble with my Computer Science class. I need to write some code that will take a string and print it backwards in reverse word order. He told me to find an empty space, then print from there and then keep searching....and repeat this until the end of the string. I typed my code out and all it does it print the first word 3 times. I know this will probably seem obvious to you guys.
public class Backwords
/*
* Gets words from main and prints in reverse order
*/
public static String BackwardsString(String str)
{
String str1 = (" " + str);
String answer = (" ");
int lastpos = str1.length();
for(int currpos = str.length(); currpos >= 0; currpos--) //shazam
{
if (str1.charAt(currpos) == ' ')
{
for (int p = currpos+1; p <lastpos; p++) //majicks
answer = answer + str1.charAt(p);
lastpos = currpos;
System.out.println(answer);
}
}
return answer;
}
public static void main(String [] args)
{
System.out.println("Enter a string : ");
Scanner firststr = new Scanner(System.in); //gets string input
String str = firststr.next();
System.out.println(BackwardsString(str));
}
}
Set answer back to answer = "" before the second nested for loop
for(int currpos = str.length(); currpos >= 0; currpos--) //shazam
{
if (str1.charAt(currpos) == ' ')
{
answer = "";
for (int p = currpos+1; p <lastpos; p++) //majicks
answer = answer + str1.charAt(p);
lastpos = currpos;
System.out.println(answer);
}
}
You should use StringBuilder instead of String here since there can be lot of String concatenation which may create more object in the heap.
Using StringBuilder you can do this easy way too.
Eg:
public static String BackwardsString(String str) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(str);
return stringBuilder.reverse().toString();
}
public static void main(String[] args) {
System.out.println("Enter a string : ");
Scanner firststr = new Scanner(System.in);
String str = firststr.next();
System.out.println(BackwardsString(str));
}
try this
Scanner sc = new Scanner(System.in);
System.out.println("Enter the string ");
String str = sc.nextLine();
String[] strArray = str.split(" ");
StringBuilder reverseString = new StringBuilder("");
for (int i = strArray.length - 1; i >= 0; i--) {
reverseString.append(strArray[i]+" ");
}
System.out.println("Reverse of string is : "+reverseString.toString());
You'd probably have an easier time splitting the string:
String[] words = str1.split(" ");
Then you'd work on each word[i] reversing it, you could break it down to a char array, or use a stringbuilder as others have suggested, up to you on what you think is appropriate for your class.

Reverse string code error

The program supposed to ask the user to enter a string then the program will reverse it and display it, but the code only return the first letter
import java.util.*;
public class ReverseString {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter a String: ");
String s = scan.next();
int x = s.length();
char c = ' ';
for(int i=x-1; i>=0;i--){
c = s.charAt(i);
}
System.out.print("The reverse of String " + s + " is ");
System.out.print(c);
}
}
Output:
Enter a String: Welcome
The reverse of String Welcome is W
You're overwriting value of c in each iteration, change it to string and add to it in the loop
String c = "";
for(int i=x-1; i>=0;i--){
c += s.charAt(i);
}
Change char c = ' '; to String reverse=""; and append the character to it for each iteration.
The problem in your code is char c can hold only one character at a time.
Do like this
String reverse ="";
for(int i=s.length()-1; i>=0;i--){
reverse += s.charAt(i);
}
System.out.print(reverse);
A character is one letter; not a string.... the easiest way to do this, would be to use a StringBuilder like so -
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter a String: ");
String s = scan.next();
// int x = s.length();
// char c = ' ';
// for (int i = x - 1; i >= 0; i--) {
// c = s.charAt(i);
//}
StringBuilder c = new StringBuilder(s);
c = c.reverse();
System.out.print("The reverse of String " + s + " is ");
System.out.print(c);
}
Or, if you want to use your current approach you can (by printing one character at time) like this -
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter a String: ");
String s = scan.next();
System.out.print("The reverse of String " + s + " is ");
int x = s.length();
for (int i = x - 1; i >= 0; i--) {
char c = s.charAt(i);
System.out.print(c);
}
System.out.println();
}
If you want to make laugh your teacher (or maybe not) ;)
org.apache.commons.lang.StringUtils.reverse(s)
or without lib:
new StringBuffer(s).reverse().toString();
More efficient approach:
char[] strArray = s.toCharArray();
int len = strArray.length;
int max = (int)Math.ceil(len / 2.0);
char t;
for (int i = 0; i < max; ++i) {
t = strArray[i];
strArray[i] = strArray[len - i - 1];
strArray[len - i - 1] = t;
}
System.out.println(String.valueOf(strArray));

Finding all uppercase letters of a string in java

So I'm trying to find all the uppercase letters in a string put in by the user but I keep getting this runtime error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: 4
at java.lang.String.charAt(String.java:686)
at P43.main(P43.java:13)
I feel foolish but I just can't figure this out and oracle even talks about charAt on the page about java.lang.StringIndexOutOfBoundsException
Here is my code for finding the uppercase letters and printing them:
import java.io.*;
import java.util.*;
public class P43{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
//Uppercase
String isUp = "";
System.out.print("Please give a string: ");
String x = in.next();
int z = x.length();
for(int y = 0; y <= z; y++){
if(Character.isUpperCase(x.charAt(y))){
char w = x.charAt(y);
isUp = isUp + w + " ";
}
}
System.out.println("The uppercase characters are " + isUp);
//Uppercase
}
}
I'd really appreciate any input and or help.
for(int y = 0; y <= z; y++){
should be
for(int y = 0; y < z; y++){
Remember array index starts from ZERO.
String length returns
the number of 16-bit Unicode characters in the string
Because loop started from ZERO, loop should terminate at length-1.
The array index out of bounds is due to the for loop not terminating on length - 1, it is terminating on length
Most iterating for loops should be in the form:
for (int i = 0; i < array.length; i++) {
// access array[i];
}
It's the same with a string.
Perhaps a cleaner way would be:
String inputString; // get user input
String outputString = "";
for (int i = 0; i < inputString.length; i++) {
c = inputString.charAt(i);
outputString += Character.isUpperCase(c) ? c + " " : "";
}
System.out.println(outputString);
Edit: Forgot String Doesn't implement Iterable<Character>, silly Java.
With Java 8 you can also use lambdas. Convert the String into a IntStream, use a filter to get the uppercase characters only and create a new String by appending the filtered characters to a StringBuilder:
Scanner in = new Scanner(System.in);
System.out.print("Please give a string: ");
//Uppercase
String isUp = in.next()
.chars()
.filter(Character::isUpperCase)
.collect(StringBuilder::new, // supplier
StringBuilder::appendCodePoint, // accumulator
StringBuilder::append) // combiner
.toString();
System.out.println("The uppercase characters are " + isUp);
//Uppercase
Inspired by:
Adam Bien - Streaming A String
Simplest way to print anIntStream as a String
Try this...
Method:
public int findUpperChar(String valitateStr) {
for (int i = valitateStr.length() - 1; i >= 0; i--) {
if (Character.isUpperCase(valitateStr.charAt(i))) {
return i;
}
}
return -1;
}
Usage:
String passwordStr = password.getText().toString();
.......
int len = findUpperChar(passwordStr);
if ( len != -1) {
capitals exist.
} else {
no capitals exist.
}
Hi one of the easy step to find uppercase char in a given string...
Program
import java.io.*;
public class testUpper
{
public static void main(String args[]) throws IOException
{
String data,answer="";
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter any String : ");
data=br.readLine();
char[] findupper=data.toCharArray();
for(int i=0;i<findupper.length;i++)
{
if(findupper[i]>=65&&findupper[i]<=91) //ascii value in between 65 and 91 is A to Z
{
answer+=findupper[i]; //adding only uppercase
}
}
System.out.println("Answer : "+answer);
}
}
Output
Enter any String :
Welcome to THe String WoRlD
Answer : WTHSWRD
You can increase the readability of your code and benefit from some other features of modern Java here. Please use the Stream approach for solving this problem. Also, I suggest importing the least number of libraries into your class. Please avoid using .* while importing.
import java.util.Scanner;
public class P43 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Please give a string: ");
String x = in.next();
x.chars().filter(c -> Character.isUpperCase(c))
.forEach(c -> System.out.print((char) c + " "));
}
}
Sample input:
saveChangesInTheEditor
Sample output:
C I T E
import java.util.Scanner;
class Demo
{
public static void main(String[] args)
{
StringBuilder s=new StringBuilder();
Scanner input = new Scanner(System.in);
System.out.println("Enter your String");
String str= input.nextLine();
for(int i=0; i<str.length(); i++)
{
if(Character.isUpperCase(str.charAt(i)))
{
System.out.print(str.charAt(i)+" ");
}
}
}
}
The simplest way I know is to use regex replacement.
isUp = x.replaceAll("[^A-Z]", "");
In simple terms, this uses a regular expression which matches any character which is not in the A-Z range, and replaces it with an empty string.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the number");
String str= input.nextLine();
int ascii;
for(int i=0; i<str.length(); i++) {
ascii = str.charAt(i);
System.out.println(ascii);
if (ascii >= 65 && ascii <= 90) {
System.out.println("captal letter found ::: "+ascii);
}
}
}
public class Cama {
public static void main(String[] args) {
String camal = "getStudentByName";
String temp = "";
for (int i = 0; i < camal.length(); i++) {
if (Character.isUpperCase(camal.charAt(i))) {
System.out.print(" " + Character.toLowerCase(camal.charAt(i)));
} else if (i == 0) {
System.out.print(Character.toUpperCase(camal.charAt(i)));
}else{
System.out.print(camal.charAt(i));
}
}
}
}

Categories

Resources