Why character in StringBuild does not change? - java

The character must be entered from the console to change to lowercase letters on this line. But it displays the same word and the symbol does not change.
public class Task {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder(requestString());
char symbol = requestSymbol().charAt(0);
int count = 0;
for (int i = 0; i < sb.length(); i++) {
if (sb.charAt(i) == symbol) {
sb.setCharAt(i, sb.charAt(Character.toUpperCase(i)));
count++;
}
}
System.out.println("Number of entries: " + count);
System.out.println("Converted string: " + sb);
}
static String requestString() {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter string:");
return scanner.nextLine();
}
static String requestSymbol() {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the symbol:");
return scanner.next();
}
}

It seems to be a problem with the line:
sb.setCharAt(i, sb.charAt(Character.toUpperCase(i)));
It should be:
sb.setCharAt(i, Character.toUpperCase(symbol));

Related

I can't add a string to itself

I'm new to java and trying to add a string to itself (plus other strings also) and it runs but doesn't do anything at all, as in it just outputs "test", which is what it is before
everything else seems to work
package chucknorris;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Input string:");
String input = scanner.nextLine();
int length = input.length();
String output = "test";
for (int current = 0;current <= length;current++) {
String letter = input.substring(current, current);
output = output + letter + " ";
if (current == length) {
System.out.println(output);
}
}
}
}
Try this Solution, but you should use StringBuilder if you want to edit a String for a multiple times
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Input string:");
String input = scanner.nextLine();
int length = input.length();
String output = "test";
for (int current = 0;current <= length;current++) {
if (current >= length) {
break;
}
String letter = input.substring(current, current + 1);
output = output + letter;
}
System.out.println(output);
}
}
use concat for the string concatenation.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Input string:");
String input = scanner.nextLine();
int length = input.length();
String output = "test";
output = output.concat(output).concat(input).concat("");
System.out.println(output);
}

So my problem in this is that I cannot seem to add a void function in my code

I want to insert a void function in my code.
import java.util.*;
public class javellana {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Input String: ");
String str = scan.nextLine();
System.out.println("Input character: ");
char str1 = scan.next().charAt(0);
int num = str.length();
int i;
for (i = num - 1; i >= 0; i--) {
if (str1 == str.charAt(i)) {
System.out.println("The character " + str1 + " you intput is " + i);
break;
}
}
}
}
That is my code and I want to add a void function starting in "for". I want the for loop to be in a void function but I can't seem to do it. How do I fix this?
public class javellana {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Input String: ");
String str = scan.nextLine();
System.out.println("Input character: ");
char str1 = scan.next().charAt(0);
int num = str.length();
tt(num,str1,str);
}
static void tt(int num , char str1, String str)
{
for(int i = num - 1; i >= 0; i--) {
if (str1 == str.charAt(i)) {
System.out.println("The character " + str1 + " you intput is " + i);
break;
}
}
}
}
Apart from the code, what you wanna achieve from this is still
unclear.
You can add a void method as static and use it directly in main method.
public class javellana {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Input String: ");
String str = scan.nextLine();
System.out.println("Input character: ");
char str1 = scan.next().charAt(0);
int num = str.length();
int i;
func(str, str1);
}
static void func(String str, char str1) {
int num = str.length();
for (int i = num - 1; i >= 0; i--) {
if (str1 == str.charAt(i)) {
System.out.println("The character " + str1 + " you intput is " + i);
break;
}
}
}
}
EDIT:
You can simply use System.out.println(str.lastIndexOf(str1)); line, instead of the entire for loop for your problem
public class javellana {
String str;
char str1;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Input String: ");
str = scan.nextLine();
System.out.println("Input character: ");
str1 = scan.next().charAt(0);
func(); // call function here
}
static void func() {
int num = str.length();
for (int i = num - 1; i >= 0; i--) {
if (str1 == str.charAt(i)) {
System.out.println("The character " + str1 + " you intput is " + i);
break;
}
}
}
}
Try this for change
If
adding a void function
means adding(declaring) another method(function) in public static void main(String){};
then this is not allowed.
What you can do is; create an anonymous class or functional interface (Java 8). Which is not exactly what you want but somehow..
main() is static method, so only static method can be used from it.
Instead of using for loop, you can use String.lastIndexOf() method.
public static void main(String... args) {
try (Scanner scan = new Scanner(System.in)) {
System.out.print("Input String: ");
String str = scan.nextLine();
System.out.print("Input character: ");
char ch = scan.next().charAt(0);
lastIndexOf(str, ch);
}
}
private static void lastIndexOf(String str, char ch) {
int i = str.lastIndexOf(ch);
if (i >= 0)
System.out.println("The character " + ch + " you input is " + i);
}
You can't create a method within a method.
Currently, you're in main method.
But you can call as many methods you want from a method.
But there's some restriction. you can't call the nonstatic method within a static method.
Therefore the #pkgajulapalli answer is probably correct.

how to take input an array[] of StringBuffer in java

I wanted to take a input an array of StringBuffer for user in java but it doesn't work properly:
public class A {
public static void main(String[] args) {
B obj =new B();
Scanner sc= new Scanner(System.in);
int l;
System.out.println("enter the length of string ");
l=sc.nextInt();
StringBuffer sb[]=new StringBuffer[l];
for(int i=0;i<sb.length;i++)
{
System.out.println("enter a string "+(i+1) +" : ");
sb[i]=sb[i].append(sc.nextLine()); // in this line they will give error
}
obj.inputstring( sb);
}
You need to initialize StringBuffer object for each and every sb[i] location.
sb[i]=new StringBuffer(sc.nextLine());
Refer javadoc for Array initialization
Try this.
public static void main(String[] args) {
//B obj =new B();
Scanner sc = new Scanner(System.in);
int l;
System.out.println("enter the length of string ");
l = sc.nextInt();
sc.nextLine();
StringBuffer sb[] = new StringBuffer[l];
System.out.println("sb length==" + sb.length);
for (int i = 0; i < sb.length; i++) {
System.out.println("enter a string " + (i + 1) + " : ");
sb[i] = new StringBuffer(sc.nextLine()); // use StringBuffer(value)
}
for(int j=0;j<sb.length;j++){
System.out.println("string "+j+"="+sb[j]);
}
//for(int j=0;j<=sb.length;j++){}
//System.out.println("sb=="+sb.toString());
}

How to read input from user with unknown length?

I want to enter a string of numbers, delimited by ",". I don't know how long it will be. The input will be passed to the program and will end with the letter "x".
JAVA!
import java.util.Scanner;
public class fromUserSum {
/// input : 1,2,4x from user
/// output : 7
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int num;
int sumTotal=0;
while(scan.nextByte() != 'x') {
num = scan.nextInt();
sumTotal += num;
}
System.out.println(sumTotal);
scan.close();
}
}
PLEASE help! :)
//////////////
public class fromUserSum {
/// input : 1,2,4x from user
/// output : 7
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String userInput;
do {
System.out.println("Please enter a list of numbers in following format: 1,2,3,4x");
userInput = scan.next();
} while (!userInput.matches("(?:\\d+(?:,\\d+)*)x") || !userInput.matches("\\d+( \\d+)*x"));
scan.close();
String[] numberStrings;
if (userInput.contains(",")) {
numberStrings = userInput.replace("x", "").split(","); // 4x is now 4 and split by ','
} else {
numberStrings = userInput.replace("x", "").split(" ");
}
int sum = 0;
for (String i : numberStrings) {
sum += Integer.valueOf(i);
}
System.out.println("The sum of all numbers in the list is: " + sum);
}
}
Try this
public static void main(String[] args) {
int result = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the value");
String string = sc.nextLine();
string = string.replace("x", "");
String[] strArray = string.split(",");
for (String str : strArray) {
result += Integer.valueOf(str);
}
System.out.println("Result is " + result);
}
Input is 1,2,3,4x
Output is Result is 10
import java.io.Console;
import java.util.Scanner;
class MainClass{
public static void main(String args[]) {
int sum=0;
Console c=System.console();
Scanner scan = new Scanner(c.readLine());
scan.useDelimiter("[,x]");
while(scan.hasNextInt())
sum+=scan.nextInt();
scan.close();
System.out.print(sum);
}
}
This does the job as well. Additionally it tells the user what input is expected and if the entered list does not match the format.
public static void main(final String[] args) {
final Scanner userInputScanner = new Scanner(System.in);
String userInput;
do {
System.out.println("Please enter a list of numbers in following format: 1,2,3,4x or 1 2 3 4x");
userInput = userInputScanner.nextLine();
} while (!(userInput.matches("\\d+(,\\d+)*x") || userInput.matches("\\d+( \\d+)*x")));
userInputScanner.close();
final String[] numberStrings = userInput.replace("x", "").split("[, ]");
int sum = 0;
for (final String numberString : numberStrings) {
sum += Integer.valueOf(numberString);
}
System.out.println("The sum of all numbers in the list is: " + sum);
}

JAVA: Count each word on a String, and count each letter on the words

So, I've got a java assignment in which I have a String with a phrase. I need to count each word the phrase has and then count how many letters each word has. I've been able to split the phrase into words by using the Tokenizer, and then count and print the amount of words with .countTokens(). However, I'm not being able to count the letters in each word.
Basically the output should be something like this:
"Nihil veritas est"
Words: 3
Nihil: 5 letters
Veritas: 7 letters
Est: 3 letters
Here's my code so far:
public class words {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.println("Please type a phrase.");
String phrase= in.nextLine();
StringTokenizer stoken = new StringTokenizer(phrase);
System.out.println("Your phrase has "+stoken.countTokens()+"words");
}
Try this:
public class words {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.println("Please type a phrase.");
String phrase= in.nextLine();
String[] words = phrase.split(" ");
System.out.println("The number of words is:"+words.length);
for(int i=0; i<words.length; i++){
System.out.println(words[i]+" is "+words[i].length()+" letters long.");
}
}
}
This code uses split() instead of Tokenizer. It just seemed easier to me.
Try this:
import java.util.Scanner;
import java.util.StringTokenizer;
public class WordCount {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("PLease enter your phrase");
String phrase = in.nextLine();
StringTokenizer st = new StringTokenizer(phrase);
System.out.println("Your phrase has " + st.countTokens() + " words");
// Loop thorough to count number of letters in each word.
while (st.hasMoreTokens()) {
String tokenName = st.nextToken();
System.out.println(tokenName + ": has " + tokenName.length() + " letters");
}
}
}
Here is my solution to your problem:
public static void main(String[]args) {
Scanner in = new Scanner(System.in);
System.out.println("Please type a phrase.");
String phrase= in.nextLine();
// get an array each having a word using split
String[]words = phrase.split(" ");
//print count of words?
System.out.println("Words: "+words.length);
//loop over the words
for(int i = 0; i < words.length; i++)
{
System.out.println(words[i]+": "+words[i].length()+" letters");
}
}
public class wordCount
{
public static void main(String[] args)
{
Scanner sc= new Scanner(System.in);
System.out.println(" Enter a String1");
String str=sc.nextLine();
System.out.println(" Entered String : ");
System.out.println(str);
//logic
char ch[]=str.toCharArray();
str="";
int count=0;
for (int i = 0; i < ch.length; i++)
{
if(ch[i]!=' ')
{
str=str+ch[i];
count++;
}
else if(ch[i-1]!=' ')
{
/*str=str+"-->"+count +" ";*/
System.out.println(str+"--->"+count);
count=0;
str="";
}
}
System.out.println(str+"--->"+count);
sc.close();
}
}

Categories

Resources