import java.util.Scanner;
public class Separate {
public static void main(String[] args) {
Scanner user_input = new Scanner( System.in );
String variable;
System.out.print("Enter Variable:");
variable = user_input.next();
Separate(variable);
}
public static void Separate(String str) {
String number = "";
String letter = "";
String symbol = "";
for (int i = 0; i < str.length(); i++) {
char a = str.charAt(i);
if (Character.isDigit(a)) {
number = number + a;
} else {
letter = letter + a;
}
}
System.out.println("Alphabets in string:"+letter);
System.out.println("Numbers in String:"+number);
}
}
Okay, i already have this code which separate the Numbers and Letters that i Input. The problem is, when ever i input Symbols for example (^,+,-,%,*) it also states as a Letter.
What i want to do is to separate the symbol from letters just like what i did on Numbers and Letters and make another output for it.
public static void separate(String string) {
StringBuilder alphabetsBuilder = new StringBuilder();
StringBuilder numbersBuilder = new StringBuilder();
StringBuilder symbolsBuilder = new StringBuilder();
for (int i = 0; i < string.length(); i++) {
char ch = string.charAt(i);
if (Character.isAlphabetic(ch)) {
alphabetsBuilder.append(ch);
} else if (Character.isDigit(ch)) {
numbersBuilder.append(ch);
} else {
symbolsBuilder.append(ch);
}
}
System.out.println("Alphabets in string: " + alphabetsBuilder.toString());
System.out.println("Numbers in String: " + numbersBuilder.toString());
System.out.println("Sysmbols in String: " + symbolsBuilder.toString());
}
You are testing if the character isDigit, else treat it as a letter.
Well, if it is not a digit, all other cases go to else, in your code. Create an else case for those symbols also.
As this reeks of homework, just see the documentation of Character, which had that nice function isDigit.
public static void Separate(String str)
{
String number = "";
String letter = "";
String symbol = "";
for (int i = 0; i < str.length(); i++)
{
char a = str.charAt(i);
if (Character.isDigit(a))
{
number = number + a;
continue;
}
if(Character.isLetter(a))
{
letter = letter + a;
}
else
{
symbol = symbol + a;
}
}
System.out.println("Alphabets in string:"+letter);
System.out.println("Numbers in String:"+number);
}
import java.util.Scanner;
public class Separate {
public static void main(String[] args) {
Scanner user_input = new Scanner( System.in );
String variable;
System.out.print("Enter Variable:");
variable = user_input.next();
Separate(variable);
}
public static void Separate(String str)
{
String number = "";
String letter = "";
String symbol = "";
for (int i = 0; i < str.length(); i++) {
char a = str.charAt(i);
if (Character.isDigit(a)) {
number = number + a;
} else if (Character.isLetter(a)) {
letter = letter + a;
} else {
symbol = symbol + a;
}
}
System.out.println("Alphabets in string:"+letter);
System.out.println("Numbers in String:"+number);
System.out.println("Symbols in String:"+symbol);
}
}
Related
I am trying to write a program Count.java that counts the characters, newlines, and words in a string input by the user with a return value that is an array of the three counts.
I've written a program that is supposed to store a string entered by the user from the main method as the variable text in the method public static int[] analyze(String text) and, then, analyze it with the three integer count variables wordCount, charCount, and lineCount.
public class Count {
public static void main(String[] args) {
System.out.print("Please enter a string: ");
System.out.println(arr);
System.out.println("Total number of words: " + arr[0]);
System.out.println("Total number of characters: " + arr[1]);
System.out.println("Total number of newlines: " + arr[2]);
}
public static int[] analyze(String text) {
Scanner in = new Scanner(System.in);
String text = in.nextLine();
int wordCount = 0;
int charCount = 0;
int lineCount = 1;
int[] arr;
arr = new arr[] {wordCount, charCount, lineCount};
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) == ' ' && text.charAt(i + 1) != ' ') {
wordCount++;
}
if (text.charAt(i) != ' ') {
charCount++;
}
}
if (text.charAt(i) == text.charAt(i)) {
lineCount++;
}
return arr;
}
}
I want it to output the number of characters, newlines, and words of the user's input string. However, when I try to run it, the compiler doesn't recognize my string variable text and array arr. Any suggestion for how I might fix this?
Jess,
There is my solution. Also I would suggest you to learn more java core and remember to try to google questions before you ask. Good luck in your journey :)
public class Count {
public static void main(String[] args) {
System.out.print("Please enter a string: ");
Scanner in = new Scanner(System.in);
String text = in.nextLine();
int arr[] = analyze(text);
System.out.println(arr);
System.out.println("Total number of words: " + arr[0]);
System.out.println("Total number of characters: " + arr[1]);
System.out.println("Total number of newlines: " + arr[2]);
}
public static int[] analyze(String text) {
int[] arr = new int[3];
// count lines
String[] lines = text.split("\r\n|\r|\n"); // taken from https://stackoverflow.com/questions/454908/split-java-string-by-new-line
arr[2] = lines.length;
// count number of words
arr[0] = countWords(text);
// count number of characters
arr[1] = counteCharacters(text);
return arr;
}
static final int OUT = 0;
static final int IN = 1;
static int countWords(String str) // taken from https://www.geeksforgeeks.org/count-words-in-a-given-string/
{
int state = OUT;
int wc = 0;
int i = 0;
while (i < str.length()) {
if (str.charAt(i) == ' ' || str.charAt(i) == '\n'
|| str.charAt(i) == '\t')
state = OUT;
else if (state == OUT) {
state = IN;
++wc;
}
++i;
}
return wc;
}
static int count = 0; // taken from https://www.javatpoint.com/java-program-to-count-the-total-number-of-characters-in-a-string
static int counteCharacters(String text) {
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) != ' ')
count++;
}
return count;
}
}
I think you should analyse input data on new string available, because not to store it in one bit String object. Another note is to use Data object instead of an array; this is more intuitive:
public class Count {
public static void main(String... args) {
try (Scanner scan = new Scanner(System.in)) {
System.out.print("Please enter a string (empty line to stop): ");
Data data = analyze(scan);
System.out.println("Total number of words: " + data.totalWords);
System.out.println("Total number of characters: " + data.totalCharacters);
System.out.println("Total number of newlines: " + data.totalNewLines);
}
}
public static Data analyze(Scanner scan) {
Data data = new Data();
while (true) {
String line = scan.nextLine();
if (line.isEmpty())
break;
else {
data.totalNewLines++;
for (int i = 0; i < line.length(); i++)
if (!Character.isWhitespace(line.charAt(i)))
data.totalCharacters++;
data.totalWords += line.split("\\s+").length;
}
}
if (data.totalNewLines > 0)
data.totalNewLines--;
return data;
}
private static final class Data {
private int totalCharacters;
private int totalNewLines;
private int totalWords;
}
}
I am working on a challenge that requires us to input a string containing numbers. For example, "This 23 string has 738 numbers"
And the method needs to add the values of 2+3 to return 5 and 7+3+8 to return 18.
But I don't know how to make a loop to find each number in the input string, perform that operation, and continue through the rest of the string. Any suggestions or solutions?
A successful method would take a string as an input, like "This 23 string has 34 or cat 48", and the method would return 5, 7 and 12.
I have figured out how to use regular expressions to tease out the numbers from a string, but I don't know how to add the digits of each number teased out into an output
package reverseTest;
import java.util.Scanner;
public class ExtractNumbers {`enter code here`
public static void main(String[] args)
{
String str;
String numbers;
Scanner SC=new Scanner(System.in);
System.out.print("Enter string that contains numbers: ");
str=SC.nextLine();
//extracting string
numbers=str.replaceAll("[^0-9]", "");
System.out.println("Numbers are: " + numbers);
}
}
And this adds ALL the numbers in a string:
String a="jklmn489pjro635ops";
int sum = 0;
String num = "";
for(int i = 0; i < a.length(); i++) {
if(Character.isDigit(a.charAt(i))) {
num = num + a.charAt(i);
} else {
if(!num.equals("")) {
sum = sum + Integer.parseInt(num);
num = "";
}
}
}
System.out.println(sum);
}
I don't know how to combine this code with code that can add the numbers this method outputs together.
We can try using Java's regex engine with the pattern \d+. Then we can iterate each match character by character, and tally the sum.
String a = "This 23 string has 738 numbers";
String pattern = "\\d+";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(a);
while (m.find()) {
System.out.print("found numbers: " + m.group(0) + " = ");
int sum = 0;
for (int i=0; i < m.group(0).length(); ++i) {
sum += m.group(0).charAt(i) - '0';
}
System.out.println(sum);
}
This prints:
found numbers: 23 = 5
found numbers: 738 = 18
You can simply split the input string to have separated tokens and then split each token to have only digits:
String s = "This 23 string has 738 numbers";
String[] st = s.split(" ");
for (int i=0 ; i<st.length ; i++) {
if (st[i].matches("[0-9]+")) {
String[] c = st[i].split("(?=\\d)");
int sum = 0;
for(int j=0 ; j<c.length ; j++) {
sum += Integer.parseInt(c[j]);
}
System.out.println(sum);
}
}
the output is:
5
18
I'm re-learning Java after a two decade hiatus, and evaluating BlueJ at the same time for possible use in my classroom. This seemed like a great project to practice with, so thanks for the post! Here's my take on it, without the use of Regular Expressions.
Class FindDigits:
import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
public class FindDigits
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.print("Enter string to analyze: ");
String input = scan.nextLine();
FindDigits fd = new FindDigits(input);
System.out.println("Input: " + fd.getInput());
List<NumberSum> results = fd.getSums();
if (results.size() > 0)
{
for(NumberSum ns: results)
{
System.out.println("Number: " + ns.getNumber() + ", Sum: " + ns.getSum());
}
}
else
{
System.out.println("No numbers found.");
}
}
private String _input;
public String getInput()
{
return _input;
}
public FindDigits(String input)
{
_input = input;
}
private List<String> getNumbers()
{
List<String> numbers = new ArrayList();
String curNumber = "";
for(Character c: getInput().toCharArray())
{
if(Character.isDigit(c))
{
curNumber = curNumber + c;
}
else
{
if (!curNumber.isEmpty())
{
numbers.add(curNumber);
curNumber = "";
}
}
}
if (!curNumber.isEmpty())
{
numbers.add(curNumber);
}
return numbers;
}
public List<NumberSum> getSums()
{
List<NumberSum> sums = new ArrayList<NumberSum>();
for(String number: getNumbers())
{
sums.add(new NumberSum(number));
}
return sums;
}
}
Class NumberSum:
public class NumberSum
{
private String _number;
public String getNumber()
{
return _number;
}
public NumberSum(String number)
{
_number = number;
for(char c: number.toCharArray())
{
if(!Character.isDigit(c))
{
_number = "";
break;
}
}
}
public int getSum()
{
return sum(getNumber());
}
private int sum(String number)
{
if (!getNumber().isEmpty())
{
int total = 0;
for(char c: number.toCharArray())
{
total = total + Character.getNumericValue(c);
}
return total;
}
else
{
return -1;
}
}
}
Output:
I have written a program which takes a String as user input and displays the count of letters, digits and white-spaces. I wrote the code using the Tokenizer-class, and it counts the letters and digits, but it leaves out the white-spaces. Any ideas?
import java.util.Scanner;
public class line {
public static void main(String[] args) {
System.out.println("Enter anything you want.");
String text;
int let = 0;
int dig = 0;
int space= 0;
Scanner sc = new Scanner(System.in);
text = sc.next();
char[]arr=text.toCharArray();
for(int i=0;i<text.length();i++) {
if (Character.isDigit(arr[i])) {
dig++;
} else if (Character.isLetter(arr[i])) {
let++;
} else if (Character.isWhitespace(arr[i])) {
space++;
}
}
System.out.println("Number of Letters : "+let);
System.out.println("Number of Digits : "+dig);
System.out.println("Number of Whitespaces : "+space);
}
}
Scanner by default breaks the input into tokens, using whitespace as the delimiter!
Simply put, it gobbles up all the whitespace!
You can change the delimiter to something else using sc.useDelimiter(/*ToDo - suitable character here - a semicolon perhaps*/).
You have got problem in
sc.next();
except it, use
sc.nextLine();
it should work.
Instead of text = sc.next(); use text = sc.nextLine();
Try using
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Line {
public static void main(String[] args) throws Exception {
String s;
System.out.println("Enter anything you want.");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
s = br.readLine();
int length = s.length();
int letters = 0;
int numbers = 0;
int spaces = 0;
for (int i = 0; i < length; i++) {
char ch;
ch = s.charAt(i);
if (Character.isLetter(ch)) {
letters++;
} else {
if (Character.isDigit(ch)) {
numbers++;
} else {
if (Character.isWhitespace(ch)) {
spaces++;
} else
continue;
}
}
}
System.out.println("Number of letters::" + letters);
System.out.println("Number of digits::" + numbers);
System.out.println("Number of white spaces:::" + spaces);
}
}
I present three random letters to the user, lets say ' J U D ' and my user has to give a word for each letter starting with the assigned random letter, for example:
"Just Use Data".
I have been unsuccessful searching for how to validate that the user's input starts with the assigned random letter.
My code
public static void generateLetters(){
Random randomLetter = new Random();
int i;
char[] letter = {'A', 'B', 'C', 'D', 'E', 'F'};
// It's A-Z, but for typing sake... you get the point
char[] letters = new char[26];
for(i = 0; i <= 3; i++){
letters[i] = letter[randomLetter.nextInt(26)];
System.out.printf(letters[i] + " ");
}
}
The above block will generate letters randomly and works fine. Below, I'll enter basically what I have for the user input.
public static String[] getWord(String[] word){
System.out.println("Enter a word for your letters: ");
Scanner wordInput = new Scanner(System.in);
String inputWord = wordInput.nextLine().toUpperCase();
return word;
}
Simple thus far and this is my main function:
public statc void main(String[] args){
generateLetters();
getWord();
}
I need to take the string returned from getWord() and verify that each word input does begin with the randomly assigned letters. I've been unsuccessful in doing this. All of the syntax I find during my online research just gets me confused.
generateLetters() should return the generated letters.
getWord() doesn't actually do anything with the user input. Make it return a String that contains the user input.
You can use a separate method to validate the input.
Here's a fixed version of your code.
public static void main(String[] args) {
char[] letters = generateLetters();
System.out.println(letters);
String input = getWord();
System.out.println("Input is " + (isValid(letters, input) ? "valid" : "invalid"));
}
public static boolean isValid(char[] letters, String input) {
String[] words = input.split(" ");
for (int n = 0; n < words.length; n++)
if (!words[n].startsWith("" + letters[n]))
return false;
return true;
}
// Here're the fixed versions of your other two methods:
public static String getWord(){
System.out.println("Enter a word for your letters: ");
Scanner wordInput = new Scanner(System.in);
String inputWord = wordInput.nextLine().toUpperCase();
wordInput.close();
return inputWord;
}
public static char[] generateLetters(){
Random randomLetter = new Random();
char[] letter = new char[26];
char c = 'A';
for (int i = 0; i < 26; i++)
letter[i] = c++;
char[] letters = new char[26];
for(int i = 0; i < 3; i++)
letters[i] = letter[randomLetter.nextInt(26)];
return letters;
}
You can try this one.
public static String getWord() {
System.out.println("Enter a word for your letters: ");
Scanner wordInput = new Scanner(System.in);
String inputWord = wordInput.nextLine().toUpperCase();
wordInput.close();
return inputWord;
}
public static void main(String[] args) {
char[] letters = generateLetters();
String input = getWord();
StringTokenizer st = new StringTokenizer(input, " ");
int counter = 0;
boolean isValid = true;
while (st.hasMoreTokens()) {
String word = st.nextToken();
if (!word.startsWith(String.valueOf(letters[counter]))) {
isValid = false;
break;
}
counter++;
}
if (isValid) {
System.out.println("valid");
} else {
System.out.println("Invalid");
}
}
This code will only work for the input you have provided, i am assuming thats what you need i.e. if the random letters are ' J U D ' only the input "Just Use Data". will qualify as correct input and not Use Just Data. I have also not checked the boundaries of input.
import java.util.Random;
import java.util.Scanner;
public class NewClass {
public static void main(String[] args) {
char[] letters = generateLetters();
String input = getWord();
String[] words = input.split(" ");
if (words.length == letters.length) {
if (check(letters, words)) {
System.out.println("Yeah");
} else {
System.out.println("Oops");
}
} else {
System.out.println("INVALID");
}
}
public static Boolean check(char[] letters, String[] words) {
for (int i = 0; i < letters.length; i++) {
if (words[i].charAt(0) != letters[i]) {
return false;
}
}
return true;
}
public static String getWord() {
System.out.println("Enter a word for your letters: ");
Scanner wordInput = new Scanner(System.in);
String inputWord = wordInput.nextLine().toUpperCase();
return inputWord;
}
public static char[] generateLetters() {
Random randomLetter = new Random();
char[] letters = new char[3];//Make it varaible length
for (int i = 0; i < letters.length; i++) {
letters[i] = (char) ((int) randomLetter.nextInt(26) + 'A');
System.out.printf(letters[i] + " ");
}
return letters;
}
}
Method 2 Regex
public static Boolean check(char[] letters, String word) {
return word.matches(letters[0]+"(\\S)*( )"+letters[1]+"(\\S)*( )"+letters[2]+"(\\S)*");
}
I am to create a program that checks for palindromes in a sentence and display the palindromes that have been found. My following code keeps giving me a "String is out of bounds" error. What am i doing wrong?
My Program:
import javax.swing.JOptionPane;
public class Palindromechkr {
public static void main(String[] args) {
//Declare Variables
String Palin, input, Rinput = "";
int wordlength, spacePos;
//Ask for sentance
input = JOptionPane.showInputDialog("enter a sentance");
//Split string
spacePos = input.indexOf(" ");
String word = input.substring(0, spacePos);
//Get palindromes
System.out.println("Your Palindromes are:");
for (int counter = 0; counter < input.length(); counter++) {
//Reverse first word
wordlength = word.length();
for (int i = wordlength - 1; i >= 0; i--) {
Rinput = Rinput + word.charAt(i);
//Add word to An array of Palindromes
if (Rinput.equalsIgnoreCase(word)) {
Palin = word;
System.out.println("Palin:" + Palin);
break;
}
//Move on to the next word in the string
input = input.substring(input.indexOf(" ") + 1) + " ";
word = input.substring(0, input.indexOf(" "));
}
}
}
}
If you know functions you can use a recursive function to build the palindrome version of a string (it's a common example of how recursion works).
Here's an example:
import javax.swing.JOptionPane;
public class Palindromechkr {
public static void main(String[] args) {
//Declare Variables
String Palin, input, Rinput = "";
int wordlength, spacePos;
//Ask for sentance
input = JOptionPane.showInputDialog("enter a sentance");
String[] words = input.split(" +"); // see regular expressions to understand the "+"
for(int i = 0; i < words.length; i++) { // cycle through all the words in the array
Rinput = makePalindrome(words[i]); // build the palindrome version of the current word using the recursive function
if(Rinput.equalsIgnoreCase(words[i])) {
Palin = words[i];
System.out.println("Palin: " + Palin);
}
}
}
// this is the recursive function that build the palindrome version of its parameter "word"
public static String makePalindrome(String word) {
if(word.length() <= 1) return word; // recursion base case
char first = word.charAt(0); // get the first character
char last = word.charAt(word.length()-1); // get the last character
String middle = word.substring(1, word.length()-1); // take the "internal" part of the word
// i.e. the word without the first and last characters
String palindrome = last + makePalindrome(middle) + first; // recursive call building the palindrome
return palindrome; // return the palindrome word
}
}
You should have done is
public static void main(String[] args) {
String Palin, input, Rinput = "";
input = new Scanner(System.in).nextLine();
//Split string
for(String str : input.split(" ")){
for (int counter = str.length()-1; counter >= 0; counter--) {
Rinput = Rinput + str.charAt(counter);
}
if (Rinput.equalsIgnoreCase(str)) {
Palin = str;
System.out.println("Palin:" + Palin);
}
Rinput="";
}
}
I don't know if you are aware but StringBuilder has a reverse method to it. Which can be used like this :
public static void main(String[] args) {
String input;
input = new Scanner(System.in).nextLine();
//Split string
for(String str : input.split(" ")){
if (new StringBuilder(str).reverse().toString().equalsIgnoreCase(str)) {
System.out.println("Palin:" + str);
}
}
}