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 7 years ago.
Improve this question
I have one input String to the program and I need to execute this String into my method, but I want to execute it if the character String is less than or equal to 20 characters, so I want to split this String into multiple Strings if the string is longer than 20 characters.
That is, the number of characters input String is 90 characters then become a 5 String 20 + 20 + 20 + 20 + 10 = 90.
I need each 20 characters String and last String do this code:
try {
enMessage = AES.encrypt(key, message);
sendSMS(contact, enMessage);
} catch (Exception e)
so its could make each 20 characters is one message.
You can use String's substring method to split the strings you want to.
You can read about how to use it here
Java String Documentation
The best example of such code I have seen so far on this site is:
public class StringSplitter {
/* regex was stolen from other stackoverflow answer*/
public static void main(String[] args) {
for (String str : "123a4567a8sdfsdfsdgasfsdfsdgsdcvsdfdgdfsdf9".split("(?<=\\G.{20})"))
System.out.format("\'%s\'%n", str);
}
}
You can try doing this:
package com.me;
import java.util.*;
import java.lang.*;
import java.io.*;
public class Test
{
public static List<String> splitMyString(String textValue, int textSize) {
ArrayList<String> myNewList= new ArrayList<String>((textValue.length() + textSize- 1) / textSize);
for (int start = 0; start < textValue.length(); start += textSize) {
myNewList.add(textValue.substring(start, Math.min(textValue.length(), start + textSize)));
}
System.out.println(myNewList.toString());
return myNewList;
}
public static void main(String[] args) {
Test.splitMyString("1234546512312312312312365", 5);
}
}
Output:
Success time: 0.1 memory: [12345, 46512, 31231, 23123,
12365]
Try this:
ArrayList<String> allstrings = new ArrayList<>();
if(inputstring.length() < 20) {
//no spliting
} else {
//if 90 char than 90/20=4.5
float numberOfspliting = inputstring.length / 20f;
for(int i = 0; i < numberofspliting; i++){
String split = inputstring.substring(i * 20, i * 20 + 20);
allstrings.add(split);
}
//like 4.5-4=0.5
float leftcharacters = numberofspliting - (int)numberofspliting;
String lastsplit = inputstring.substring((int)numberofspliting * 20, (int)numberofspliting * 20 + leftcharacters * 20f);
allstrings.add(lastsplit);
}//end if
Related
I'm practicing Java and I have a question about printing all values inside a String array. I would need to print everything inside the String arrays I have created.
I can't seem to make "Arrays.toString" to work in my code and I don't want to have to point out each value inside the array. Is there a way I can print them all at once?
public class MyCode {
public static void main(String[] args) {
String[] majority = {"Congrats, you may enter!", " Awesome!"};
String[] minority = {"I'm sorry, you are too young.", " Ah that's too bad!"};
int permition = 17;
boolean authorization = (permition >= 18);
if (authorization == true) {
System.out.println(majority[0] + majority[1]);
} else {
System.out.println(minority[0] + minority[1]);
}
}
}
So, if the person is above or equal to 18, the result should be "Congrats, you may enter! Awesome!", or if below 18 "I'm sorry, you are too young. Ah that's too bad!".
You can try this
List<String>majorities =
Arrays.asList(majority);
List<String>minorities =
Arrays.asList(minority);
String str_majority = String.join("",
majorities);
String str_minority = String.join("",
minorities);
String final = str_majority +
str_minority
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 7 years ago.
So this is my text file:
CareFlight101 0 2
PiperCub 2 99
AirAmbulance 2 1
TransWorld122 2 5
Cessna152 3 99
Eastern429 4 10
They are suppose to be aircrafts name followed my arrival time and landing priority.
I am trying to splitting it so that it takes each into account. I am having trouble splitting it though because it it throwing a 'java.lang.ArrayIndexOutOfBoundsException: 1' error
This is what I have so far:
public class TheAircrafts {
public static ArrayList<Plane> planeList;
public static void main(String[] args){
try {
File f = new File("sample_data_p3.txt");
Scanner sc = new Scanner(f);
List<Plane> people = new ArrayList<Plane>();
while(sc.hasNextLine()){
String line = sc.nextLine();
String[] details = line.split("\\s+");
String flightID = details[0];
int arrivalTime = Integer.parseInt(details[1]);
int landingPriority = Integer.parseInt(details[2]);
Plane p = new Plane(flightID, arrivalTime, landingPriority);
planeList.add(p);
}
for(Plane p: planeList){
System.out.println(p.toString());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
And in my plane class I have:
public class Plane {
private String flightID;
private int arrivalTime;
private int landingPriority;
private int numRunways;
public Plane(String flightID, int arrivalTime, int landingPriority) {
this.setflightID(flightID);
this.arrivalTime = arrivalTime;
this.landingPriority = landingPriority;
}
followed by get and set and get methods for each of the variables
You get a IndexOutOfBoundsException in this case when there is a line which not more than i elements seperated by a space.
In your case there is a line which has only one word in it. And hence when you try to get the second word which didn't exist you get an Exception.
To avoid getting so, you can check if that line has 3 words or not.
String []details = line.split("\\s+");
if(details.length == 3)
{
//do your setting
}
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 7 years ago.
Improve this question
I am looking to take a list of words or names and output them into groups in a specific order via php or Java but have no idea how to do so. I will give an example with the order: (To clarify, this isn't homework. I am doing this for a tournament that I am hosting, and it would make it easy to generate seeds during the event)
Amount of names: 12
Size of Groups: 3
Hilde Frankum
Earlie Uphoff
Rich Laclair
Vicenta Baskin
Herminia Lakin
Hermelinda Hostetter
Bernice Sylva
Blossom Nesby
Lashon Kwan
Esther Farraj
Tana Olguin
Pamula Davin
Output:
Group 1:
Hilde Frankum
Herminia Lakin
Lashon Kwan
Group 2:
Earlie Uphoff
Hermelinda Hostetter
Esther Farraj
Group 3:
Rich Laclair
Bernice Sylva
Tana Olguin
Group 4:
Vicenta Baskin
Blossom Nesby
Pamula Davin
The list takes the name next in line and inserts it into a new group in the order that it is listed in until there are no more groups left and then restarts until there isn't any names left.
PFB sample code. I have created a Group class which holds an group(array of String objects). An ArrayList which holds random number of Group objects.
Program is dynamic based on input names and Size of Groups:
import java.util.ArrayList;
import java.util.List;
public class Group {
String group[];
public Group(int groupSize) {
this.group = new String[groupSize];
}
#Override
public String toString() {
StringBuilder strBuilder = new StringBuilder();
for (int i = 0; i < group.length; i++) {
if (i != 0)
strBuilder.append(", ");
strBuilder.append(group[i]);
}
return strBuilder.toString();
}
public static void main(String[] args) {
String[] inputArray = { "Hilde Frankum", "Earlie Uphoff",
"Rich Laclair", "Vicenta Baskin", "Herminia Lakin",
"Hermelinda Hostetter", "Bernice Sylva", "Blossom Nesby",
"Lashon Kwan", "Esther Farraj", "Tana Olguin", "Pamula Davin" };
int numGroups = 4;
createGroup(inputArray, numGroups);
}
public static void createGroup(String inputArray[], int numGroups) {
int groupSize = inputArray.length / numGroups;
List<Group> lists = new ArrayList<Group>();
for (int i = 0; i < numGroups; i++)
lists.add(new Group(groupSize));
for (int i = 0, x = 0; i < groupSize; i++)
for (int j = 0; j < numGroups; j++)
lists.get(j).group[i] = inputArray[x++];
for (Group groups : lists)
System.out.println(groups.toString());
}
}
Here's a Java method that should do it.
String[][] groupThem(ArrayList<String> /*could be an array without many changes*/ things, int sizeOfGroups){
int qtyOfThings = things.size();
int qtyOfGroups = qtyOfThings / sizeOfGroups;
String[][] groups = new String[qtyOfGroups][sizeOfGroups];
int counter = 0;
while(counter < qtyOfThings){
groups[counter%qtyOfGroups][counter%sizeOfGroups] = things.get(counter);
counter++;
}
return groups;
}
$arrayOfNames = array(
'Hilde Frankum',
'Earlie Uphoff',
'Rich Laclair',
'Vicenta Baskin',
'Herminia Lakin',
'Hermelinda Hostetter',
'Bernice Sylva',
'Blossom Nesby',
'Lashon Kwan',
'Esther Farraj',
'Tana Olguin',
'Pamula Davin'
);
sort($arrayOfNames);
$ar = array_chunk($arrayOfNames, 3);
foreach($ar as $key => $groups){
echo "Group #" . ($key + 1) .' '. implode(' ',$groups) . "\n";
}
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 9 years ago.
Improve this question
I'm trying to return different array values according to the condition. Here is my code but it made error. Please help me find out what's the problem.
private static String subject[] = {"Mathematics", "English"};
private static String studentNum[] = {"1", "2"};
private static int marks[][] = {{56,51}, // Student 1 mark for Mathermatics
{69,85}}; // Student 2 mark for English
public static double AverageMarks(String aCode) {
double sum[] = new double[subject.length];
double average[] = new double[subject.length];
for(int j=0;j<subject.length;j++) {
for(int i=0;i<studentNum.length;i++) {
sum[j] += marks[j][i];
average[j] = (sum[j] / studentNum.length); // average[0] is the average mark of Mathermatics and average[1] is the average mark of English
}
if (aCode.equals(subject[j])) {
return average[j];
}
else {
return 0;
}
}
}
You are almost there. The line
average[j] = (sum[j] / studentNum.length);
should be out of the nested for, because the nested for is used to sum every grade, after it finishes you should assign the sum to sum[j].
Also, you should put the return 0 at the end of the function, or the for loop would just loop one time (because if the condition aCode.equals(...) is not true, it will return 0) in the first loop.
public static double averageMarks(String aCode)
{
double sum[] = new double[subject.length];
double average[] = new double[subject.length];
for (int j = 0; j < subject.length; j++) {
for (int i = 0; i < studentNum.length; i++) {
sum[j] += marks[j][i];
}
average[j] = (sum[j] / studentNum.length); // average[0] is the average mark of Mathermatics and average[1] is the average mark of English
if (aCode.equals(subject[j])) {
return average[j];
}
}
return 0;
}
Note: I would recommend you to follow Java naming conventions. Your method should be called like methodName, not like MethodName.
You are having dead code in the program.
for(int j=0;j<subject.length;j++)
These loop is of no use because in the first iteration of the loop you are using return.
Also one return type of the method is missing which must be outside the 2 loops.
My initial look, I notice this since you didn't describe more about your error I layout the first thing i see that could be wrong.
if (aCode.equals(subject[j])) {return average[j];}
else {return 0;}
This line of code in particular i believe is wrong. It'll never get to the outer loop to check the different subject because it goes straight to the else.
public static double AverageMarks(String aCode) {
double sum[] = new double[subject.length];
double average[] = new double[subject.length];
for(int j=0;j<subject.length;j++){
for(int i=0;i<studentNum.length;i++) {
sum[j] += marks[j][i];
}
average[j] = (sum[j] / studentNum.length);
if (aCode.equals(subject[j])) return average[j];
}
return 0;
}
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 9 years ago.
Improve this question
I've been trying to write a simple program in java to find time complexity of a program.A program whih just searches for "for" loop or "while" loop and prints the no of iteration such as O(n) or O(2n) etc.
I got the i/p program in textarea.Is there any way by which i could do the opertaion?
Please any one help me.
This is not full proof, but would work for you
import java.util.StringTokenizer;
public class Complexity {
public static void main(String[] args) {
String input = "for(i=0;i<10;i++)\n{\nfor(i=0;i<10;i++)\n{\nfor(i=0;i<10;i++)\n{\n}\n}\n}\nfor(i=0;i<10;i++)\n{\n}\nfor(i=0;i<10;i++)\n{\nfor(i=0;i<10;i++)\n{\n}\n}";
int open_bracket=0;
StringTokenizer t = new StringTokenizer(input);
String result = "";
String token="";
int current = 0;
System.out.println("CODE \n"+input);
while(t.hasMoreTokens())
{
token = t.nextToken();
if(token.equals("{")) open_bracket++;
if(token.equals("}")) open_bracket--;
if(token.length()>=3) if(token.substring(0, 3).equals("for")) current++;
if(open_bracket==0&&token.equals("}"))
{
result += " n^"+current+" +";
current = 0;
}
}
if(result.length()>0) result = result.substring(0, result.length()-1);
result = "O( "+result+")";
System.out.println("RESULT = "+result);
}
}
OUTPUT
CODE
for(i=0;i<10;i++)
{
for(i=0;i<10;i++)
{
for(i=0;i<10;i++)
{
}
}
}
for(i=0;i<10;i++)
{
}
for(i=0;i<10;i++)
{
for(i=0;i<10;i++)
{
}
}
RESULT = O( n^3 + n^1 + n^2 )