The output is fine but the output is in Uppercase letter, I want the output to be lowercase character, what should I do?
import java.util.Scanner;
public class Q2 {
public static void main(String[] args) {
int a[]=new int[26];
Scanner sc = new Scanner (System.in);
String str=sc.nextLine();
for(int i = 0; i<str.length();i++) {
if(str.charAt(i)>=65 && str.charAt(i)<=90) {
a[str.charAt(i)-65]++;
}
else if(str.charAt(i)>=97 && str.charAt(i)<=122) {
a[str.charAt(i)-97]++;
}
}
for(int i=0;i<26;i++) {
if(a[i]>0) {
System.out.print(" "+(char )(i+65)+ "(" + a[i]+")");
}
}
}
}
'A' is 65. 'a' is 97. Use 97 instead of 65 in your final loop.
Alternatively use 'a' directly instead of the number. This makes it more obvious what you're doing in that code.
It may be more straightforward to convert the entire string to lower case to avoid checking for upper case letters.
Also, as suggested earlier using character literals as a instead of 97 would make the code more readable.
Scanner sc = new Scanner(System.in);
int a[] = new int[26];
String str = sc.nextLine().toLowerCase();
for (char c : str.toCharArray()) {
if (c >= 'a' && c <= 'z') {
a[c - 'a']++;
}
}
for (char c = 'a'; c <= 'z'; c++) {
int i = c - 'a';
if (a[i] > 0) {
System.out.print(" "+ c + "(" + a[i] + ")");
}
}
Check out this post with a accepted answer How do I convert strings between uppercase and lowercase in Java?
You could probably do something like this
import java.util.Scanner;
public class Q2 {
public static void main(String[] args) {
int a[]=new int[26];
Scanner sc = new Scanner (System.in);
String str=sc.nextLine();
String lowerCaseInput = str.toLowerCase();
System.out.print(lowerCaseInput);
}
}
Related
I have to create a program that reads in the number of character to be printed, and it will print random chars (a-z, A-Z, 0-9 and characters like !, &, $, etc). And the first character to be printed cannot be a number (0-9).
So an example output would be like:
Length of Variable? 20
a5fTnO$akP_a12BahsiO
This is what I have so far, but I'm stuck and don't know what else I can do to make it work. I'm not sure whether I'm on the right track either.
Would it be easier for me to create a string of the characters and then just get random characters from the string (if that's possible)?
import java.util.Scanner;
public class VariableNameRandomGen{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.print("Length of the variable? ");
int num = sc.nextInt();
final int noOfChars = num;
final int charsPerLine = num;
for(int i = 0; i < noOfChars; i++){
char ch = getRandomCharacter();
if((i+i) % charsPerLine == 0)
System.out.println(ch);
else
System.out.print(ch);
}
}
public static char getRandomCharacter(char ch1, char 2){
return (char)(ch1 + Math.random() * (ch2 - ch1 + 1));
}
public static char getRandomUpperCaseLetter(){
return getRandomCharacter('A', 'Z');
}
public static char getRandomDigitCharacter(){
return getRandomCharacter('0', '9');
}
}
You can use the sample string contains all char you want:
final static String SAMPLE = "abcd... xyzABCD...XYZ ()?!;"
final static String NUM = "0123456789";
public static char getRandomCharacter(String s){
return s.charAt( new Random(s.lenght()).nextInt());
}
And in main
String rs = "" + getRandomCharacter(SAMPLE);
for(int i = 1; i < noOfChars; i++){
char ch = getRandomCharacter(SAMPLE + NUM);
rs+= ch;
}
System.out.print(rs);
I am a beginner in java and am having trouble with printing out userinput with charAt(). I need to create a program that takes userinput and adds "op" before vowels in that text. (example: Userinput -> "Beautiful" would be translated as "Bopeautopifopul") I am struggling to figure how to write this. So far I have come up with this small bit.
import java.util.Scanner;
public class oplang {
static Scanner userinput = new Scanner(System.in);
public static void main(String[] args) {
char c ='a';
int n,l;
System.out.println("This is an Openglopish translator! Enter a word here to translate ->");
String message = userinput.nextLine();
System.out.println("Translation is:");
l = message.length();
for (n=0; n<l; n++);
{
c = message.charAt();
if (c != ' ');
{
System.out.println(" ");
}
c++;
}
}}
I would use a regular expression, group any vowels - replace it with op followed by the grouping (use (?i) first if it should be case insensitive). Like,
System.out.println("Translation is:");
System.out.println(message.replaceAll("(?i)([aeiou])", "op$1"));
If you can't use a regular expression, then I would prefer a for-each loop and something like
System.out.println("Translation is:");
for (char ch : message.toCharArray()) {
if ("aeiou".indexOf(Character.toLowerCase(ch)) > -1) {
System.out.print("op");
}
System.out.print(ch);
}
System.out.println();
And, if you absolutely must use charAt, that can be written like
System.out.println("Translation is:");
for (int i = 0; i < message.length(); i++) {
char ch = message.charAt(i);
if ("aeiou".indexOf(Character.toLowerCase(ch)) > -1) {
System.out.print("op");
}
System.out.print(ch);
}
System.out.println();
I am trying to write a Java program that will print letters twice; all other characters, such as spaces, numbers, and punctuation marks, are to be left alone, except for "!" which should be tripled. My program only doubles all characters so I'm not too sure what to do now as I am very new to Java.
This is what I have so far:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a line of text.");
String myStr = scan.nextLine();
if (myStr.length()>0){
String answer = "";
for(int j=0; j<myStr.length(); j++){
char ch = myStr.charAt(j);
answer = answer + ch + ch;
}
System.out.println(answer);
}
else {
System.out.println("Please enter a string longer than 0 characters");
}
}
How about something like this, using each line as IntStream, since char values are just integers;
String myStr = scan.nextLine().chars()
.flatMap(ch -> {
if (ch == '!') {
return IntStream.of(ch, ch, ch);
} else if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) {
return IntStream.of(ch, ch);
}
return IntStream.of(ch);
})
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString();
It works great, and so much fun to work with Java streams
You can do this:
String str = "abc!123";
for(int x=0; x<str.length(); x++)
if(str.substring(x, x+1).matches("[a-zA-Z+]")) //if is alphabet
System.out.print(str.substring(x, x+1) + str.substring(x, x+1));
else if (str.substring(x, x+1).equals("!"))
System.out.print("!!!");
else
System.out.print(str.substring(x, x+1));
A rather straight forward approach which works accordingly to what you currently is doing. check whether a character is alphabet, print twice. If it is !, print 3 times. Else print the respective character once.
Input:
abc!123
Output:
aabbcc!!!123
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
String str = input.nextLine();
doubleStr(str);
}
public static void doubleStr(String s)
{
char[] array = s.toCharArray();
for(char a: array)
{
if(a>='0' && a<='9')
{
System.out.print(a);
}else if(a=='!')
{
for(int i=0; i<=2; i++)
{
System.out.print(a);
}
}
else
{
for(int i=0; i<=1; i++)
{
System.out.print(a);
}
}
}
}
Result
Original: abc ! 9
aabbcc !!! 9
A simple for loop of the characters will do it. Assuming you might want the result for other than simple printing, a transformation method returning the result would be better. That will also allow unit testing, if needed.
private static String transform(CharSequence input) {
StringBuilder buf = new StringBuilder(input.length());
for (int i = 0; i < input.length(); i++) {
char ch = input.charAt(i);
buf.append(ch);
if (ch == '!')
buf.append(ch).append(ch);
else if (Character.isLetter(ch))
buf.append(ch);
}
return buf.toString();
}
Test
System.out.println(transform("abc234&#!ff"));
System.out.println(transform("He said: \"You can't do that!\""));
Output from Ideone
aabbcc234&#!!!ffff
HHee ssaaiidd: "YYoouu ccaann'tt ddoo tthhaatt!!!"
Very Simply you can do it like this: Use regex, no need to any kind of loop.
Just Edit this line:
String answer = myStr.replaceAll("(\\p{Alpha}|(!))", "$1$1$2");
Usage:
public static void main(String[] args) throws Exception {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a line of text.");
String myStr = scan.nextLine();
if (myStr.length()>0){
String answer = myStr.replaceAll("(\\p{Alpha}|(!))", "$1$1$2");
System.out.println(answer);
}
else {
System.out.println("Please enter a string longer than 0 characters");
}
}
And the result: It is just what you want.
Input: abc234&#!ff
Output: aabbcc234&#!!!ffff
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 );
}
}
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));
}
}
}
}