Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I wrote a simple program in Java which writes a word backwards. Trying to check if "hello" works. In if-statement I'm checking that string is equal to "olleh". Could anyone see why the if statement won't execute.
public class MyProgram {
public static void main(String[] args) {
String x = "hello";
System.out.println(back(x));
}
public static String back(String str) {
String y = " ";
String temp = " ";
for (int i = str.length() - 1; i >= 0; i--) {
char lets = str.charAt(i);
y += Character.toString(lets);
System.out.println(y);
if (y.equals("olleh")) {
System.out.println("nice");
}
}
return y;
}
}
Try this it will work
public class MyProgram
{
public static void main(String[] args)
{
String x = "hello";
System.out.println(back(x));
}
public static String back(String str )
{
String temp = "";
for (int i = str.length() - 1; i >= 0; i--) {
char lets = str.charAt(i);
temp = temp + lets;
}
if (temp.equals("olleh")) {
System.out.println("nice");
}
return temp;
}
}
If you will initialize y variable to empty string instead of space your if-statement will execute and print "nice". Also you do not need a temp string as you don't use it. You probably want to return you reverted string back (alternatively you can make your method void and remove the return statement).
public static String back(String str) {
String y = "";
for (int i = str.length() - 1; i >= 0; i--) {
char lets = str.charAt(i);
y += Character.toString(lets);
System.out.println(y);
if (y.equals("olleh")) {
System.out.println("nice");
}
}
return y;
}
By the way, it's better to use StringBuilder when you're concatenating strings in a loop.
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
Here is my code:
public class Code {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
reverse(-123);
}
public static int reverse(int x) {
String str = Integer.toString(x);
char c[] = new char[str.length()];
for (int i = 0; i < str.length(); i++) {
c[i] = str.charAt(str.length() - 1 - i);
}
if (c[str.length()-1] == '-') {
for (int i=c.length-2; i >=0; i--) {
c[i+1] = c[i];
}
c[0] = '-';
}
String n = new String(c);
int re = Integer.parseInt(n);
return re;
}
}
I'm doing a Java exercise which is to change the order of an Integer to reverse with the '-' in it, but when I run the program, it doesn't print out anything, please help me solve this!!
public static void main(String[] args) {
System.out.println(reverse(-123));
}
should work now, you missed print statement.
To print we need to add a print statement i.e,
System.out.println(reverse(-123));
Just add System.out.println where you called the function reverse
public class Code {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
System.out.println(reverse(-123));
}
public static int reverse(int x) {
String str = Integer.toString(x);
char c[] = new char[str.length()];
for (int i = 0; i < str.length(); i++) {
c[i] = str.charAt(str.length() - 1 - i);
}
if (c[str.length()-1] == '-') {
for (int i=c.length-2; i >=0; i--) {
c[i+1] = c[i];
}
c[0] = '-';
}
String n = new String(c);
int re = Integer.parseInt(n);
return re;
}
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I'm learning ArrayList in Java. I'm trying to add and print elements in an Array with various methods. Trying to run or compile the above code results in 2 "placeholder" print and the console hanging when trying to set String = Scanner value. What's wrong? Here's the code:
public class Arraylist {
private ArrayList<String> list = new ArrayList<>();
public void addIt(String str) {
list.add(str);
}
public String toStrings() {
int i = list.size();
String prova = new String();
while ((i < list.size()) && (i >= 0)) {
prova = list.get(i);
i--;
}
return prova;
}
public static void main(String args[]) {
Arraylist ciccio = new Arraylist();
Scanner in = new Scanner(System.in);
System.out.println("Placeholder");
String str;
System.out.println("Placeholder");
str = in.next();
System.out.println("Placeholder");
while (!str.equals("bye")) {
System.out.println("Add new values");
ciccio.addIt(in.next());
}
System.out.println("Printing");
String str2;
str2 = ciccio.toStrings();
in.close();
}
}
It will never enter the while. i should start on list.size() - 1 not list.size(). Also, you might want to append to that string, not replace it.
public String toStrings() {
int i = list.size() - 1;
String prova = new String();
while ((i < list.size()) && (i >= 0)) {
prova += list.get(i);
i--;
}
return prova;
}
Also, it will never exit this loop since str is only assigned once.
while (!str.equals("bye")) {
System.out.println("Add new values");
ciccio.addIt(in.next());
}
Fix:
boolean control = true;
while (control) {
System.out.println("Add new values");
String temp = in.next();
if (temp.equals("bye"))
control = false;
else
ciccio.addIt(temp);
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I currently have an assignment where we have the entire (swedish) alphabet in lower case as a string, and we should convert every other character to upper case. This is where I am right now:
public static void main(String[] args) {
String alphabet = "abcdefghijklmnopqrstuvwxyzåäö";
System.out.println(alphabet);
for (int i = 0; i < 29; i = i + 2) {
char result = alphabet.charAt(i);
alphabet.toUpperCase(result);
}
System.out.println(alphabet);
}
The problem now is that alphabet.toUpperCase(result); gives me an error that I can't convert char to locale. How do I fix this?
If you want to get the uppercase of a char, you should use Character.toUpperCase(c), not String's toUpperCase.
So, I think you might be looking for something like this:
public static void main(String[] args) {
String alphabet = "abcdefghijklmnopqrstuvwxyzåäö";
System.out.println(alphabet);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < alphabet.length(); i++) {
char c = alphabet.charAt(i);
sb.append(i % 2 == 0 ? Character.toUpperCase(c) : c);
}
String result = sb.toString();
System.out.println(result);
}
Output:
abcdefghijklmnopqrstuvwxyzåäö
AbCdEfGhIjKlMnOpQrStUvWxYzÅäÖ
Since Strings are immutable, you have to create a new String to get what you want. An efficient way of doing this is with a StringBuilder.
Edit:
Another way to do it without StringBuilder and perhaps a more intuitive way is to convert the String to an array of chars, which makes it mutable. In the end, you just convert it back to a String. The result would look like this:
public static void main(String[] args) {
String alphabet = "abcdefghijklmnopqrstuvwxyzåäö";
System.out.println(alphabet);
char[] chars = alphabet.toCharArray();
for (int i = 0; i < alphabet.length(); i+=2) {
chars[i] = Character.toUpperCase(chars[i]);
}
String result = new String(chars);
System.out.println(result);
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I want to eliminate vowels from a String, I can eliminate them, but I fail to return them to main(). I got the exact output by using the following code.
String string = "ajeIokluj";
String s = string.replaceAll("[aeiouAEIOU]","");
return s;
It will be great if the required output came by using for loop.
Hope you have written the code similar to below considering your fail to return statement .
public static void main(String[] args) {
String string = "ajeIokluj";
String s = eliminateVowels(string);
System.out.println(s);
}
private static String eliminateVowels(String string) {
String s = string.replaceAll("[aeiouAEIOU]","");
return s;
}
If you did it works perfectly fine and if not use above as reference ;)
Based on your comments since you looking for specifically using for loop (Which is not recommended) please find code below.
public static String removeVowels(final String string){
final String vowels = "AaEeIiOoUu";
final StringBuilder builder = new StringBuilder();
for(final char c : string.toCharArray())
if(vowels.indexOf(c) < 0)
builder.append(c);
return builder.toString();
}
public class main {
public static String removeVowels(String word) {
String ret = "";
String realRet = "";
for (int i = 0; i < word.length(); i++) {
if ("aeiouAEIOU".indexOf(word.charAt(i)) == -1) {
ret += word.charAt(i);
}
}
realRet = realRet + ret.charAt(0) + ret.charAt(1);
return realRet.toLowerCase() ;
}
public static void main(String[] args) {
String pass = removeVowels("Your String");
for(int i=0 ; i < 3; i++) {
pass = pass + (int) (Math.random() * 100) ;
}
System.out.println(pass);
}
}
Try this it may work you!!
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
import java.util.StringTokenizer;
public class PigLatins {
String str1;
int vowelIndex;
String[] vowels = {"a","e","i","o","u","A","E","I","O","U"};
String counter = "";
public String pigLatin(String str) {
String[] result = str.split("\\s");
for (int x=0; x<result.length; x++) {
for(int i = 0;i<vowels[i].length();i++) {
if(!result[x].contains(vowels[i])) {
str1 = result[x]+"ay";
}
else if(result[x].startsWith(vowels[i])) {
str1 = result[x]+"ay";
}
for(int j = 0;j<result[x].length();j++)
if(Character.toString(result[x].charAt(j)) == vowels[i]) {
vowelIndex = j;
break;
}
if(vowelIndex > 0 && !result[x].startsWith(vowels[i]) && result[x].contains(vowels[i])) {
str1 = result[x].substring(1,vowelIndex) + result[x].substring(0,1) + "ay";
}
}
counter+=str1;
}
return counter;
}
}
At this part result[x].substring(1,vowelIndex) in the if statement, it seems to return null, why is it wrong and how could I fix it? (I removed the driver class as stackoverflow told me to I had too much code)
You should change :
for(int i = 0;i<vowels[i].length();i++)
to
for(int i = 0;i<vowels.length;i++)
Since you want to iterate over all the vowels in the array.
vowels[i].length() will always give you 1, since it's the length of the i'th String in the vowels array.
Beside that, it would make more sense to change the vowels array from String[] to char[].
the problem here is that the vowelIndex is 0 while you start in index 1 for the substring.
i don't quite understand what you are trying to achive but you need to check in you if statement the value of vowelIndex:
if(vowelIndex > 0 && !result[x].startsWith(vowels[i]) && result[x].contains(vowels[i]))
the whole function should be
public String pigLatin(String str) {
String[] result = str.split("\\s");
for (int x=0; x<result.length; x++) {
for(int i = 0;i<vowels[i].length();i++) {
if(!result[x].contains(vowels[i])) {
str1 = result[x]+"ay";
}
else if(result[x].startsWith(vowels[i])) {
str1 = result[x]+"ay";
}
for(int j = 0;j<result[x].length();j++)
if(Character.toString(result[x].charAt(j)) == vowels[i]) {
vowelIndex = j;
break;
}
if(vowelIndex > 0 && !result[x].startsWith(vowels[i]) && result[x].contains(vowels[i])) {
str1 = result[x].substring(1,vowelIndex) + result[x].substring(0,1) + "ay";
}
}
counter+=str1;
}
return counter;
}
also you should not use an array of strings of you need an array of charecters, or if i understand correctly you should use a set of charecters