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 8 years ago.
Improve this question
basically id like a few hints or tips on how to solve this question.. maybe a few things which i could read up on about arraylists and loop which would make it simple for me to understand!..
the question is :
Processing an ArrayList of Characters:
cList is an ArrayList of objects of type Character that has been declared and intialised. Write a loop that will count the Characters that are not spaces and print the number out to the terminal window.
and second question would be:
Looping through a String
Assuming that a variable has been declared like this:
String s;
and that a value has already been assigned to s, write a loop statement that will print the characters of s in reverse order (so if s = "HELLO", your loop should print "OLLEH").
for the first question i tried to do:
public ArrayList()
public static void main(String[] args) {
int countBlank;
char ch;
public ArrayList (int cList)
{
int cList = ;
while(cList ){
System.out.println(cList);
}
}
and second question :
i have no idea, but a read up would be great!
thank you!
You could start by reading up on ArrayList Javadoc and documentation on mindprod.
In your example you haven't declared cList as arraylist nor filled it with Character objects. Instead of a while you might look into for. To get the characters in a String, String.toCharArray() might be of use.
For your first question, you want to loop through the list and count the number of times a character isn't a space.
int counter = 0;
for (Character c : characters) {
if (c == null {
continue; // Note: You can have null values in an java.util.ArrayList
}
if (!Character.isSpaceChar(c)) {
counter++;
}
}
System.out.println(counter);
For your second question:
for (int i = s.length() - 1; i >= 0; i--) {
System.out.print(s.charAt(i));
}
An arraylist is probably too fat for that:
import java.text.CharacterIterator;
import java.text.StringCharacterIterator;
public class CI {
private static final String text = "Hello";
public static void main(String[] args) {
CharacterIterator it = new StringCharacterIterator(text);
for (char ch = it.last(); ch != CharacterIterator.DONE; ch = it
.previous()) {
System.out.print(ch);
}
}
}
Answer to Question 1:
import java.util.*;
public class ProcessListOfChars{
public static int printCharsInListIgnoreSpaces(List<Character> cList){
int count =0;
for(Character character:cList){
// System.out.println("Value :"+character);
if(character!=null &&!character.toString().trim().equals("")){
++count;
}
}
return count;
}
public static void main(String... args){
List<Character> cList = new ArrayList<Character>();
cList.add('c'); //Autoboxed char to Charater Wrapper Class
cList.add(' '); //Space character
cList.add('r');
cList.add('b');
cList.add(' ');
int count = printCharsInListIgnoreSpaces(cList);
System.out.println("Count of Characers :"+count);
}
}
Related
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 2 years ago.
Improve this question
//. I was writing code to get first letters of all words in a string.
public class Firstword {
static void func(String str)
{
String k ="";
String str1=" "+str;
char[] ch= str1.toCharArray();
for(int i=0;i<ch.length-2;i++)
{
if(i != ch.length-1)
while(i<ch.length && ch[i]!=' ')
i++;
k=k+ch[i+1];
}
System.out.print(k);
System.out.print(ch.length);
}
public static void main(String[] args)
{
String str = "Hello Banner jee";
func(str);
}
}
Your error is here:
k=k+ch[i+1];
You are getting out of bounds.
Because of this:
while(i<ch.length && ch[i]!=' ')
i++;
Something like this will work -
static void func(String str)
{
String [] words = str.split(" ");
for(int i = 0; i < words.length ;i++){
System.out.println(words[i].charAt(0));
}
}
public static void main(String[] args)
{
String str = "Hello Banner jee";
func(str);
}
Output -
H
B
j
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 3 years ago.
Improve this question
How can i seperate this String:
"thisisanexampleforthisproblemicantsolvetestes"
To this array:
{"thisi","sanex","ampl","efor","this","prob","lemi","cant","solv","etes","tes"}
I want to seperate the first 10 letters in the String into 2 elemnts in an array and the rest should be every 4 letters, to one elemnt in an array.
I hope you can help me. I tried this all day but still didnt solve it
Assuming your input string length >= 10 you can do something like below using streams:
String str = "thisisanexampleforthisproblemicantsolvetestes";
String[] splited = Stream.of(str.substring(0, 10).split("(?<=\\G.{5})"),
str.substring(10).split("(?<=\\G.{4})"))
.flatMap(e -> Arrays.stream(e))
.toArray(String[]::new);
System.out.println(Arrays.toString(splited));
where the regex "(?<=\\G.{n})" is used to split a string at each nth char
More simple to understand:
Results in: thisi, sanex, ampl, efor, this, prob, lemi, cant, solv, etes, tes
public static List<String> strangeThingsDo(String str)
{
List<String> li = new ArrayList<>();
int len = str.length();
if (len <= 5)
{
li.add(str);
return li;
}
if (len <= 10)
{
li.add(str.substring(0,5));
li.add(str.substring(5));
return li;
}
li.add(str.substring(0,5));
li.add(str.substring(5,10));
String s,rest = str.substring(10);
int restlen = rest.length();
int end = 0;
for (int i = 0; i < restlen;i += 4)
{
end = i + 4;
if (end > restlen)
{ s = rest.substring(i);
li.add(s);
break;
}
s = rest.substring(i,end);
li.add(s);
}
System.out.println("---: " + li );
return li;
}
The following code will show you how to split a string by numbers of characters. We create a method called splitToNChars() that takes two arguments. The first arguments is the string to be split and the second arguments is the split size.
This splitToNChars() method will split the string in a for loop. First we’ll create a List object that will store parts of the split string. Next we do a loop and get the substring for the defined size from the text and store it into the List. After the entire string is read we convert the List object into an array of String by using the List‘s toArray() method.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class SplitStringForEveryNChar {
public static void main(String[] args) {
String text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
System.out.println(Arrays.toString(splitToNChar(text, 3)));
System.out.println(Arrays.toString(splitToNChar(text, 4)));
System.out.println(Arrays.toString(splitToNChar(text, 5)));
}
private static String[] splitToNChar(String text, int size) {
List<String> parts = new ArrayList<>();
int length = text.length();
for (int i = 0; i < length; i += size) {
parts.add(text.substring(i, Math.min(length, i + size)));
}
return parts.toArray(new String[0]);
}
}
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'm really new to java and just learning. I'm doing a java assignment and I don't quite understand; I am supposed to create a method that will take in a String array and return a randomly selected Sting from that array. here are the exact instructions:
*getRandomWord --> consumes an array of Strings and selects
(returns) one of the words at random.
signature: String getRandomWord (String [] array)
*
Then I think I have to create another method. I doubt an you have two methods named the same thing but the instructions say:*getRandomWord --> consumes an array of Strings and an integer (len).
This method selects a word from the array whose
length is more than len. If the length of the word
selected is less than len, then this method selects
another word at random. This is repeated 500 times
until a word is found/returned or no word is found
in which case this method will return null.
signature: String getRandomWord (String [] array, int len)
*
As I said I'm really new so help is appreciated.
Since this is an assignment I will only give you pointers to write the method yourself. The algorithm to use in String getRandomWord (String [] array)is elucidated below:
Calculate the length of the array. See How to find length of a string array
Generate the index of the random word from the array's length. See Getting random numbers in java
Get and return the random word from the array.
All these should be done in not more than 3 lines of code. Good Luck!
I would suggest to do it yourself. If you don't get, code is here :) Use the Random API. nextInt() method of Random method gives the Random value, which can be used as index to return random String from Arra.
Below is complete code of 2 methods:
import java.util.Random;
public class TestJava {
public static void main(String[] args) {
String[] strArray = { "first", "second", "third" };
System.out.println(getRandomWord(strArray));
}
static String getRandomWord(String[] array) {
Random random = new Random();
int index = random.nextInt(array.length);
return array[index];
}
static String getRandomWordWithLength(String[] array, int len) {
Random random = new Random();
for (int i = 0; i < 500; i++) {
int index = random.nextInt(3);
String selectedString = array[index];
if (selectedString.length() > len)
return selectedString;
}
return null;
}
}
Try to do yourself at first as it is an assignment. Take help from the code below if you failed it to do yourself.
private String getRandomWord(String[] array) {
int idx = new Random().nextInt(array.length);
return (array[idx]);
}
private String getRandomWord(String[] array, int len) {
String word = null;
for (int i = 1; i <= 500; i++) {
word = getRandomWord(array);
if (word.length() > len) {
break;
} else {
word = null;
}
}
return word;
}
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 have a class like below
public class EXOR{
public static void conv(){
String [] Parray={"243f6a88","85a308d3","13198a2e","03707344","a4093822","299f31d0","082efa98",
"ec4e6c89","452821e6", "38d01377", "be5466cf","34e90c6c","c0ac29b7","c97c50dd","3f84d5b5","b5470917","9216d5d9","8979fb1b"};
String binAddr[]=new String[18];
for (int i=0;i<18;i++)
{
int x[]=new int[18];
binAddr[i]= Integer.toBinaryString(Integer.parseInt(Parray[i],16));
System.out.println("binernya : " +binAddr[i]);
}
}
public static void main(String[] args){
new EXOR().conv();
}
}
and I want to convert that array to binary array format.
I want to get output like below
for example
00100100001111110110101010001000
10000111101000110000100011010011
................................
How to fix this problem?
I suppose while executing your code you must've got a number point exception. This occurs when the Hexadecimal string is out of the range of Integer.
You can use:
binAddr[i]= (new BigInteger(Parray[i],16)).toString(2);
instead of
binAddr[i]= Integer.toBinaryString(Integer.parseInt(Parray[i],16));
This will solve your problem for quick reference
Big Integer Documentation
Code:
public class EXOR {
public static void conv(){
String [] Parray={"243f6a88","85a308d3","13198a2e","03707344","a4093822","299f31d0","082efa98",
"ec4e6c89","452821e6", "38d01377", "be5466cf","34e90c6c","c0ac29b7","c97c50dd","3f84d5b5","b5470917","9216d5d9","8979fb1b"};
String [] binAddr = new String[Parray.length];
for (int i = 0; i < binAddr.length; i++)
{
int strLen = Parray[i].length();
binAddr[i] = "";
for(int j = 0; j < strLen; j++) {
String temp = Integer.toBinaryString(
Integer.parseInt(String.valueOf(
Parray[i].charAt(j)), 16));
// Pad with leading zeroes
for(int k = 0; k < (4 - temp.length()); k++) {
binAddr[i] += "0";
}
binAddr[i] += temp;
}
System.out.println("Original: " + Parray[i]);
System.out.println("Binary: " + binAddr[i]);
}
}
public static void main(String[] args){
conv();
}
}
First few lines of Output:
Original: 243f6a88
Binary: 00100100001111110110101010001000
Original: 85a308d3
Binary: 10000101101000110000100011010011
We have Integer.MAX_VALUE = 2147483647
But, the 2nd item "85A308D3" = 2242054355. It exceed the capability of an Integer.
So, you use Integer.parseInt(85A308D3) will cause java.lang.NumberFormatException.
To fix it, change your code to use Long instead of Integer
binAddr[i] = Long.toBinaryString(Long.parseLong(Parray[i], 16));
Hope this help!
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 8 years ago.
Improve this question
//This program determines if the input string is a palindrome
import java.util.*;//importing all the methods from java.util class
import static java.lang.System.out;
public class Pallindrome {
public static void main(String[] args) {
#SuppressWarnings("resource")
Scanner input= new Scanner(System.in);
String pallindrome;
out.println("Enter a string: ");
pallindrome= input.nextLine();
ArrayList<String> pall= new ArrayList<String>();
buildAL(pall, pallindrome);
display(pall);
if(isPalendrome(pall))
out.println(pallindrome + " is a pallindrome");
else
out.println(pallindrome + " is not a pallindrome");
}
static void display(ArrayList<String> arr1){ //this method is for displaying the array list
for(int i=0; i<arr1.size();i++)
out.print(arr1.get(i));
out.println();
}
static void buildAL(ArrayList<String> arr2, String word){ //this is for building the array with the entered word
for(int i=0;i<arr2.size();i++)
arr2.add(word.charAt(i)+ "");
}
static Boolean isPalendrome(ArrayList<String> arr3){ //it will test if the word is pallindrome
ArrayList<String> rarr3= new ArrayList<String>();
rarr3.addAll(arr3);
Collections.reverse(rarr3);
for(int i=0;i<rarr3.size();i++)
if(!(rarr3.get(i).equals(arr3.get(i))))
return false;
return true;
}
}
When I run this code it shows the same output. please point out the error.
It's unclear what the problem is but your for loop doesnt over the letters in word as the termination condition is based on the empty List size passed to the buildAL method. Replace
for (int i = 0; i < arr2.size(); i++)
with
for (int i = 0; i < word.length(); i++) {
Below
static void buildAL(ArrayList<String> arr2, String word){
for(int i=0;i<arr2.size();i++)
arr2.add(word.charAt(i)+ "");
}
arr2.size() is 0 as you don't have any element in the list. Either add the word to the list or do word.length() in for loop.
Also, if I have to do the same thing I would do something like -
After reading the string from the scanner, Simply do
StringBuilder sb = new StringBuilder("your String");
if ("yourString".equals(sb.reverse().toString())) {
//or you can use equalsIgnoreCase also if that fits your requirement
//its a palindrome
} //Otherwise, not.