This is my code to convert String to ASCII and ASCII to String. I have problem when the user enter text with spaces the all texts didn't convert but if i wrote the text in program the text converted . This is my input "Java is easy"
String str = input.next();
//String str = "Java is easy";
char ch[] = str.toCharArray();
int num[] = new int[str.length()];
for (int i = 0; i < str.length(); i++) {
System.out.print((int)ch[i] + " ");
num[i] = (int)ch[i];
}
System.out.println("");
for (int j = 0; j < str.length(); j++) {
System.out.print((char)num[j]);
}
System.out.println("");
Scanner.next() reads a single word, i.e. "Java".
Scanner.nextLine() reads an entire line, i.e. "Java is easy"
You should change
String str = input.next();
to
String str = input.nextLine();
Related
I was given to code something similar to piglatin. But I am getting the "ig" of pig in latin. What is wrong with the code?
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String str = s.nextLine();
String end = "ay";
int i, j;
String word = "";
String[] arr = str.split(" ");
for (j = 0; j < arr.length; j++) {
String indWord = arr[j];
char c = indWord.charAt(0);
for (i = 1; i < indWord.length(); i++) {
word = word + indWord.charAt(i);
}
String res = "";
res = word + c + end + " ";
System.out.print(res);
}
}
}
Axpected:
pig latin ----> igpay atinlay
Actual:
Because you are not clearing the word variable for each iteration... that was hard to see because your indentation is wrong.
Move the String word=""; line to the inside of the for(j=0;j<arr.length;j++){ loop so that the word variable is cleared for every word and you start over (instead of carrying its contents from the last word)
So I'm barely learning Java and I'm having a hard time using loops. I'm supposed to write a program that let the user enter a word and enter a letter they want to remove while printing out the other letters.
here is what I have right now:
System.out.print("Please enter a word: ");
String word = kbreader.nextLine();
System.out.print("Enter the letter you want to remove: ");
for (int k = 0; k <= word.length(); k ++)
{
String remove = kbreader.nextLine();
String word2 = word.charAt(k) + "";
String remove2 = remove.charAt(0) + "";
if (!word2.equals(remove2))
{
System.out.print(word2);
}
}
here is an example:
enter a word: aaabxaaa
enter a letter you want to remove: a
bx
One simple way to handle this would be to just use String#replace here:
System.out.println(word.replace(remove, ""));
This would remove all instances of the string remove, which in your case would just be a single letter.
Another way to do this would be to iterate your input string, and then selectively print only those characters which do not match the character to be removed:
char charRemove = remove.charAt(0);
for (int i=0; i < s.length(); i++){
char c = s.charAt(i);
if (c != charRemove) System.out.print(c);
}
Use public String replace(char oldChar, char newChar) function in java.
Modify to this :
System.out.print("Please enter a word: ");
String word = kbreader.nextLine();
System.out.print("Enter the letter you want to remove: ");
String remove = kbreader.nextLine();
word = word.replace(remove ,"");
System.out.print(word);
This is how you can do it :
System.out.print("Please enter a word: ");
String word = kbreader.nextLine();
System.out.print("Enter the letter you want to remove: ");
//read the char to remove just once before starting the loop
char remove = kbreader.nextLine().charAt(0);
for (int k = 0; k <= word.length(); k ++)
{
char word_char = word.charAt(k);
//check if the current char is equal to char required to be removed
if (word_char != remove)
{
System.out.print(word_char);
}
}
My problem is that when i input "b" it converts correctly but when i input other letters it just displaying the conversion of "b"
char ch = 'b';
int ascii = ch;
int castAscii = (int) ch;
DisplayText.setText(UserInput.getText() + " = " + castAscii);
This is because you only convert the character b to it's ascii value and not the actual user input. Assuming that UserInput.getText() returns the user defined character as character and not string:
int castAscii = (int) UserInput.getText();
DisplayText.setText(UserInput.getText() + " = " + castAscii);
In case UserInput.getText() returns a string, you can convert it into a character array and then iterate through it to combine the output.
String userInput = UserInput.getText();
String output = userInput + "=";
for (int i = 0; i < userInput.length(); i++) {
int castAscii = (int) userInput.toCharArray()[i];
output += castAscii;
if (i < userInput.length()) {
output += ",";
}
}
DisplayText.setText(output);
Using a framework like apache commons-lang would make for a more elegant solution, but this will work.
you set the ch='b'.so always you convert the "b" and ignore the input.
you must set the ch to what the user entered.
as I mentioned in comments,this is an example code to clarify the process.
String s = "hello";
char[] chars = s.toCharArray();
for (int i = 0; i < chars.length; i++) {
System.out.println(chars[i]);
int ascii = (int) chars[i];
System.out.println(ascii);
}
you can write scanner.nextline() instead of "hello" next to String s to get the string from the user.
I have been trying to write a Java program which converts the first letter of every word of a string into a capital letter. Right now it looks like this:
package strings;
import java.util.Scanner;
public class small_cap {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the sentence");
String st = sc.next();
String str = " " + st;
int j = 0; char chr = ' ';
for (int i = 0; i < str.length(); i++){
j = i + 1;
chr = str.charAt(j);
if (chr == ' '){
char a = Character.toUpperCase(str.charAt(j));
str = str.replace(str.charAt(j), a);
}
else{
char a = Character.toLowerCase(str.charAt(j));
str = str.replace(str.charAt(j), a);
}
}
System.out.println(str);
}
}
Unfortunately I keep on getting the error:
java.lang.StringIndexOutOfBoundsException: String index out of range: 4
at java.lang.String.charAt(String.java:658)
at small_cap.main(small_cap.java:19)
I don't really see any fault in the code. Can someone please point out where I am going wrong?
You were using Scanner.next() rather then Scanner.nextLine() which will read the whole sentence rather then single word.
You are adding extra space in String. Don't know the big reason behind that. It can be done without it.
Let say the Input is : "abc def" which will become " abc def" after adding extra space. Length of string will become : 7
Now for loop will iterate from 0 to 6. But on i = 6 it will try to alter the element on 7th position (since you are doing j=i+1) which will cause string index out of range error.
You are using String.Replace which will replace all matching characters irrespective of their position.
import java.util.Scanner;
public class small_cap {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the sentence");
String st = sc.nextLine();
String str = " " + st;
int j = 0; char chr = ' ';
for (int i = 0; i < str.length()-1; i++){
j = i+1;
chr = str.charAt(i);
if (chr == ' '){
char a = Character.toUpperCase(str.charAt(j));
str = str.substring(0,j)+a+str.substring(j+1);
}
else{
char a = Character.toLowerCase(str.charAt(j));
str = str.substring(0,j)+a+str.substring(j+1);
}
}
System.out.println(str);
}
}
for (int i = 0; i < str.length(); i++){
j = i + 1;
When i reaches the last valid index length - 1, j will be equal to length, which is out of bounds.
I don't really see the point of the j variable to begin with - did you mean to use i somewhere else inside the loop as well, or should you just make your loop start from 1? Or did you perhaps mean to check the previous character by doing j = i - 1; (in that case make sure you don't read before index 0)
I am trying to write a for loop in Java that will count the occurrences of a letter in a string. The user will enter the letter to count and the string in which to search. This is a very basic code, and we have not gotten to arrays or much else yet. (I realize that I declared letter twice, but my brain is dead at this point) This is what I have tried so far and am having trouble with, any help is appreciated:
Ok I changed my code per suggestions, but now it is only reading the first word of my sentence?
import java.util.Scanner;
public class CountCharacters {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
char letter;
String sentence = "";
System.out.println("Enter a character for which to search");
letter = in.next().charAt(0);
System.out.println("Enter the string to search");
sentence = in.next();
int count = 0;
for (int i = 0; i < sentence.length(); i++) {
char ch = sentence.charAt(i);
if (ch == letter) {
count++;
}
}
System.out.printf("There are %d occurrences of %s in %s", count,
letter, sentence);
}
}
I see a couple of issues. First you have two variables with the same name.
Second your if condition check for the lenght of the sentence to be greater then 0 instead of checking for character equality.
Scanner in = new Scanner(System.in);
char inLetter = "";
String sentence = "";
System.out.println("Enter a character for which to search");
inLetter = in.next().charAt(0);
System.out.println("Enter the string to search");
sentence = in.next();
int letter = 0;
for (int i = 0; i < sentence.length(); i++) {
char ch = sentence.charAt(i);
if (inLetter == ch) {
letter++;
}
}
System.out.print(sentence.charAt(letter));
I would also strongly suggest to validate the input (which is not done in the example above) instead of just assuming you got 1 character from the first input and 1 sentence in the second.
Your if (sentence.length() <= 0) { is not right. Change your condition like:
System.out.println("Enter a character for which to search");
letter = in.next();
System.out.println("Enter the string to search");
sentence = in.next();
char searchLet=letter.charAt(0); // Convert String to char
int letter = 0;
for (int i = 0; i < sentence.length(); i++) {
char ch = sentence.charAt(i);
if (searchLet== ch) { // Check the occurrence of desired letter.
letter++;
}
}
System.out.print(sentence.charAt(letter));
if (sentence.length() <= 0) {
letter++;
}
The above part of code in your program is wrong. This will never be true until otherwise you input an empty string.
And basically this is not the correct logic. You will have to use the direct comparison.
No need to loop:
String sentence = "abcabcabcd";
String letter = "b";
int numOfOccurences = sentence.length() -
sentence.replaceAll(letter, "").length();
System.out.println("numOfOccurences = "+numOfOccurences);
OUTPUT:
numOfOccurences = 3
Try this
forget String letter = "" <-- Delete
forget letter = in.next() <-- Delete
// There's no nextChar() method, so this is a work aroung
char ch = in.findWithinHorizon(".", 0).charAt(0);
int letter = 0;
for (int i = 0; i < sentence.length(); i++) {
if (sentence.charAt(i) == ch) {
letter++;
}
}
System.out.println(letter); // print number of times letter appears
// You don't want this
System.out.print(sentence.charAt(letter)); // Makes no sense
Try this:
Char letter = '';
String sentence = "";
System.out.println("Enter a character for which to search");
letter = in.next().charAt(0);
System.out.println("Enter the string to search");
sentence = in.next();
int count= 0;
for (int i = 0; i < sentence.length(); i++) {
char ch = sentence.charAt(i);
if (ch==letter) {
count++;
}
}
System.out.print(letter+" occurance:"+count);
You need to know the char you wanna search. You can use char charToSearch = letter.toCharArray()[0];
Define a variable, such as count to count the occurrences of a letter in a given string.
Loop the string and compare each char, if the char is equal to the char to search, then count++;
Example--->
int count = 0;
char charToSearch = letter.toCharArray()[0];
for (int i = 0; i < sentence.length(); i++) {
if (sentence.charAt(i) == charToSearch) {
count++;
}
}
System.out.printf("Occurrences of a %s in %s is %d", letter, sentence, count);
Hope this will helpful to you.
import java.util.Scanner;
public class CountCharacters {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter the string to search");
String sentence = in.nextLine();
System.out.println("Enter a character for which to search");
String letter = in.next();
int noOfOccurance = 0;
for (int i = 0; i < sentence.length(); i++) {
char dh=letter.charAt(0);
char ch = sentence.charAt(i);
if (dh==ch) {
noOfOccurance++;
}
}
System.out.print(noOfOccurance);
}
}
Sample Input Output:
Enter the string to search
how are you
Enter a character for which to search
o
No of Occurances : 2
try the indexOf() method.
it should work
your Scanner class has not moved to the next line after reading the character
letter = in.next().charAt(0);
add another in.nextLine() before reading the input string
System.out.println("Enter a character for which to search");
letter = in.next().charAt(0);
in.nextLine();
System.out.println("Enter the string to search");
sentence = in.nextLine();
old thread but hope this helps :)