During making programs about counting the number of alphabets each(e.g input-abc/output- a:1, b:1, c:1, d:0, ... , z:0)I have a problem. I don't know why the if clauses does not work...
Here is my code.
import java.util.Scanner;
public class Prac05 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String a = sc.nextLine();
String[] b = a.split("");
if (a.length() <= 100) {
for (int i = 0; i < b.length; i++) {
for (int j = 'a'; j <= 'z'; j++) {
if(b[i].equals((char) j)) {
System.out.println("1");
}
}
}
}
}
}
I am supposed to print "1", however since if-clauses does not true, nothing does output...
You are comparing a String object to a Character object, which do not equal each other because of their different types.
An easy solution, which will also result in more efficient and more elegant code is to use String.charAt(), rather than splitting the original string to a lot of small String objects, and iterate from 0 to a.length for each character in the string.
Related
I have a method called displayWord that is supposed to compare each index of an array with another array and if the indexes match, it is supposed to execute this line displayedWord[i] = wordArray[i]. When I print the displayedWord, they are all question marks even thought the print statement executes so I know it is going into the if block.
Why is displayedWord always questions marks when I print it?
public static void displayWord(char[] correctGuesses, char[] wordArray) {
char[] displayedWord = new char[wordArray.length];
for(int i = 0; i < wordArray.length; i++) {
for(int j = 0; j < correctGuesses.length; j++) {
if(wordArray[i] == correctGuesses[j]) {
displayedWord[i] = wordArray[i];
System.out.println("they are the same");
} else displayedWord[i] = '?';
}
}
for(char c : displayedWord) {
System.out.print(c);
}
}
That's because you are overeating the displayedWord, even if the char was found
Use break when you find the char to get out of the loop
here is the code
public static void displayWord(char[] correctGuesses, char[] wordArray) {
char[] displayedWord = new char[wordArray.length];
for(int i = 0; i < wordArray.length; i++) {
for(int j = 0; j < correctGuesses.length; j++) {
if(wordArray[i] == correctGuesses[j]) {
displayedWord[i] = wordArray[i];
System.out.println("they are the same");
break;
} else displayedWord[i] = '?';
}
}
for(char c : displayedWord) {
System.out.print(c);
}
}
Currently you are not comparing the corresponding indices of the two arrays, because you have defined a double for loop with two different variables.
With your code above it loops through each element of wordArray and compares every element of correctGuesses array for each wordArray element.
To get what you want, you only want to have one for loop which iterates n-times where n is the length of the smaller array.
You are overriding the correct character at the next iteration when your code hits the else case.
And it also seems like you don't need a nested loop to check whether a character in the array of guesses a matches a character in the containing correct characters (in case if characters at the same position need to be compared).
public static void displayWord(char[] correctGuesses, char[] wordArray) {
int len = Math.min(correctGuesses.length, wordArray.length);
char[] displayedWord = new char[len];
for(int i = 0; i < len; i++) {
if(wordArray[i] == correctGuesses[i]) {
displayedWord[i] = wordArray[i];
System.out.println("they are the same " + wordArray[i]);
} else displayedWord[i] = '?';
}
for(char c : displayedWord) {
System.out.print(c);
}
}
main()
public static void main(String[] args) {
displayWord(new char[]{'a', 'b', 'c'},new char[]{'e', 'b', 'e'});
}
Output:
they are the same b
?b?
This is the initial challenge I'm trying to address
1) takes two arguments—a “source" English word in a string, and an English dictionary supplied in an array
2) returns a list of English words as an array
The words returned are those from the dictionary that have four consecutive letters (or more) in common with the “source” word. For example, the word MATTER has the four letters in a row “ATTE" in common ATTEND.
The code however gives me errors with the substring
Below is the code for your reference.
public class FourLetterInCommon {
static String wrd = "split";
static String[] d = new String[]{"SPLITS", "SPLITTED", "SPLITTER", "SPLITTERS", "SPLITTING", "SPLITTINGS", "SPLITTISM", "SPLITTISMS", "SPLITTIST", "SPLITTISTS"};
public static void main(String[] args){
System.out.println(fourletters (wrd, d));
}
public static List<String> fourletters (String word, String[] dict){
int dictsize = dict.length;
int wordlength = word.length();
List<String> Commonletters = new ArrayList<String>();
for(int i = 0; i<=dictsize; i++) {
for (int j=0; j<=wordlength;) {
if(dict[i].contains(word.substring(i, 5)))
{
Commonletters.add(dict[i]);
}
break;
}
}
return Commonletters;
}
}
This is the error message I get:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1 at java.lang.String.substring(Unknown Source) at FourLetterInCommon.fourletters(FourLetterInCommon.java:22) at FourLetterInCommon.main(FourLetterInCommon.java:10)
What does the errors mean? Apologies, but a bit clueless at this stage.
Quite a few issues here.
1)
for(int i = 0; i<=dictsize; i++) {
should be
for(int i = 0; i<dictsize; i++) {
2)
for (int j=0; j<=wordlength;) {
should be
for (int j=0; j<=wordlength-4; j++) {
3)
if(dict[i].contains(word.substring(i, 5)))
should be
if(dict[i].contains(word.substring(j, j+4)))
4)
I don't believe you really want to break; there. I'm guessing you want to break when you find a match, so it should be inside the if statement.
Corrected code:
public class FourLetterInCommon
{
static String wrd = "SPLIT";
static String[] d = new String[] { "SPLITS", "SPLITTED", "SPLITTER", "SPLITTERS", "SPLITTING", "SPLITTINGS",
"SPLITTISM", "SPLITTISMS", "SPLITTIST", "SPLITTISTS" };
public static void main(String[] args)
{
System.out.println(fourletters(wrd, d));
}
public static List<String> fourletters(String word, String[] dict)
{
int dictsize = dict.length;
int wordlength = word.length();
List<String> Commonletters = new ArrayList<String>();
for (int i = 0; i < dictsize; i++)
{
for (int j = 0; j <= wordlength - 4; j++)
{
if (dict[i].contains(word.substring(j, j + 4)))
{
Commonletters.add(dict[i]);
break;
}
}
}
return Commonletters;
}
}
Output:
[SPLITS, SPLITTED, SPLITTER, SPLITTERS, SPLITTING, SPLITTINGS, SPLITTISM, SPLITTISMS, SPLITTIST, SPLITTISTS]
The following line would throw an Exception:
if(dict[i].contains(word.substring(i, 5)))
Here, i ranges from 0 to dict.length which is 10 in this case. word contains 5 characters only. So, accessing any character from index 5 onwards would throw an Exception.
If you want to check for certain number of characters then you should use this:
for (int j=0; j < wordlength;) {
if(dict[i].contains(word.substring(j, wordlength - j)))
I have a problem with this code. Otherwise it does exactly what the title says, but if the given strings are "aa" and "bbbb", it prints just "abab" instead it should print "ababbb". The program seems to stop after the characters are printed from the shorter string. Here's the code:
public static void main(String[] args) {
Scanner lukija = new Scanner(System.in);
System.out.print("Anna merkkijono: ");
String merkkijono1 = lukija.nextLine();
System.out.println("Anna toinen merkkijono: ");
String merkkijono2 = lukija.nextLine();
for (int index = 0; index < merkkijono1.length() || index < merkkijono2.length(); index++) {
if (merkkijono1.length() > index) {
System.out.print(merkkijono1.charAt(index));
if (merkkijono2.length() > index) {
System.out.print(merkkijono2.charAt(index));
}
}
}
}
}
So somehow i should make it continue even when the Characters are printed from the shorter string, any tips?
Also for some reason one of the brackets didn't fit into the code text and i wasn't able to include the java.util.Scanner and public class without turning the whole code text into a mess, sorry about that.
Move the second if-statement out of the first one.
for (int index = 0; index < merkkijono1.length() || index < merkkijono2.length(); index++) {
if (merkkijono1.length() > index) {
System.out.print(merkkijono1.charAt(index));
}
if (merkkijono2.length() > index) {
System.out.print(merkkijono2.charAt(index));
}
}
It seems the if statement was inside the wrong loop.
Here, I tested it and it works.
import java.util.Scanner;
public class Program1 {
public static void main(String[] args) {
Scanner lukija = new Scanner(System.in);
System.out.print("Anna merkkijono: ");
String merkkijono1 = lukija.nextLine();
System.out.print("Anna toinen merkkijono: ");
String merkkijono2 = lukija.nextLine();
for (int i = 0; i < merkkijono1.length() || i < merkkijono2.length(); i++) {
if (merkkijono1.length() > i) {
System.out.print(merkkijono1.charAt(i));
}
if (merkkijono2.length() > i) {
System.out.print(merkkijono2.charAt(i));
}
}
}
}
I need to double each letter in a string using a for loop and an if-then statement. How can you comb through a string and test if each character is a letter or a symbol like an exclamation point? And then print the string back out with each letter doubled and each exclamation point tripled.
This is what I have so far. It's unfinished and it doesn't work at all, but am I on the right track?
import java.util.Scanner;
public class DoubleLetters{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("Enter a sentence:");
String sentence = scan.nextLine();
boolean isLetter = false;
for (int i = 0; i < sentence.length(); i++){
isLetter = Character.isLetter(sentence.charAt(i));
if (i == sentence.length() || sentence.charAt(i) == ' ' || isLetter == false){
System.out.print(sentence.charAt(i) + sentence.charAt(i));
}
}
It looks like you were on the right way, then passed the right exit and carried on the wrong way.
for (int i = 0; i < sentence.length(); i++){ [...] } is a right way to iterate over a string's characters.
Character.isLetter(c) is a right way to check whether a character is a letter.
However, your condition is chaotic :
why would you make special conditions for spaces and end characters?
why is your isLetter condition negated?
I think your condition should simply be
if (isLetter) { /* print twice */ }
else if (isExclamationPoint) { /* print "thrice" */ }
else { /* print once */ }
Try this:
import java.util.*;
public class DoubleLetters{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("Enter a sentence:");
String sentence = scan.nextLine();
StringBuilder sb = new StringBuilder();
for (Character c: sentence.toCharArray()){
sb.append(c);
if(Character.isLetter(c)){
sb.append(c);
}
else if(c == '!'){
sb.append(c).append(c);
}
}
sentence = sb.toString();
System.out.println(sentence);
}
}
When manipulating strings like this, it is best to use StringBuilder, which allocates a contiguous character buffer of a given size. You can count how big your output String needs to be, and pass this size to the StringBuffer on construction.
I would also recommend continuing to call String.charAt for maximum efficiency.
You may also want to encapsulate your routine in a function. You can take the input as a CharSequence for maximum utility.
public class DoubleLetters {
private static int getRepetitionCount(char c) {
if (Character.isLetter(c)) {
return 2;
} else if (c == '!') {
return 3;
} else {
return 1;
}
}
public static String doubleLetters(CharSequence in) {
int inLength = in.length();
int outLength = 0;
for (int i = 0; i < inLength; ++i) {
outLength += getRepetitionCount(in.charAt(i));
}
StringBuilder out = new StringBuilder(outLength);
for (int i = 0; i < inLength; ++i) {
char c = in.charAt(i);
int reps = getRepetitionCount(c);
for (int r = 0; r < reps; ++r) {
out.append(c);
}
}
return out.toString();
}
public static void main(String[] args) {
String test = "hello! world!";
System.out.print(doubleLetters(test));
}
}
In this specific case, you could alternatively allocate a buffer of size 3 * inLength, which will be large enough to hold any potential output string.
import java.util.*;
public class Pemdas {
public static double Express(String str)
{
Stack<Double> num = new Stack<Double>();
Stack<String> op = new Stack<String>();
String number = "[0-9]*"; // any digit from 0-9
for (int i = 0; i < str.length(); i++)
{
if (str.substring(i,i+1).equals(number))
num.push(Double.parseDouble(str.substring(i, i+1)));
else if (str.substring(i, i+1).equals("+"))
op.push(str.substring(i, i +1));
System.out.println(str);
}
double n = num.pop();
if (op.pop().equals("+"))
n = n + num.pop();
return n;
}
public static void main(String[] args)
{
System.out.print("Enter an Expression: ");
String ex = StdIn.readString(); // This is where I enter my string input
System.out.println(Express(ex));
}
}
Let's say that I have an String variable of "5 + 5" as my input. In the for loop, the 5 is supposed to be pushed into the num stack, but I keep getting an ESE and I don't understand why.
You're using equals() when you want to match against a regex. equals() is for comparing literal strings. You likely want matches():
if (str.substring(i,i+1).matches(number))
num.push(Double.parseDouble(str.substring(i, i+1)));
In fact, you don't need a regex at all here. You can simplify your loop by doing something like:
for (int i = 0; i < str.length(); i++)
{
char c = str.charAt(i);
if (Character.isDigit(c))
num.push((double) (c - '0'));
else if (c == '+')
op.push("+");
System.out.println(str);
}
Finally, please follow Java's naming conventions and call your method express() instead of Express().