How do I check if a string array is full [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I want to check if there is a value assigned to every part of my string array e.g. If my string array is String[8], I need to check if there is 8 different values in the string array.

You need to iterate through each element of the array and check if it is null, if none is null then the list is full.
boolean isFull = true;
for(String s : yourarray) {
if(s == null) {
isFull = false;
break;
}
}
If each value needs to be different then you have to have nested loop. (A bit unclear in the question)
boolean isFull = true;
for(String s : yourarray) {
for(String t : yourarray) {
if(s == null || s.equals(t)) {
isFull = false;
break;
}
}
}

You want to know if the characters that make up the string are all different. For this, I recommend the following methods: String#length, String.charAt, String.indexOf and a loop over all characters, i.e. from 0 to n-1, where n is the string length.

You can do it like this: Here str_array (just initialized for example purpose) is the string array, and empty_indexes is the list of indexes of String array that are empty.
String str = "This is the example string";
String[] str_array = str.split(" ");
ArrayList<Integer> empty_indexes = new ArrayList<Integer>();
for (int i = 0; i < str_array.length; i++) {
if (str_array[i] != null) {
if (str_array.equals("")) {
empty_indexes.add(i);
}
} else {
empty_indexes.add(i);
}
}

Use a for loop:
boolean isFull = true;
for(int i = 0;i<yourarray.length;i++)
{
if(yourarray[i] != null && !yourarray[i].isEmpty())
{
isFull = false;
break;
}
}

Related

Blank Screen after launching/debugging ArrayList exercise in Eclipse [closed]

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);
}

Expansion of Molecular notation of Chemical Formula [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I looked around a bit for a solution to parsing out a chemical formula that contained molecular components that may have their own suffixes for the purposes of being able to parse a formula for its complete atomic fraction.
How would one do this in Java?
Not having been able to find a way to do this in short order (and not having done a fun algorithm in a while) I settled on a stack implementation, as it's actually less complicated than a math operation stack.
Going backward through the stack, you only have to be aware of a few things, as this is fundamentally a modified implementation of a common solution to parsing a mathematical statement.
1) Your integer suffix can be built of multiple characters
2) Your integer suffix could be a multiplier (next character being a ")")
3) You need to handle for implicit "1"s
The implementation pops characters off one stack and pushes only letters and numbers onto your "return stack".
String expandFormula(String s){
Stack<Character> stack = new Stack();
Stack<Character> hanoi = new Stack();
char[] ca = s.toCharArray();
Character c;
List<Integer> multipliers = new ArrayList();
String multiBuff;
int val;
boolean flag;
for (int i = 0; i < ca.length; i++)
stack.push(ca[i]);
while(!stack.isEmpty()){
c = stack.pop();
if (Character.isLetter(c)){
try{
//previous parse was end of Symbol, implicit "1"
flag = Character.isUpperCase(hanoi.peek());
}
catch(EmptyStackException ese){ //change exception
flag = false;
}
//push implicit 1
if (flag){
stack.push(c);
stack.push('1');
}
//continue as usual
else
hanoi.push(c);
}
//begin number parsing
else if(Character.isDigit(c)){
flag = false;
multiBuff = c +"";
//parse the integer out
while(Character.isDigit(stack.peek())){
c = stack.pop();
multiBuff = c + multiBuff;
}
//if next char is ), then value is a suffix
if (stack.peek() == ')'){
flag = true;
stack.pop();
multipliers.add(Integer.parseInt(multiBuff));
//pop successive )s
while(stack.peek() == ')'){
stack.pop();
multipliers.add(1);
}
}
if(Character.isLetter(stack.peek())){
val = flag ? 0 : Integer.parseInt(multiBuff);
//get full value of
for(Integer i : multipliers){
if (val == 0)
val = i;
else
val *= i;
}
//trim and push first decibit
while(val > 0){
hanoi.push(Character.forDigit(val % 10, 10));
val /= 10;
}
}
}
//end of nest, remove most recent multiplier
else if(c == '(')
try{
multipliers.remove(multipliers.size()-1);
}
catch(ArrayIndexOutOfBoundsException aioobe){
}
}
multiBuff = "";
while(!hanoi.isEmpty())
multiBuff += hanoi.pop();
return multibuff;
}
This solution can be converted directly to your output string by:
1) Change "hanoi" to string
2) Change "hanoi.push(c)" to hanoi = c + hanoi
3) Change "hanoi.peek()" to "hanoi.charAt(0)"
4) Change Exceptions as necessary (or use general exceptions anyway)
5) Just return hanoi instead of the multibuff thing at the bottom.

I seem to get a null when my code runs [closed]

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

Creating a boolean method to check for consecutive numbers [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I need help writing a method that checks if numbers and text are consecutive. It needs to return a boolean value of true if an input like inputted deFgh or 456789 and false for anything else not consecutive. I don't understand how to make the loop be true for cases like xyZaBcD and 890123 or cbazyx
try this code:
public static boolean isConsecutive(final String s) throws IllegalArgumentException
{
if (null == s) throw new IllegalArgumentException();
if (s.length() <= 1) return true;
final String lc = s.toLowerCase();
char c = lc.charAt(0);
for (int cc=1; cc<lc.length(); cc++)
if ( (c+1) != lc.charAt(cc) )
return false;
else
c++;
return true;
}
public static void main(String[] args)
{
try
{
System.out.println(isConsecutive("456789"));
System.out.println(isConsecutive("deFgh"));
System.out.println(isConsecutive("xyZaBcD"));
System.out.println(isConsecutive("890123"));
}
catch(final Exception e)
{
e.printStackTrace();
}
}
but I really suggest you do not show it to teacher, as it will have more questions, use it only as direction to your own code
This can be implemented at easiest way:
public class Check {
private static boolean checkConsecutive(String str) {
str = str.toLowerCase();
if (str.length() == 1) return true;
for (int i = 1; i < str.length(); i++) {
String first = str.substring(i, i+1);
String beforeFirst = str.substring(i-1, i);
if (beforeFirst.compareTo(first) > 0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
Check obj = new Check();
System.out.printf("abcdef is: %s%n", obj.checkConsecutive("abcdef"));
System.out.printf("12345 is: %s%n", obj.checkConsecutive("12345"));
System.out.printf("54321 is: %s%n", obj.checkConsecutive("54321"));
System.out.printf("fedcba is: %s%n", obj.checkConsecutive("fedcba"));
}
}
Output will be next:
abcdef is: true
12345 is: true
54321 is: false
fedcba is: false
This line str.substring(i, i+1) return exactly one letter, and we can use compareTo() from String class it compares consecutive by itself.
Just iterate over string and check sequence of char codes. If needed, use toLowerCase() method.
You can cast (int) to the characters in the loop. If the integer is between 48 and 57 inclusive, that means that the character is a digit.
See ASCII Table for the integers given by casting from char.

Algorithm:Find first non-repeated character in an input string [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
I have seen this and this question but mine is different. I want to write an efficient code for it in java. I came up with 2 solutions:
Approach 1.
find_first_reapeted(char[] input)
{
HashMap<Character,Integer> myhash = new HashMap<Character,Integer> ();
for(int i=0;i<input.length;i++)
{
if(myhash.containsKey(input[i])
myhash.put(input[i],2); //just put 2 even if it is more than 2
else
myhash.put(input[i],1);
}
for(int i=0;i<input.length;i++)
{
if(myhash.getValue(input[i])==1)
return input[i];
}
}
Approach 2.
find_first_reapeted(char[] input)
{
int[] allchars = new int[26];
for(int i=0;i<input.length;i++)
{
allchars[input[i]-'a'] += 1;
}
for(int i=0;i<input.length;i++)
{
if(allchars[input[i]-'a']==1)
return input[i];
}
}
First is there any better solution? (int term of time and space complexity)?
If not which one of the the above is better? I'm not sure about the space complexity of hashmap!
How about
The first repeating character.
char find_first_repeated(char[] input) {
BitSet bs = new BitSet();
for(char c : input) {
if(bs.get(c))
return c;
bs.set(c);
}
return '\uffff'; // invalid char
}
The first non repeating character, I would use the second approach but using the for-each loop to make it cleaner.

Categories