I am doing a project in android ,and i have a problem My array list values like this
[men-1, men-2, men-3, women-1, women-2, women-3]
How can I split these values in different arrays? i.e how can I save men-1,men-2,men-3 in one array and women-1,women-2,women-3 in other array?
It is hard to help you without details but you should probably
create separate Lists for man and woman elements,
iterate over all elements of your lists
in case of list is string you can determine its gender using element.startsWith("man")
in case elements are objects of Man or Woman classes you can use instanceof operator like if (element instanceof Man){listOfMans.add(element)}
now if you want to place ell elements in separate arrays you can use toArray(T[] array) method from each List instance.
the below code may help you
import java.util.Arrays;
public class Test{
public static void main(String[] args) {
String[] input = new String[] {"men-1", "men-2", "men-3", "women-1", "women-2", "women-3"};
int arr1Size=getCount(input, "women");
String[] arr1 = new String[arr1Size];
String[] arr2 = new String[input.length-arr1Size];
int i=0,j=0;
for(String str: input){
if(str.contains("women")){
arr1[i] = str;
i++;
}else{
arr2[j] = str;
j++;
}
}
System.out.println(Arrays.deepToString(arr1));
System.out.println(Arrays.deepToString(arr2));
}
public static int getCount(String[] input, String find){
int count=0;
for(String str: input){
if(str.contains(find)){
count++;
}
}
return count;
}
}
If those are the object of a class then you can easily do it using instanceOf operator... Otherwise below code can help you.. you can do it using arrays only as well as using arraylist
/**
*
*/
package com.sharique.test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
/**
* #author Sharique
*
*/
public class Test {
/**
* #param args
*/
//List<Integer> list = new ArrayList<>();
//int[] arr = new int[10];
//int[] ar1= arr.clone();
public void usingArrays(){
StringBuffer sb1 = new StringBuffer("Men");
String[] arrays = {"Men-1","Men-2","Men-3","Women-1","Women-2","Women-3"};
String[] arrOfMen = new String[3];
String[] arrOfWomen = new String[3];
String str=null;
int count1=0;
int count2=0;
for(int i=0;i<arrays.length;i++){
str=arrays[i];
if(str.contains(sb1)){
arrOfMen[count1++]=str;
}else{
arrOfWomen[count2++]=str;
}
}
for(int i=0;i<arrOfMen.length;i++)
System.out.print(arrOfMen[i]+" ");
//For a new Line
System.out.println();
for(int i=0;i<arrOfWomen.length;i++)
System.out.print(arrOfWomen[i]+" ");
}
public void usingArrayList(){
String[] arrays1 = {"Men-1","Men-2","Men-3","Women-1","Women-2","Women-3"};
List<String> list = new ArrayList<>(Arrays.asList(arrays1));
String[] arrays2 = new String[3];
StringBuffer sb = new StringBuffer("Women");
int count=0;
String str=null;
Iterator<String> iterator = list.iterator();
while(iterator.hasNext()){
str =iterator.next();
if(str.contains(sb)){
arrays2[count++] = str;
iterator.remove();
}
}
//for a new line
System.out.println();
arrays1 = list.toArray(new String[list.size()]);
for(int i=0;i<arrays1.length;i++)
System.out.print(arrays1[i]+" ");
//for a new line
System.out.println();
for(int i=0;i<arrays2.length;i++)
System.out.print(arrays2[i]+" ");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Test test = new Test();
test.usingArrays();
test.usingArrayList();
}
}
Related
Ok so I'm working on this code to blend humanities and STEM. I know very basic java code and so I'm currently trying to stick to String methods. I know using arrays may be easier but I'm not well learned in how to use them. So so far I've made code that counts the words in the string in order to determine how many words to remove (half of them). Next I need to figure out a way to randomly remove half of the words and return a new string, possibly with spaces replacing the removed letters.
Here is my code so far:
public class wordcount
{
public static void main (String[] args)
{
System.out.println("Simple Java Word Count Program");
String str1 = "Look, you want it you devour it and then, then good as it was you realize it wasn’t what you exactly wanted what you wanted exactly was wanting";
String[] wordArray = str1.split("\\s+");
int wordCount = wordArray.length;
System.out.println(str1 + "");
System.out.println("Word count is = " + wordCount);
int wordCount2 = wordCount/2;
}
}
I copied the array to an arrayList to then iterate through the list and delete random elements. I hope this is the type of answer you are looking for.
public static void main(String[] args) {
String str1 = "Look, you want it you devour it and then, then good as it was you realize it wasn’t what you exactly wanted what you wanted exactly was wanting";
String[] wordArray = str1.split("\\s+");
ArrayList<String> wordList = new ArrayList<String>(Arrays.asList(wordArray));
int wordCount = wordList.size();
int halfWordCount = wordCount/2;
int tracker = 0; //counter for iterations in while loop
Random random = new Random();
while(tracker < halfWordCount){
int randomIndex = random.nextInt(wordList.size());
wordList.remove(randomIndex);
tracker++;
}
System.out.println(wordList.toString());
}
import java.util.Arrays;
import java.util.* ;
public class wordcount
{
public ArrayList<Integer> test(Integer[] array)
{
ArrayList<Integer> list = new ArrayList<Integer>();
for(int i=0; i<array.length; i++)
list.add(array[i]);
return list;
}
public ArrayList<String> testS(String[] array)
{
ArrayList<String> list = new ArrayList<String>();
for(int i=0; i<array.length; i++)
list.add(array[i]);
return list;
}
public static void main (String[] args)
{
System.out.println("Removing random words in a Poem Program");
String str1 = "Sample Poem by Noah Eli Gordon: Look, you want it you devour it and then, then good as it was you realize it wasn’t what you exactly wanted what you wanted exactly was wanting";
String[] wordArray = str1.split("\\s+");
int wordCount = wordArray.length;
System.out.println(str1 + "");
//System.out.println("Word count is = " + wordCount);
//System.out.println(wordArray);
//String[] ret = wordArray;
//for(String str : ret)
// System.out.print(str);
int wordCount2 = wordCount/2;
Integer[] myIntArray = new Integer[wordCount];
//for(int i = 0; i<wordCount;i++)
// myIntArray[i] = i;
//for(int str : myIntArray)
//System.out.print(str);
wordcount w = new wordcount();
String[] wordArray2 = new String[wordCount2];
for(int i = 0; i <= wordCount2; i++)
{
int rand = (int)(Math.random()*(myIntArray.length-1));
ArrayList<Integer> list = w.test(myIntArray);
list.remove(rand);
myIntArray = list.toArray(myIntArray);
ArrayList<String> listS = w.testS(wordArray);
listS.remove(rand);
wordArray2 = listS.toArray(wordArray);
}
List<String> list = new ArrayList<String>();
for(String s : wordArray2)
{
if(s != null && s.length() > 0)
{
list.add(s);
}
}
wordArray2 = list.toArray(new String[list.size()]);
//for(int str : myIntArray)
//System.out.println(str);
System.out.println();
String[] ret2 = wordArray2;
for(String str : ret2)
System.out.print(str + " ");
}
}
Here is my first method. I have a file that I added its contents to an ArrayList. I can print that just fine but I need to create a method that adds line numbers to the beginning of each String. I can do that outside the method but i'm having problems creating a method that returns an arrayList so i can use the updated arrayList in other methods and then I need to display the updated ArrayList. Here is my code.
My output for the first method should be
1 bird
2 cat
etc...
My output for the second method should return the elements in the ArrayList in reverse order.
2 cat
1 bird
etc...
import java.util.*;
import java.io.*;
public class List
{
public static void main(String[] args) throws IOException
{
int line =1;
ArrayList<String> textArray = new ArrayList<String>();
ArrayList<String> newArray = new ArrayList<String>();
File f = new File("src/List.txt");
Scanner sc = new Scanner(f);
int num = 1;
while(sc.hasNext())
{
textArray.add(sc.nextLine());
}
numbered(textArray);
reverseOrder(textArray);
}
public static ArrayList<String> numbered(ArrayList<String> textArray)
{
ArrayList<String> results = new ArrayList<String>(textArray.size());
String s;
int num = 1;
for (String r : results)
{
r = num + " " + results;
num++;
}
return results;
}
public static ArrayList<String> reverseOrder(ArrayList<String> textArray)
{
ArrayList<String> results = new ArrayList<String>(textArray.size());
String s;
int num = 1;
for (String r : results)
{
}
return results;
}
You are returning your arrays correctly, the problem is that you are creating new Objects inside your methods, instead of using the ones you receive as parameters
ArrayList<String> results = new ArrayList<String>(textArray.size());
So you are iterating empty arrays.
Inside your for loop, you could just iterate the received ArrayList
for (String r : textArray)
Also, your results array is always empty, you should add new elements like this:
results.add(r);
This may work:
public static ArrayList<String> numbered(ArrayList<String> textArray)
{
ArrayList<String> results = new ArrayList<String>(textArray.size());
String s;
int num = 1;
for (String r : textArray)
{
r = num + " " + results;
num++;
results.add(r);
}
return results;
}
Have not tested this but it should work. As you can see pretty straight forward. Best of Luck and happy coding.
public ArrayList<String> numList(ArrayList<String> originalArrayList)
{
ArrayList<String> newNumberedList = new ArrayList<String>();
for(int i = 0;i< originalArrayList.size(); i++){
int newi = i+1;
newNumberedList.add(newi+". "+originalArrayList.get(i));
}
return newNumberedList ;
}
You are instantiating the 'results' arraylist, and iterating it. You need to iterate the textArray list for starters and call results.add("text");
The user is allowed to play with an array of strings. They can add strings to the array, remove strings from the array, search for strings in the array, and eventually they will be able to sort the array. The sorting is what is messing me up. I've tried a few different approaches. The first approach was to convert the array into an ArrayList and use Collections to sort the ArrayList, which would be converted back into the static class array. It doesn't work. The second approach I tried was to iterate through the array and try to sort only the strings added by the user instead of everything in the array (since there are some null values in the array). Perhaps I should iterate through the array and then store the non-null values into a new array that I can then sort? But what if I want to add more strings after sorting the new array? That's why I stopped with the second solution. The third attempt was to use Arrays.sort() on my array but for some reason it does not work.
Here is the exception:
Exception in thread "main" java.lang.NullPointerException
at java.util.ComparableTimSort.countRunAndMakeAscending(ComparableTimSort.java:290)
at java.util.ComparableTimSort.sort(ComparableTimSort.java:157)
at java.util.ComparableTimSort.sort(ComparableTimSort.java:146)
at java.util.Arrays.sort(Arrays.java:472)
at java.util.Collections.sort(Collections.java:155)
at testingSearch.sortArray(testingSearch.java:93)
at testingSearch.main(testingSearch.java:42)
Here is my code:
import java.util.Scanner;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class testingSearch {
static String[] strArray;
static {
strArray = new String[5];
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while(true){
System.out.println("1. Add string to the string array.");
System.out.println("2. Remove string from the string array.");
System.out.println("3. Display strings in string array.");
System.out.println("4. Search the string array for a string.");
System.out.println("5. Sort the strings in the string array.");
int userChoice = 0;
userChoice = input.nextInt();
switch(userChoice) {
case 1:
addString();
break;
case 2:
removeString();
break;
case 3:
displayStrings();
break;
case 4:
searchArray();
break;
case 5:
sortArray();
break;
}
}
}
public static void addString(){
Scanner input = new Scanner(System.in);
System.out.println("What string do you want to add?");
String userInput;
userInput = input.nextLine();
ArrayList<String> stringList = new ArrayList<String> (Arrays.asList(strArray));
stringList.add(userInput);
strArray = stringList.toArray(strArray);
}
public static void removeString(){
Scanner input = new Scanner(System.in);
System.out.println("What string do you want to remove?");
String userInput;
userInput = input.nextLine();
ArrayList<String> stringList = new ArrayList<String> (Arrays.asList(strArray));
stringList.remove(userInput);
strArray = stringList.toArray(strArray);
}
public static void displayStrings(){
for (String s: strArray){
if (!(s == null)){
System.out.println(s);
}
}
}
public static void searchArray(){
Scanner input = new Scanner(System.in);
System.out.println("What string do you want to search the array for?");
String userInput;
userInput = input.nextLine();
ArrayList<String> stringList = new ArrayList<String>(Arrays.asList(strArray));
if (stringList.contains(userInput)){
System.out.println("The string array contains that string!");
}
else {
System.out.println("The string array does not contain that string...");
}
}
public static void sortArray(){
/*ArrayList<String> stringList = new ArrayList<String> (Arrays.asList(strArray));
Collections.sort(stringList);
strArray = stringList.toArray(strArray);*/
/*for (String s: strArray) {
if (!(s == null)){
Arrays.sort(strArray);
}
}*/
List<String> stringList = new ArrayList<String>(Arrays.asList(strArray));
Collections.sort(stringList);
strArray = stringList.toArray(strArray);
//Arrays.sort(strArray);
}
}
The reason you're getting NullPointerExceptions can be explained by the javadoc for Arrays#sort() (emphasis mine):
Sorts the specified array of objects into ascending order, according to the natural ordering of its elements. All elements in the array must implement the Comparable interface.
Because Arrays.sort() expects Comparable elements and not null values, you end up with a NullPointerException when the method tries to call compareTo().
The fix-this-now way of solving this would be to simply make sure all null elements in your array are replaced with something non-null, such as "". So loop through your array at creation and after removing a String and set null elements to "". However, this solution probably wouldn't perform too well for your code, as it requires another loop after every String is removed, which could grow onerous. At least it won't require you to create a bunch of objects, due to the magic of the String pool, so it's a bit better than what you might do with a different object.
A better solution would be to simply use ArrayList<String> instead of a raw array; after all, you're already using one to manage addString() and removeString(), so you would have less converting from array to ArrayList and back to do. In addition, you wouldn't need to worry about NPEs when sorting (at least for your use case; adding null to a Collection would still result in NPEs when sorting).
You can also just use a raw array, but managing that would get kind of annoying, so I wouldn't recommend that. If you do it right you won't have to worry about NPEs though.
No problem! Here you go:
1. Create a new array
2. Insert items to that array, in the right order
public class sorter {
public static void main(String[] args){
String[] array = new String[]{"HI", "BYE", null, "SUP", ":)"};
//Sort:
String[] newArray = new String[array.length];
int index = 0;
for(int m = 0 ; m < newArray.length; m++){
String leastString = null;
int i = 0;
for(i = 0; i < array.length; i++){
if(leastString==null&&array[i]!=null){
leastString = array[i];
break;
}
}
for(int j = i+1; j < newArray.length; j++){
if(array[j]!=null){
if(array[j].compareTo(array[i])<0){
leastString = array[j];
i = j;
}
}
}
if(i==newArray.length)break;
newArray[m] = leastString;
array[i] = null;
}
for(String s : newArray){
System.out.println(s);
}
}
}
This prints:
:)
BYE
HI
SUP
null
EDIT: Another very simple way to solve this in a very effiecient manner, is to use ArrayList:
public class AClass {
public static void main(String[] args){
String[] array = new String[]{"HI", "BYE", null, "SUP", ":)"};
//Sort:
ArrayList<String> newArray = new ArrayList<String>();
for(String s : array){
if(s!=null){
newArray.add(s);
}
}
Collections.sort(newArray);
String[] retval = new String[newArray.size()];
retval = newArray.toArray(retval);
for(String s : retval){
System.out.println(s);
}
}
}
I guess the simple way of doing things really would be:
static String[] strArray;
static {
strArray = new String[5];
for(int i = 0, i < strArray.length; i++)
{
strArray[i] = "";
}
}
And then just call
Arrays.sort(strArray);
When you want to sort it. If that doesn't work, although I think it should; your initial approach would have been the following:
List<String> stringList = new ArrayList<String>();
for(int i = 0; i < strArray.length; i++)
{
stringList.add(strArray[i]);
}
Collections.sort(stringList);
strArray = stringList.toArray(new String[stringList.size()]);
Although it clearly doesn't seem very memory-friendly.
So I'm trying to read the first 100 strings, which are words into an array of 100 Strings. and while doing that I'm trying to set each corresponding integer in an array of integers to 1, so counting each word the first time its read.
It's reading a book, 100 words at a time, and counting those words. So far I have this, how would I just make a switch statement of 100 cases?
Thanks in advance for any help!
package program6;
import java.util.Scanner;
public class Program6 {
static Scanner keyboard = new Scanner(System.in);
static String input;
String[] StringArray = new String[100];
int[] IntArray = new int[100];
String filename = "myths.txt";
String stringnumber;
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
HashMap<String,Integer> map = new HashMap();
public void count(String file){
Scanner in = null;
try{
in = new Scanner(new File(file));
}catch(IOException ex){
}
String val = in.next();
for(String currentKey : map.keySet()){
if(map.containsKey(val)){
map.put(currentKey,map.get(currentKey)+1);
}else{
map.put(val,1);
}
}
}
Try this :
Map<String, Integer> record = new HashMap<String, Integer>();
for(String temp: StringArray){
if(record.containsKey(temp)){
Integer num = record.get(temp) + 1;
record.put(temp, num);
}
else{
record.put(temp, 1);
}
}
I am new to java programming. My question is this I have a String array but when I am trying to convert it to an int array I keep getting
java.lang.NumberFormatException
My code is
private void processLine(String[] strings) {
Integer[] intarray=new Integer[strings.length];
int i=0;
for(String str:strings){
intarray[i]=Integer.parseInt(str);//Exception in this line
i++;
}
}
Any help would be great thanks!!!
Suppose, for example, that we have a arrays of strings:
String[] strings = {"1", "2", "3"};
With Lambda Expressions [1] [2] (since Java 8), you can do the next ▼:
int[] array = Arrays.asList(strings).stream().mapToInt(Integer::parseInt).toArray();
▼ This is another way:
int[] array = Arrays.stream(strings).mapToInt(Integer::parseInt).toArray();
—————————
Notes
1. Lambda Expressions in The Java Tutorials.
2. Java SE 8: Lambda Quick Start
To get rid of additional whitespace, you could change the code like this:
intarray[i]=Integer.parseInt(str.trim()); // No more Exception in this line
To help debug, and make your code better, do this:
private void processLine(String[] strings) {
Integer[] intarray=new Integer[strings.length];
int i=0;
for(String str:strings){
try {
intarray[i]=Integer.parseInt(str);
i++;
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Not a number: " + str + " at index " + i, e);
}
}
}
Also, from a code neatness point, you could reduce the lines by doing this:
for (String str : strings)
intarray[i++] = Integer.parseInt(str);
Another short way:
int[] myIntArray = Arrays.stream(myStringArray).mapToInt(Integer::parseInt).toArray();
Since you are trying to get an Integer[] array you could use:
Integer[] intarray = Stream.of(strings).mapToInt(Integer::parseInt).boxed().toArray(Integer[]::new);
Your code:
private void processLine(String[] strings) {
Integer[] intarray = Stream.of(strings).mapToInt(Integer::parseInt).boxed().toArray(Integer[]::new);
}
Note, that this only works for Java 8 and higher.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class array_test {
public static void main(String args[]) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
String[] s_array = line.split(" ");
/* Splitting the array of number
separated by space into string array.*/
Integer [] a = new Integer[s_array.length];
/Creating the int array of size equals to string array./
for(int i =0; i<a.length;i++)
{
a[i]= Integer.parseInt(s_array[i]);// Parsing from string to int
System.out.println(a[i]);
}
// your integer array is ready to use.
}
}
This is because your string does not strictly contain the integers in string format. It has alphanumeric chars in it.
public static int[] strArrayToIntArray(String[] a){
int[] b = new int[a.length];
for (int i = 0; i < a.length; i++) {
b[i] = Integer.parseInt(a[i]);
}
return b;
}
This is a simple function, that should help you.
You can use him like this:
int[] arr = strArrayToIntArray(/*YOUR STR ARRAY*/);
private void processLine(String[] strings) {
Integer[] intarray=new Integer[strings.length];
for(int i=0;i<strings.length;i++) {
intarray[i]=Integer.parseInt(strings[i]);
}
for(Integer temp:intarray) {
System.out.println("convert int array from String"+temp);
}
}