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);
}
Related
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 4 years ago.
Improve this question
I am new towards coding, so I've managed to create a code that allows me to reverse words, however, I don't fully understand the for loop construct, because I created this using online resources.
public class word {
public static String rWords(String input) {
String[] split = input.split("");
String output = " ";
for (int i = split.length - 1; i >= 0; i--) {
output += (split[i] + "");
}
return output.trim();
}
}
Say there is already a main class that contains a string value of input, this is another class called word, I understand that making it public static string means it's public and static means it's not declared in instances. It contains one parameter with the input from main class, the output is empty for my for loops results to go into that, however, how does the for loop allow my input to be reversed and return.trim do?
Why don't you use out-of-box approach? E.g. StringBuilder already has a method reverse():
public static String reverseWords(String str) {
return Arrays.stream(str.trim().split("\\s+"))
.map(word -> new StringBuilder(word).reverse().toString())
.collect(Collectors.joining(" "));
}
But you string can do it with old Java:
public static String reverseWords(String str) {
// using StringBuilder for multiple string concatenation
StringBuilder buf = new StringBuilder(str.length());
for (String word : str.trim().split("\\s+")) {
// add space if word is not first one
if (buf.length() > 0)
buf.append(' ');
// add each word from end to beginning
for (int i = word.length() - 1; i >= 0; i--)
buf.append(word.charAt(i));
}
return buf.toString();
}
In case you need swap words in the sentence, principle is the same:
public static String reverseWords(String str) {
StringBuilder buf = new StringBuilder(str.length());
String[] words = str.trim().split("\\s+");
for (int i = words.length - 1; i >= 0; i--) {
if (buf.length() > 0)
buf.append(' ');
buf.append(words[i]);
}
return buf.toString();
}
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.
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
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 8 years ago.
Improve this question
I've been having a bit of an issue with my assignment. After reading from an input.txt file, I've created an array in which all of the information has been stored in, but for some reason I seem to be unable to compare them individually. I've tried equals() and contains() I can't think of anything else that would work. what I'm trying to achieve.
public static void readFromFile(String filePath) throws IOException{
BufferedReader inputFile = new BufferedReader(new FileReader(filePath));
String inputText = null;
List<String> list = new ArrayList<String>();
String[] splited = null;
//splitting the text file
while((inputText = inputFile.readLine())!= null) {
splited = inputText.split("[;^:]");
for (String part : splited) {
list.add(part);
}
}
String [] stockArr = list.toArray(new String[list.size()]);
// verify contents of array
for(int index = 0; index < stockArr.length;index++) {
System.out.println(stockArr[i]);
}
for (int i = 0; i > stockArr.length; i++) {
if(stockArr[i].equals("BusinessContact")) {
System.out.println("test");
}
}
}
Now if I were to print this, it does not print "test" but rather only
BusinessContact
firstName=Victor
middleName=Garces
lastName=Guana
Address
addressType=WORK
streetName=Athabasca Hall
streetNumber=2-32
apartmentNumber=4-52
city=Edmonton
postalCode=T6G 2E8
country=Canada
Check your run-condition for the second for-loop:
for (int i = 0; i > stockArr.length; i++){
if(stockArr[i].equals("BusinessContact")){
System.out.println("test");
}
}
I think you rather meant
for (int i = 0; i < stockArr.length; i++){
if(stockArr[i].equals("BusinessContact")){
System.out.println("test");
}
}
The last for loop should have a < in its condition:
for (int i = 0; i < stockArr.length; i++){