I'm trying to convert a main programs "String[] args" into 5 ints, and 4 doubles. (i know it's kind of confusing)
The way i was thinking of doing it was having a forreach loop to loop through String args[] and add them to an int array (for the first 5), however i had to use for the array, so it doesn't work.
if (args != null) {
// If arguments where given, use the arguments and run the program
// NEED TO SOMEHOW CONVERT ARGS INTO INTEGER FORM AFTER BEING PASSED IN
ArrayList<Integer> valArr = new ArrayList<Integer>(10); // could be 9
for (String val : args) {
// Parse the string and add it to valArray
int temp = Integer.parseInt(val);
valArr.add(temp);
}
CarPark cp = new CarPark(valArr[0], valArr[1], valArr[2], valArr[3]);
this is what i'm looking at at the moment... am i completely wrong? or close?
Just parse it with two indexing for loops.
int[] myInts = new int[5];
double[] myDoubles = new double[4];
// Initialize these arrays with "defaults" here.
// Notice how we handle the possibility of the user not entering enough values.
for (int i = 0; i < Math.min(5, args.length); i++)
myInts[i] = Integer.parseInt(args[i]);
for (int i = 0; i < Math.min(4, args.length - 5); i++)
myDoubles[i] = Double.parseDouble(args[i+5]);
CarPark cp = new CarPark(myInts[0], myInts[1], myInts[2], myInts[3]);
you have to get the values from the array list as given below
CarPark cp = new CarPark(valArr.get(0), valArr.get(1), valArr.get(2), valArr.get(3));
look at ArrayList Doc
above could be like this
CarPark cp = new CarPark(valArr.get(0), valArr.get(1), valArr.get(2), valArr.get(3));
I think this should work.
if (args != null) {
// If arguments where given, use the arguments and run the program
// NEED TO SOMEHOW CONVERT ARGS INTO INTEGER FORM AFTER BEING PASSED IN
ArrayList<Integer> valArr = new ArrayList<Integer>(10); // could be 9
for (String val : args) {
// Parse the string and add it to valArray
int temp = Integer.parseInt(val);
valArr.add(temp);
}
CarPark cp = new CarPark(valArr.get(0), valArr.get(1), valArr.get(2), valArr.get(3));
Here is your corrected code:-
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
args=new String[4];
for(int i=0;i<4;i++){
System.out.println("Enter value no- "+(i+1));
args[i]=sc.nextLine();
}
ArrayList<Integer> valArr = new ArrayList<Integer>(10);
if (args != null) {
// If arguments where given, use the arguments and run the program
// NEED TO SOMEHOW CONVERT ARGS INTO INTEGER FORM AFTER BEING PASSED IN
// could be 9
for (String val : args) {
// Parse the string and add it to valArray
int temp = Integer.parseInt(val.trim());
valArr.add(temp);
}
}
System.out.println(valArr);
//CarPark cp = new CarPark(valArr[0], valArr[1], valArr[2], valArr[3]);
}
}
This is just the code for Integer part in similar way you can extend the args array length and include double values, Remeber to use val.trim() to remove whitespaces otherwise it will throw NumberFormatException.
Related
I need to execute by command line a code that will provide a multidimensional array with elements with not necessarily equal lengths.
The execution string is bellow:
start /wait java -jar testMSMWithIndex.jar Foursquare_weather_day_root-type_type 0,1,2-4
I'm considering to pass the parameter 0,1,2-4 and then convert it in a multidimensional array with elements of different lengths in this case, i.e. {{0}, {1}, {2, 4}}.
Note that {{0, null}, {1, null}, {2, 4}} does not work to my problem.
Do you guys know how to develop a method or even get directly as an array from args?
I really appreciate any help you can provide.
It's doubtful that anything already exists to do this for you, so you'll have to parse the string for yourself. Something like this would do it:
public static int[][] parseRaggedArrayFromString(String s)
throws NumberFormatException {
String[] ss = s.split(",");
int[][] result = new int[ss.length][];
for (int i = 0; i < ss.length; ++i) {
if (!ss[i].contains("-")) {
result[i] = new int[1];
result[i][0] = Integer.parseInt(ss[i]);
} else {
String[] range = ss[i].split("-", 2);
int lo = Integer.parseInt(range[0]);
int hi = Integer.parseInt(range[1]);
int size = hi - lo + 1;
result[i] = new int[size > 0 ? size : 1];
int j = 0;
do {
result[i][j] = lo;
++lo;
++j;
} while (lo <= hi);
}
}
return result;
}
It's basically a split on , and -. From there is just handling the data. Comments in the code.
/**
* #author sedj601
*/
public class Main {
public static void main(String[] args) {
String input = "0,1,2-3";
String[] firstArray = input.split(",");//Split on ,.
String[][] outputArray = new String[firstArray.length][];//The array that will be holding the output
//Used to process the firstArray
for (int i = 0; i < firstArray.length; i++) {
if (firstArray[i].length() > 1) {//If the lenght is greater than one. split on -.
String[] secondArray = firstArray[i].split("-");
//Subtract the two numbers and add one to get the lenght of the array that will hold these values
int arrayLength = Integer.parseInt(secondArray[1]) - Integer.parseInt(secondArray[0]) + 1;
String[] tempArray = new String[arrayLength];
int increment = 0;//Keeps up with the tempArray index.
//loop from the first number to the last number inclusively.
for (int t = Integer.parseInt(secondArray[0]); t <= Integer.parseInt(secondArray[1]); t++) {
tempArray[increment++] = Integer.toString(t);//Add the data to the array.
}
outputArray[i] = tempArray;//Add the array to the output array.
} else {//If the lenght is 1, creat an array and add the current data.
String[] tempArray = new String[1];
tempArray[0] = firstArray[i];
outputArray[i] = tempArray;
}
}
//Print the output.
for (String[] x : outputArray) {
for (String y : x) {
System.out.print(y + " ");
}
System.out.println();
}
}
}
Output:
--- exec-maven-plugin:1.5.0:exec (default-cli) # JavaTestingGround ---
0
1
2 3
------------------------------------------------------------------------
BUILD SUCCESS
------------------------------------------------------------------------
Total time: 1.194 s
Finished at: 2021-01-08T00:08:15-06:00
------------------------------------------------------------------------
I really think that's possible when you create an array of type Object .(not a good idea) Since multi-D arrays can only hold arrays of same length (int[][]). Then you create and retrieve values from array by casting...
I am trying here to be creative and adopt to your requirements..
public class x {
public static void main(String[] args) {
Object[] arguments = new Object[args.length];
// Then make a loop to capture arguments in array..
// or add manually
arguments[0] = new String[]{args[0]};
arguments[1] = new String[]{args[1],args[2]};
//Then retrieve info from object later by casting
System.out.println(java.util.Arrays.toString((String[]) arguments[1]));
}
}
...
Although, please consider using a collection...
While I waited for the answer, I found a way to solve the problem.
The relevant information here is that we do not need to set the second array dimension in its instantiation.
The code is below:
// INPUT string = "2-3,1,4-5"
private static String[][] featuresConversion(String string) {
String[] firstLevel = string.split(","); // 1st lvl separator
String[][] features = new String[firstLevel.length][]; // Sets 1st lvl length only
int i = 0;
for (String element : firstLevel) {
features[i++] = element.split("-");
}
return features;
}
I want to thank you all. All suggested solutions also work fine!
Basically, I'm working on a program for my class to find the leading digit of numbers from a text file and sort them. I know I don't have the best coding skills out there since I'm a beginner, but I have an idea on how to do it. Somehow, I've encountered a problem where the array that's suppose to be returned comes out to be empty. This array is returned twice, actually. The first time, to the main method, it returns neatly, but when it's returned to change3(), it returns "[]."
I've tried to change the variables around, and even tried to combine the methods, but nothing works and I just get errors.
import java.io.*;
import java.util.*;
class PG
{
public static void main(String[] args)
{
List<String> Strings = new ArrayList<String>();
Strings = change(); // it works perfectly right here
System.out.println(Strings); // it works perfectly right here
List<Integer> Integers = new ArrayList<Integer>();
Integers = change2();
List<Integer> leads = new ArrayList<Integer>();
leads = change3();
}
public static List<String> change()
{
Scanner in = new Scanner(System.in);
List<String> list_S = new ArrayList<String>();
while (in.hasNextLine())
{
String line = in.nextLine();
line = line.replaceAll(",", "");
int result = Integer.parseInt(line);
List<Integer> list_I = new ArrayList<Integer>();
list_I.add(result);
list_S.add(line);
}
return list_S;
}
public static List<Integer> change2()
{
Scanner in = new Scanner(System.in);
List<Integer> list_I = new ArrayList<Integer>();
while (in.hasNextLine())
{
String line = in.nextLine();
line = line.replaceAll(",", "");
int result = Integer.parseInt(line);
List<String> list_S = new ArrayList<String>();
list_I.add(result);
list_S.add(line);
}
return list_I;
}
public static List<Integer> change3()
{
List<String> list = new ArrayList<String>();
list = change(); // This is supposed to give me a list of numbers(string) so it can help me find the leading digit
System.out.println(list); // checking to see if the list even has numbers in it. It does not. It returns [] as if nothing is in the list.
List<Integer> leads = new ArrayList<Integer>();
for (int i = 0; i < list.size(); i++)
{
// get the leading integer
}
return leads;
}
}
Basically, for right now, I just want it to print the list in the method change3(), so I can continue to work on the program.
Try this code. it should work. if its not working please comment the issue.
Also match this code with your.
There are some changes in change method. I have removed redundant code.
I will suggest to pass the list in all 3 change methods if its same list being used. so you don't have to read it again with the help of scanner.
import java.io.*;
import java.util.*;
class PG
{
public static void main(String[] args)
{
List<String> Strings = new ArrayList<String>();
Strings = change(); // it works perfectly right here
System.out.println(Strings); // it works perfectly right here
List<Integer> Integers = new ArrayList<Integer>();
Integers = change2();
List<Integer> leads = new ArrayList<Integer>();
leads = change3();
}
public static List<String> change()
{
Scanner in = new Scanner(System.in);
List<String> list_S = new ArrayList<String>();
while (in.hasNextLine())
{
String line = in.nextLine();
line = line.replaceAll(",", "");
list_S.add(line);
}
return list_S;
}
public static List<Integer> change2()
{
Scanner in = new Scanner(System.in);
List<Integer> list_I = new ArrayList<Integer>();
while (in.hasNextLine())
{
String line = in.nextLine();
line = line.replaceAll(",", "");
int result = Integer.parseInt(line);
list_I.add(result);
}
return list_I;
}
public static List<Integer> change3()
{
List<String> list = new ArrayList<String>();
list = change(); // This is supposed to give me a list of numbers(string) so it can help me find the leading digit
System.out.println(list); // checking to see if the list even has numbers in it. It does not. It returns [] as if nothing is in the list.
List<Integer> leads = new ArrayList<Integer>();
for (int i = 0; i < list.size(); i++)
{
// get the leading integer
}
return leads;
}
}
This question already has answers here:
Differences between System.out.println() and return in Java
(4 answers)
Closed 5 years ago.
I'm still learning the basics of coding in Java and have moved onto using methods which has thrown me. My issue is nothing is being returned to the console and I have no idea why. Here's my code:
public class MethodsPractice {
public int returnInteger (int num1, int num2){
return num1 + num2;
}
public String[] upperCaseString(String[] strings){
String[] upperStrings = new String[strings.length];
for (int i = 0; i < strings.length; i++){
upperStrings[i] = strings[i].toUpperCase();
}
return upperStrings;
}
public static void main(String[] args) {
MethodsPractice myMethods = new MethodsPractice();
int result = myMethods.returnInteger (10,20);
String[] names = {"Bob", "Alex", "Luke"};
String[] newNames = myMethods.upperCaseString(names);
}
}
Simply put, you just aren't putting anything to console. Your code creates a new object, does some math, then creates an array of strings, but it never does anything with those newly created objects, for ex: If you wanted to print the result of the math function you need to use:
System.out.println(result);
Java (mostly)does not print anything to console you don't tell it to.
System.out is the stream where you can print to console.
Of course, println is not the only function :) https://docs.oracle.com/javase/7/docs/api/java/lang/System.html#out
upperCaseString just returns the a new array, which your main method saves to the newNames variable, and then does nothing with it. If you want to print it, you would have to do so explicitly, e.g.:
System.out.println(Arrays.toString(newNames));
To see content in the console, you need to call the methods from System.out like
print() : show content
println() : show content and go to next line
To easily print arrays, there is tips like :
String[] newNames = myMethods.upperCaseString(names);
System.out.println(Arrays.toString(newNames));
The classic way to print array will be with for (or foreach loop)
for(int i = 0; i<newNames.length ; i++) // for loop
System.out.print(newNames[i] + ", ");
for(String str : newNames) // foreach loop
System.out.print(str + ", ");
You have to add an Console Output with:
System.out.print(); //without new line
or
System.out:println(); //starts a new line after output
For example:
public class MethodsPractice {
public int returnInteger (int num1, int num2){
return num1 + num2;
}
public String[] upperCaseString(String[] strings){
String[] upperStrings = new String[strings.length];
for (int i = 0; i < strings.length; i++){
upperStrings[i] = strings[i].toUpperCase();
}
return upperStrings;
}
public static void main(String[] args) {
MethodsPractice myMethods = new MethodsPractice();
int result = myMethods.returnInteger (10,20);
String[] names = {"Bob", "Alex", "Luke"};
String[] newNames = myMethods.upperCaseString(names);
System.out.print(name[0]);
System.out.println(name[1]);
System.out.print(name[2])
}
}
In the Consol will output:
BobAlex
Luke
I am trying to create an array that reads string tokens from standard input, and places them in an array, and then prints the words out, until it reaches a specific word. For example, let's say I wanted my array to read a series of words until it reached the word "okay" from std in, print out each word, and then terminate before printing out "okay". The length of this array will be unknown, so I am confused on how to do this.
String s = sc.next();
String[] copy = new String[???];
for( int i = 0; i < copy.length; i++ ){
copy[i] = sc.next();
}
Something like:
String s = sc.next();
ArrayList<String> copy = new ArrayList<String>();
while(!s.equals("okay")){
copy.add(s);
s = sc.next();
}
for (String n : copy){
System.out.println(n);
}
If you don't want to use any list at all, then this becomes impossible. This is simply because array size needs to be defined at the time the array object is created.
So with this constraint you can have a large integer and declare an array of that size.
Final int MY_LARGE_CONST = 3000;
...
String[] tokens = new String[MY_LARGE_CONST]...
This is wasteful since it takes more memory and will fail if you have more tokens than the constant.
Alternaely if you are ok with lists and not ok with iterating over that for actual processing, then u can put the tokens in an ArrayList and once they are all collected, call the toArray method on the ArrayList object.
It's my code Without using ArrayList.
import java.util.Scanner;
import java.util.StringTokenizer;
public class Sample {
public static void main(String[] args) {
Scanner sc = new Scanner(System. in );
String line = sc.nextLine();
StringTokenizer st = new StringTokenizer(line);
int len = st.countTokens();
String[] array = new String[len];
for (int idx = 0; idx < len; idx++) {
array[idx] = st.nextToken();
}
for (String str: array) {
System.out.println(str);
}
}
}
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.