I have been doing an assignment, and I'm stuck. If I enter the letters: ahb, it prints only the last letter b not the whole thing:
public void run()
{
String value;
while (true) {
try {
value = (String) conB.remove();
if(value != null) { {
for(int i=0; i < value.length(); i++) {
if(Character.isDigit(value.charAt(i))) {
int x = Integer.parseInt(value);
bConWin.setData(" "+(x*2));
}
if(Character.isLowerCase(value.charAt(i))) {
char x = value.toUpperCase().charAt(i);
//changed.append(Character.toUpperCase(x));
bConWin.setData(" " +x);
}
if(Character.isUpperCase(value.charAt(i))) {
char x = value.toLowerCase().charAt(i);
bConWin.setData(" "+x);
}
}
}
}
}
}
You are only ever assigning one character as bConWin's data. Here's a fix as well as some tidying:
public static void main(String args[]) {
String value = "HaaaOppSaN";
if(value != null) {
StringBuilder newValue = new StringBuilder();
for(int i = 0; i < value.length(); i++) {
char x = value.charAt(i);
if(Character.isLowerCase(x)) {
x = Character.toUpperCase(x);
} else {
x = Character.toLowerCase(x);
}
newValue.append("" + x);
}
bConWin.setData(newValue.toString());
}
}
The outer endless loop is not needed. The try without a catch block as well.
Take a look at this:
public static void main(String[] args) {
String switched = switchCharacterCase("Hello World!");
bConWin.setData(switched);
System.out.println(switched);
}
public static String switchCharacterCase(final String input) {
StringBuilder switched = new StringBuilder();
if(input != null) { // nothing to do here, return switched
for(int i = 0; i < input.length(); i++) {
Character c = input.charAt(i);
if(Character.isLowerCase(c)) {
c = Character.toUpperCase(c);
} else {
c = Character.toLowerCase(c);
}
switched.append(c);
}
}
return switched.toString();
}
Related
In this problem, I am attempting to begin with an array and add or remove words. My problem so far is adding words. I want to have an array String[] {"",""} and fill this up, and if a word is repeated, do nothing. So, add("computer"), add("again"), and add("computer") would result in {"computer", "again"} and give me count 3. I keep getting {"computer", "computer", "again"} remove("computer") would result in {"again", "again"} and give me count 1. Could on look at this code and help?
public class WordList {
public String[] words;
int count;
public WordList() {
count = 0;
words = new String[] {"",""};
}
public int addWord(String w) {
WordList r = new WordList();
int x = r.findWord(w);
int y = words.length;
if (x>-1) {
return count;
}
else if (x==-1) {
if (count < words.length) {
words[count] = w;
}
else if (count == words.length) {
String[] nwords = new String[words.length * 2];
for (int i = 0; i < words.length; i++) {
nwords[i] = words[i];
}
words = nwords;
words[y] = w;
}
count++;
}
return count;
}
public void removeWord(String s) {
WordList r = new WordList();
int x = r.findWord(s);
if (x == -1) {
return;
}
if (x>-1) {
for (int j=0;j<words.length;j++) {
words[j] = words[j+1];
count--;
}
}
return;
}
public int findWord(String w) {
for (int i =0;i<words.length; i++) {
if (w.equals(words[i])) {
return i;
}
}
return -1;
}
public boolean equals(WordList other) {
if (words.length != other.count) {
return false;
} else {
for (int i = 0; i < words.length; i++) {
if (words[i] != other.words[i]) {
return false;
}
}
}
return true;
}
public String toString() {
String s = "There are " + count + " word" + ((words.length == 1)?"":"s") + " in the word list:\n";
for (String w : words) {
s = s + w + "\n";
}
return s;
}
public static void main(String[] args) {
WordList wl = new WordList();
System.out.println(wl.addWord("computer"));
System.out.println(wl.addWord("abacus"));
System.out.println(wl.addWord("computer"));
wl.removeWord("computer");
}
}
First of all. Please consider Arraylist or Map.
Nevertheless i tried to keep changes to the minimal
public class WordList {
public String[] words;
int count;
public WordList() {
count = 0;
words = new String[] {"",""};
}
public int addWord(String w) {
//WordList r = new WordList();
int x = findWord(w);
int y = words.length;
if (x>-1) {
return count++;
}
else if (x==-1) {
if (count < words.length) {
words[count] = w;
}
else if (count == words.length) {
String[] nwords = new String[words.length * 2];
for (int i = 0; i < words.length; i++) {
nwords[i] = words[i];
}
words = nwords;
words[y] = w;
}
count++;
}
return count;
}
public void removeWord(String s) {
//WordList r = new WordList();
int x = findWord(s);
if (x == -1) {
return;
}
if (x>-1) {
for (int j=0;j<words.length;j++) {
if(words.length < j+1 && !words[j+1].isBlank()){
words[j] = words[j+1];
}
}
count--;
}
return;
}
public int findWord(String w) {
for (int i =0;i<words.length; i++) {
if (w.equals(words[i])) {
return i;
}
}
return -1;
}
public boolean equals(WordList other) {
if (words.length != other.count) {
return false;
} else {
for (int i = 0; i < words.length; i++) {
if (words[i] != other.words[i]) {
return false;
}
}
}
return true;
}
public String toString() {
String s = "There are " + count + " word" + ((words.length == 1)?"":"s") + " in the word list:\n";
for (String w : words) {
s = s + w + "\n";
}
return s;
}
public static void main(String[] args) {
WordList wl = new WordList();
System.out.println(wl.addWord("computer"));
System.out.println(wl);
System.out.println(wl.addWord("abacus"));
System.out.println(wl);
System.out.println(wl.addWord("computer"));
System.out.println(wl);
wl.removeWord("computer");
System.out.println(wl);
}
}
The severe ones are:
1. You are working on new instances of wordlist (r) when adding and removing which is absolutely wrong.
2. When removing word you have to check the length of word before going for j+1
You should use a Set, not an array.
That will reduce your code to:
class WordList {
private Set<String> words;
public WordList() {
words = new HashSet<>();
}
public int addWord(String w) {
words.add(w);
return words.size();
}
public void removeWord(String s) {
words.remove(s);
}
public boolean findWord(String w) {
return words.contains(w);
}
public boolean equals(WordList other) {
return this.words.equals(other.words);
}
#Override
public String toString() {
String s = "There are " + words.size() + " word" + ((words.size() == 1)?"":"s") + " in the word list:\n";
for (String w : words) {
s = s + w + "\n";
}
return s;
}
public static void main(String[] args) {
WordList wl = new WordList();
System.out.println(wl.addWord("computer"));
System.out.println(wl.addWord("abacus"));
System.out.println(wl.addWord("computer"));
wl.removeWord("computer");
}
}
Output
1
2
2
I'm doing a homework task that is:
Find a unique vowel in the string that is preceded by a consonant, and this consonant is preceded by a vowel.
Example: "eeaaAOEacafu"
Result is: u
What i already did:
Main.class
public class Principal {
public static void main(String[] args) {
// TODO Auto-generated method stub
Stream str = new Stream();
str.setText("eeaaAOEacafu");
System.out.println(str.returnChar(str.getVowel()));
}
Stream.class
public class Stream {
String text;
char vowel;
public String getText() {
return texto;
}
public void setText(String text) {
this.text = text;
}
public char getVowel() {
return vowel;
}
public void setVowel(char vowel) {
this.vowel = vowel;
}
public boolean isVowel(String str) {
str = str.toLowerCase();
for(int i=0; i<str.length(); i++) {
char c = str.charAt(i);
if(c=='a' || c=='e' || c=='i' || c=='o'|| c=='u') {
return true;
} else {
return false;
}
}
return false;
}
public char returnChar(String str) {
char last;
char next;
char result = '0';
int j=1;
for(int i=0; i<str.length(); i++) {
last = str.charAt(i-1);
next = str.charAt(i+1);
j++;
if(!vogal(str.charAt(i))) {
if(vogal(last) && vogal(next)) {
result = next;
}
}
}
this.setVowel(result);
return result;
} }
This returns: String index out of range: -1
This j=1, was to fix this -1 out of range. It fix but i got new one: out of range 11 because of the next.
The thing is: I have to use pure java and no API.
Can you guys help me?
use regular expressions for the test and locating the character
[aeiouAEIOU][bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ]([aeiouAEIOU])
Use a String as a cheap map to keep track of which vowels you've already seen. Also, keep a count of how many consecutive consonants you've encountered. Then, when you hit a vowel that you haven't seen before preceded by a single consonant you've found your answer.
public static void main(String[] args)
{
String s = "eeaaAOEacafu".toLowerCase();
int consCount = 0;
String seenVowels = "";
for(int i=0; i<s.length(); i++)
{
char c = s.charAt(i);
if("aeiou".indexOf(c) >= 0)
{
if(seenVowels.indexOf(c) == -1)
{
if(consCount == 1)
{
System.out.println("Result: " + c);
break;
}
seenVowels += c;
}
consCount = 0;
}
else consCount++;
}
}
Output:
Result: u
The above works if we take 'unique' to mean that we haven't seen the vowel before. If the vowel has to be unique within the input string then things are a little more complicated. Now we have to keep track of each vowel that meets the original criteria, but remove the solution if we subsequently encounter another instance of the same vowel.
Here's some code to illustrate:
public static void main(String[] args)
{
String s = "afuxekozue".toLowerCase();
int consCount = 0;
String seenVowels = "";
String answer = "";
for(int i=0; i<s.length(); i++)
{
char c = s.charAt(i);
if("aeiou".indexOf(c) >= 0)
{
if(seenVowels.indexOf(c) == -1)
{
if(consCount == 1)
{
answer += c;
}
seenVowels += c;
}
else if(answer.indexOf(c) >= 0)
{
answer = answer.replaceAll(String.valueOf(c), "");;
}
consCount = 0;
}
else consCount++;
}
if(answer.length() > 0)
System.out.println("Result: " + answer.charAt(0));
}
Output:
Result: o
import java.util.Scanner;
public class StringWithoutDuplicate {
public static void stringWithoutDuplicate(String s1)
{
int n = s1.length();
int i = 0;
while(i<n)
{
if(s1.charAt(i) == s1.charAt(i+1))
{
if(s1.charAt(i) == s1.charAt(n-1))
{
System.out.println(s1.charAt(i));
}
i++;
}
else if(s1.charAt(i) != s1.charAt(i+1))
{
if(s1.charAt(i) == s1.charAt(n-1))
{
System.out.println(s1.charAt(i));
}
System.out.println(s1.charAt(i));;
i++;
}
}
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
s.useDelimiter(",");
String s1 = s.next();
System.out.println(s1);
stringWithoutDuplicate(s1);
}
}
The code is giving the output but with an exception
please tell me the error in my code and ways to correct it.
I don't want to change the logic of my code so kindly solve it using this logic only.
ERROR:
Range of your i is from 0 to (n-1) which is same as the range of index of characters in your string s1. This is correct.
But during the last iteration of your while loop, i = n-1
At this point, s1.charAt(i+1) becomes same as s1.charAt(n). This should be giving an error.
public static void stringWithoutDuplicate(String s1) {
int prev = -1;
for (int i = 0, size = s1.length(); i < size; ++i) {
char c = s1.charAt(i);
if (c != prev) {
System.out.println(c);
prev = c;
}
}
}
I'm trying to implement KMP algorithm. My algorithm works correctly with the following example
Text: 121121
Pattern: 121
Result: 1,4
But when Text is 12121 and pattern is the same as above, result just: 1. I don't know if this is the problem of the algorithm or of my implementation?
Other example:
Text: 1111111111
Pattern: 111
Result: 1,4,7
My code is:
public class KMP {
public static void main(String[] args) throws IOException{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String text = reader.readLine();
String pattern = reader.readLine();
search(text,pattern);
}
private static void search(String text,String pattern)
{
int[] Pi = Pi(pattern);
for (int i = 0,q=0; i <text.length()&&q<pattern.length() ; i++,q++) {
while (q>=0 && pattern.charAt(q)!=text.charAt(i))
{
q=Pi[q];
}
if(q==pattern.length()-1) {
System.out.println(i-pattern.length()+2);
q=Pi[q];
}
}
}
private static int[] Pi(String p) {
int[] Pi = new int[p.length()];
Pi[0]=-1;
int i=0;
int j=-1;
while (i<p.length()-1) {
while (j>=0 && p.charAt(j)!=p.charAt(i))
{
j=Pi[j];
}
i++;
j++;
if(p.charAt(j)==p.charAt(i)) Pi[i]=Pi[j];
else Pi[i]=j;
}
return Pi;
}
}
Hope help you.
public int strStr(String source, String target) {
if (source == null || target == null){
return -1;
}
if (source.isEmpty() && !target.isEmpty()){
return -1;
}
if (source.isEmpty() && target.isEmpty()){
return 0;
}
if (target.isEmpty()){
return 0;
}
int index = 0;
int compare_index = 0;
int compare_start_index = 0;
int compare_same_length = 0;
List<Integer> answers = new ArrayList<Integer>();
while (true){
if (compare_same_length ==0){
compare_start_index = compare_index;
}
if (source.charAt(compare_index) == target.charAt(index)){
compare_same_length++;
index++;
} else {
if (compare_same_length >0){
compare_index--;
}
compare_same_length = 0;
index = 0;
}
compare_index++;
if (compare_same_length == target.length()){
answers.add(compare_start_index+1);
compare_same_length=0;
index=0;
}
if (compare_index == source.length()){
//here are answers
for (int i = 0; i < answers.size(); i++) {
int value = answers.get(i);
}
return 1;
}
}
}
Java won't stop reading from input.
I understand that maybe this while loop might have something to do with it:
while(input.hasMoreTokens());
{
array1[counter] = input.nextToken();
counter++;
}
But I don't see why the loop should be a problem because I am already calling .nextToken() which should advance the token.
Here's the full source code:
import java.io.*;
import java.util.*;
class HelloWorld
{
static String ReadLn (int maxLg) // utility function to read from stdin
{
byte lin[] = new byte [maxLg];
int lg = 0, car = -1;
String line = "";
try
{
while (lg < maxLg)
{
car = System.in.read();
if ((car < 0) || (car == '\n')) break;
lin [lg++] += car;
}
}
catch (IOException e)
{
return (null);
}
if ((car < 0) && (lg == 0)) return (null); // eof
return (new String (lin, 0, lg));
}
public static void main (String args[]) // entry point from OS
{
HelloWorld myWork = new HelloWorld(); // create a dinamic instance
myWork.Begin(); // the true entry point
}
void Begin()
{
String idata;
StringTokenizer input;
while ((idata = HelloWorld.ReadLn (255)) != null)
{
input = new StringTokenizer (idata);
String[] array1 = {};
int counter = 0;
while(input.hasMoreTokens());
{
array1[counter] = input.nextToken();
counter++;
}
int[] array2 = {};
for(int a = 0; a < array1.length; a++)
{
array2[a] = Integer.parseInt(array1[a]);
}
int[] array3 = {};
for(int b = 0; b < array2.length; b++)
{
if ( array2[b] != 42)
{
array3[b] = array2[b];
}
else
{
break;
}
}
String string = "";
for( int c = 0; c < array3.length; c++)
{
if( c < array3.length - 1)
{
string += array3[c] + "\n";
}
else
{
string += array3[c];
}
}
System.out.println(string);
}
}
}
You have a stray semicolon at the end of the while:
while(input.hasMoreTokens());
^ REMOVE THIS