Generating Random Number of Characters - java

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);

Related

Produce lowercase character instead of uppercase in Java

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);
}
}

I want to display the occurrence of a character in string. How can I improve my code? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I want to create a program that will display the number of occurrences of a character in a string and also count them. Right now the code just counts the characters.
I want to make the following changes:
1) How do I make this program only count one type of a character, like a or c in a string I love ice cream.
2) How do I also print the character in a string, let's say there are two d my program will then display 2 d first.
3) For the Scanner input = new Scanner(System.in); part I get error in my eclipse, says scanner cannot be resolved to a type.
Also feel free to comment on anything need to be improved in the code. Basically just want a simple program to display all the C in a string and then count the string's occurrence. I want to then mess around the code on my own, change it so I can learn Java.
So this is my code so far:
public class Count {
static final int MAX_CHAR = 256; //is this part even needed?
public static void countString(String str)
{
// Create an array of size 256 i.e. ASCII_SIZE
int count[] = new int[MAX_CHAR];
int length = str.length();
// Initialize count array index
for (int i = 0; i < length; i++)
count[str.charAt(i)]++;
// Create an array of given String size
char ch[] = new char[str.length()];
for (int i = 0; i < length; i++) {
ch[i] = str.charAt(i);
int find = 0;
for (int j = 0; j <= i; j++) {
// If any matches found
if (str.charAt(i) == ch[j])
find++;
}
if (find == 1)
System.out.println("Number of Occurrence of " +
str.charAt(i) + " is:" + count[str.charAt(i)]);
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str = "geeksforgeeks";
countString(str);
}
}
Try this
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str = input.nextLine();
// Whatever is the input it take the first character.
char searchKey = input.nextLine().charAt(0);
countString(str, searchKey);
}
public static void countString(String str, char searchKey) {
// The count show both number and size of occurrence of searchKey
String count = "";
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == searchKey)
count += str.charAt(i) + "\n";
}
System.out.println(count + "\nNumber of Occurrence of "
+ searchKey + " is " + count.length() + " in string " + str);
}
You could utilize the fact that each char can be used as an index into an array and use an array to count up each character.
public class Count {
static final int MAX_CHAR = 256;
private static void countString(String str, Character character) {
int [] counts = new int[MAX_CHAR];
char [] chars = str.toCharArray();
for (char ch : chars) {
if (character!=null && character!=ch) {
continue;
}
counts[ch]++;
}
for (int i=0; i<counts.length; i++) {
if (counts[i]>0) {
System.out.println("Character " + (char)i + " appeared " + counts[i] + " times");
}
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str = input.nextLine();
countString(str, 'e');
}
}
you can take input from user "which character he/she wants to count".
To show the occurrence of character see code below.
You need to import java.util.Scanner class.
Here is your code:
import java.util.Arrays;
import java.util.Scanner;
public class Count {
public static void countString(String str)
{
if(str!=null) {
int length = str.length();
// Create an array of given String size
char ch[] = str.toCharArray();
Arrays.sort(ch);
if(length>0) {
char x = ch[0];
int count = 1;
for(int i=1;i<length; i++) {
if(ch[i] == x) {
count++;
} else {
System.out.println("Number of Occurrence of '" +
ch[i-1] + "' is: " + count);
x= ch[i];
count = 1;
}
}
System.out.println("Number of Occurrence of '" +
ch[length-1] + "' is: " + count);
}
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str = input.nextLine();//"geeksforgeeks";
countString(str);
}
}
See the snippet below for a way to do it in Java8
public static void main(String[] args) {
// printing all frequencies
getCharacterFrequency("test")
.forEach((key,value) -> System.out.println("Key : " + key + ", value: " + value));
// printing frequency for a specific character
Map<Character, Long> frequencies = getCharacterFrequency("test");
Character character = 't';
System.out.println("Frequency for t: " +
(frequencies.containsKey(character) ? frequencies.get(character): 0));
}
public static final Map<Character, Long> getCharacterFrequency(String string){
if(string == null){
throw new RuntimeException("Null string");
}
return string
.chars()
.mapToObj(c -> (char) c)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
}
You just have to modify this line of code:
using for loop, print str.charAt(i) for count[str.charAt(i) times in your if statement.
if (find == 1) {
for(int k=0;k< count[str.charAt(i)];k++)
System.out.print(str.charAt(i)+",");
System.out.println(count[str.charAt(i)]);
}
Edit: modified based on your comment, if you want the whole code
import java.util.*;
public class Count {
static final int MAX_CHAR = 256; //is this part even needed?
public static void countString(String str)
{
// Create an array of size 256 i.e. ASCII_SIZE
int count[] = new int[MAX_CHAR];
int length = str.length();
// Initialize count array index
for (int i = 0; i < length; i++)
count[str.charAt(i)]++;
// Create an array of given String size
char ch[] = new char[str.length()];
for (int i = 0; i < length; i++) {
ch[i] = str.charAt(i);
int find = 0;
for (int j = 0; j <= i; j++) {
// If any matches found
if (str.charAt(i) == ch[j]){
//System.out.println(str.charAt(i));
find++;
}
}
if (find == 1) {
for(int k=0;k< count[str.charAt(i)];k++)
System.out.print(str.charAt(i)+",");
System.out.println(count[str.charAt(i)]);
}
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str = "geeksfeorgeeks";
str = input.nextLine();
countString(str);
}
}
output
g,g,2
e,e,e,e,e,5
k,k,2
s,s,2
f,1
o,1
r,1
I know you are beginner but if you want to try new version java 8 features which makes our coding life simple and easier you can try this
public class Count {
static final int MAX_CHAR = 256;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str = "geeksforgeeks";
countString(str, 'e');
}
public static void countString(String str, char value)
{
List<String> l = Arrays.asList(str.split(""));
// prints count of each character occurence in string
l.stream().forEach(character->System.out.println("Number of Occurrence of " +
character + " is:" + Collections.frequency(l, character)));
if(!(Character.toString(value).isEmpty())) {
// prints count of specified character in string
System.out.println("Number of Occurrence of " +
value + " is:" + Collections.frequency(l, Character.toString(value)));
}
}
And this is the code with requirements mentioned in comments
public class Count {
static final int MAX_CHAR = 256;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str = "geeksforgeeks";
countString(str, 'e');
}
public static void countString(String str, char value)
{
String[] arr = str.split("");
StringBuffer tempString = new StringBuffer();
for(String s:arr) {
tempString.append(s);
for(char ch:s.toCharArray()) {
System.out.println("Number of Occurrence of " +
ch + " is:" + tempString.chars().filter(i->i==ch).count());
}
}
if(!(Character.toString(value).isEmpty())) {
StringBuffer tempString2 = new StringBuffer();
for(String s:arr) {
tempString2.append(s);
for(char ch:s.toCharArray()) {
if(ch==value) {
System.out.println("Number of Occurrence of " +
ch + " is:" + tempString2.chars().filter(i->i==ch).count());
}
}
}
}
}
}
You can use this code below;
import java.util.Scanner;
public class Count {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str = input.nextLine();
char key = input.nextLine().charAt(0);
countString(str, key);
}
public static void countString(String str, char searchKey) {
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == searchKey)
count++;
}
System.out.println("Number of Occurrence of "
+ searchKey + " is " + count + " in string " + str);
for (int i = 0; i < count; i++) {
System.out.println(searchKey);
}
if (count > 0) {
System.out.println(count);
}
}
}
I would create a method such as the one below:
public static String stringCounter(String k) {
char[] strings = k.toCharArray();
int numStrings = strings.length;
Map<String, Integer> m = new HashMap<String, Integer>();
int counter = 0;
for(int x = 0; x < numStrings; x++) {
for(int y = 0; y < numStrings; y++) {
if(strings[x] == strings[y]) {
counter++;
}
}m.put(String.valueOf(strings[x]), counter);
counter = 0;
}
for(int x = 0; x < strings.length; x++) {
System.out.println(m.get(String.valueOf(strings[x])) + String.valueOf(strings[x]));
}
return m.toString();
}
}
Obviously as you did, I would pass a String as the argument to the stringCounter method. I would convert the String to a charArray in this scenario and I would also create a map in order to store a String as the key, and store an Integer for the number of times that individual string occurs in the character Array. The variable counter will count how many times that individual String occurs. We can then create a nested for loop. The outer loop will loop through each character in the array and the inner loop will compare it to each character in the array. If there is a match, the counter will increment. When the nested loop is finished, we can add the character to the Map along with the number of times it occurred in the loop. We can then print the results in another for loop my iterating through the map and the char array. We can print the number of times the character occurred as you mentioned doing, along with the value. We can also return the String value of the map which looks cleaner too. But you can simply make this method void if you don't want to return the map. The output should be as follows:
I tested the method in the main method by entering the String "Hello world":
System.out.println(stringCounter("Hello World"));
And here is our final output:
1H
1e
3l
3l
2o
1
1W
2o
1r
3l
1d
{ =1, r=1, d=1, e=1, W=1, H=1, l=3, o=2}
You get the number of times each character occurs in the String and you can use either the Map or print the output.
Now for your scanner. To add the Scanner to the program here is the code that you will need to add at the top of your code to prompt the user for String input:
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a String: ");
String str = scan.nextLine();
System.out.println(stringCounter(str));
You have to create the Scanner Object first, adding System.in to the constructor to get input from the keyboard. You can then prompt the user with a print statement to enter a String. You can then create a String variable which will store the String by calling the "Scanner.nextLine()" method as the value. This will grab the next line of userinput from the keyboard. Now you can pass the userinput to our method and it will operate the same way. Here is what it should look like to the user:
Please enter a String:
Hello World
1H
1e
3l
3l
2o
1
1W
2o
1r
3l
1d
{ =1, r=1, d=1, e=1, W=1, H=1, l=3, o=2}

How can I ignore part of an input in Java?

I need to make a program that can convert hexadecimal values to decimal. I got the program to work but I need to make my program display the same output no matter if the hexadecimal value entered contains the "0x" in front or not.
this is my code.
import java.util.Scanner;
public class Main {
public static long hex2decimal(String s){
String digits = "0123456789ABCDEF";
int val = 0;
for(int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
int d = digits.indexOf(c);
val = 16*val + d;
}
return val;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
long decimal;
System.out.println("Please enter the hex string:");
String s = sc.next().toUpperCase();
decimal = hex2decimal(s);
System.out.println(decimal);
}
}
Why should you not using Integer.parseInt("121",16), rather custom logic for converting hex to decimal. Here 16 is radix telling number is hexadecimal and will be converted to decimal.
System.out.println(Integer.parseInt("121",16));

Counting Upper and Lower characters in a string using an array

I have been working on this problem for two days now and have no idea where I'm going wrong.
Essentially I need to ask a user for a string of words.
I need to set up an int array of 26 elements that holds the count of lower case letters and one for upper case letters.
I can't get the program to compare with the array elements properly. This is my code so far:
public class Lab17Array {
public static void main(String[] args)
{
Scanner kb = new Scanner (System.in);
int lLetter = 0;
int uLetter = 0;
// int[] alph = new int [26];
int alph [] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
int Alph [] = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
System.out.println("Enter a phrase");
String user = kb.nextLine();
// to print out length of word
System.out.println("Total number of letters is " + user.length());
for(int i = 0; i < user.length(); i++)
{
}
System.out.println("Upper case letters are:" + uLetter);
System.out.println("Lower case letters are:" + lLetter);
int otherL = user.length() - (uLetter + lLetter);
// to print out other chars that aren't letters
System.out.println("Number of all other letters is " + otherL );
}
}
Inside my for loop is where I've been trying different if conditions. I have no idea what I'm missing?
Using an Array
You could use String.toCharArray() and a for-each loop to iterate your userInput (you seem to have changed the variable name between your post, and your comment). Regardless, something like
for (char ch : user.toCharArray()) {
if (Character.isLowerCase(ch)) {
lLetter++;
} else if (Character.isUpperCase(ch)) {
uLetter++;
}
}
Using Regular Expression(s)
You could reduce your code by using a regular expression to remove all non-lowercase characters from the input and another to remove all non-uppercase characters from the input like
int lLetter = user.replaceAll("[^a-z]", "").length(); // <-- removes everything not a-z
int uLetter = user.replaceAll("[^A-Z]", "").length(); // <-- removes everything not A-Z
Try this
int upperCount = 0;
int lowerCount = 0;
Scanner sc = new Scanner(System.in);
String w = sc.nextLine();
for(int i = 0; i < w.length(); i++){
if(Character.isUpperCase(w.charAt(i))){
upperCount++;
}else{
lowerCount++;
}
}
System.out.println("Upper Counts are "+upperCount+" lower counts are "+lowerCount);
Try this.
for(int i = 0; i < user.length(); i++)
{
int ch = user.charAt(i);
if (Arrays.binarySearch(alph, ch) >= 0)
++lLetter;
if (Arrays.binarySearch(Alph, ch) >= 0)
++uLetter;
}

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