This is the original prompt:
Write program that gets a comma-delimited String of integers (e.g. “4,8,16,32,…”) from the user at the command line and then converts the String to an ArrayList of Integers (using the wrapper class) with each element containing one of the input integers in sequence. Finally, use a for loop to output the integers to the command line, each on a separate line.
import java.util.Scanner;
import java.util.ArrayList;
public class Parser {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
ArrayList<String> myInts = new ArrayList<String>();
String integers = "";
System.out.print("Enter a list of delimited integers: ");
integers = scnr.nextLine();
for (int i = 0; i < myInts.size(); i++) {
integers = myInts.get(i);
myInts.add(integers);
System.out.println(myInts);
}
}
}
I was able to get it to where it accepts the list of delimited integers, but I'm stuck on the converting piece of it and the for loop, specifically printing each number to a separate line.
The easiest way to convert this string would be to split it according to the comma and apply Integer.valueOf to each element:
List<Integer> converted = Arrays.stream(integers.split(","))
.map(Integer::valueOf)
.collect(Collectors.toList());
Printing them, assuming you have to use a for loop, would just mean looping over them and printing each one individually:
for (Integer i : converted) {
System.out.println(i);
}
If you don't absolutely have to use a for loop, this could also be done much more elegantly with streams, even without storing to a temporary list:
Arrays.stream(integers.split(","))
.map(Integer::valueOf)
.forEach(System.out::println);
First, you can convert the input string to String[], by using the split method: input.split(","). This will give you an array where the elements are strings which were separated by ",".
And then, to convert a String to an Integer wrapper, you can use:
Integer i = Integer.valueOf(str);
Integer i = Integer.parseInt(str)
myInts is empty, your data is in integers.
I suggest that you search about the fonction : split (from String)
Related
My goal is to implement a method named add that receives a reference to a Scanner object associated with a stream of input consisting of integers only. The method reads all the integers remaining to be read from the stream and returns their sum.
So if the input were 3 51 204 17 1040, the returned value would be 1315. The method must not use a loop of any kind (for, while, do-while t accomplish its job).
My attempt is shown below:
public void add(Scanner scanner){
Scanner input = new Scanner(System.input);
String s = input.nextLine();
String[] numbers = str.split(" ")
int[] ints = new int[numbers.length];
}
The specific issue that I am running into is the conversion of the string array into an integer array.
Since you can't use a loop of any kind, I think you are supposed to use recursion. You need to actually return a value. Presumably an int. Something like check if there is an int. If so, read it and recursively add any other int(s); Otherwise, return 0. Like,
public int add(Scanner input){
if (input.hasNextInt()) {
return input.nextInt() + add(input);
}
return 0;
}
I'm trying solve problem in Strings,finding matching characters in to String.
I solve it using Character Array and inner loop but i think it has more time complexity. so try to solve it in Arrays binary search but it gives inappropriate result.i want working structure of binary search method in java.
I set matched value in the String two to duplicate char '#',because don't want to match another char.
public static void main(String[] args) {
Scanner s= new Scanner(System.in);
String team1 = s.next();
String team2 = s.next();
char[] teamA = team1.toCharArray();
char[] teamB = team2.toCharArray();
Arrays.sort(teamB);
int count = 0;
for(int a=0;a< teamA.length;a++) {
int index = Arrays.binarySearch(teamB, teamA[a]);
if(index >= 0) {
count++;
teamB[index] = '#';
}
}
System.out.println(count);
}
if i give input of two strings
"aabc" and "zbaa" expected output is 3
but my program gives output 2.
The problem is that once you update the teamB array in the loop the array is no longer sorted. And in unsorted array binary search will give unexpected outputs.
This is the original prompt:
I need to write a program that gets a comma-delimited String of integers (e.g. “4,8,16,32,…”) from the user at the command line and then converts the String to an ArrayList of Integers (using the wrapper class) with each element containing one of the input integers in sequence. Finally, use a for loop to output the integers to the command line, each on a separate line.
This is the code that I have so far:
import java.util.Scanner;
import java.util.ArrayList;
public class Parser {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
ArrayList<String> myInts = new ArrayList<String>();
String integers = "";
System.out.print("Enter a list of delimited integers: ");
integers = scnr.nextLine();
for (int i = 0; i < myInts.size(); i++) {
integers = myInts.get(i);
myInts.add(integers);
System.out.println(myInts);
}
System.out.println(integers);
}
}
I am confused on where to go with the rest of this program. If someone could help explain to me what I need to do, that would be much appreciated!
As Matthew and Marc pointed out you have to first split the string into tokens and then parse each token to transform them into Integers.
You could try it with something like this:
String stringOfInts = "1,2,3,4,5";
List<Integer> integers = new ArrayList<>();
String[] splittedStringOfInts = stringOfInts.split(",");
for(String strInt : splittedStringOfInts) {
integers.add(Integer.parseInt(strInt));
}
// do something with integers
In the split() method you define how to split the string into tokens. In your case it's simply the comma (,) sign.
Hope this helps.
Regards Patrick
I need to input n numbers, store them in a variable and make them available for later processing.
Constraints:
1. Any number of SPACES between successive inputs.
2. The count of inputs would be UNKNOWN.
3. Input set should not exceed 256KB and should be between 0<= i <=10^18
Example Input:
100
9
81
128
1278
If I understand your question, then yes. One way, is to use a Scanner, and hasNextDouble()
Scanner scan = new Scanner(System.in);
List<Double> al = new ArrayList<>();
while (scan.hasNextDouble()) { // <-- when no more doubles, the loop will stop.
al.add(scan.nextDouble());
}
System.out.println(al);
if you're input is all coming in on one line like in your text, you could do something like:
import java.util.ArrayList;
public class Numbers
{
public static void main(String[] args)
{
ArrayList<Double> numbers = new ArrayList<Double>();
String[] inputs = args[0].split(" ");
for (String input : inputs)
{
numbers.add(Double.parseDouble(input));
}
//do something clever with numbers array list.
}
}
I am trying to split a user inputed set, such as { 1 2 3 4 }, as a string, into an array list so that when I print out the array list it will read {1, 2, 3, 5}. Here is my code so far. I am not really sure how the Scanner.next() method works, but I am attempting to use it. This is for a small portion of my program. Actually it's like the beginning.
import java.util.Scanner;
import java.util.ArrayList;
public class practice {
public static void main (String[]args){
Scanner stdIn = new Scanner (System.in);
String set;
String set2 = "";
System.out.print("Enter set:");
set = stdIn.nextLine();
if(set.charAt(0) == '{'){
for(int i =1; i<set.length(); i++){
set2 += set.charAt(i);
}
}
else if(set.charAt(1) == '{'){
for(int i = 2; i <set.length();i++){
set2 += set.charAt(i);
}
}
System.out.print(set2);
ArrayList<Integer> array = new ArrayList<Integer>();
while(stdIn.next() != "}"){
set2 = stdIn.next();
array.add(Integer.parseInt(set2));
}
System.out.print(array);
}
}
You should use the String.split(String) and String.replaceAll(String, String) methods in String in order to do a lot of what your code currently does.
You can get the user input as you are currently doing it, with stdIn.nextLine();, but afterward, you can do the string processing in an easier way.
First, you should remove the unnecessary characters, and end up with just a sequence of numbers separated by spaces.
You can do this by simply calling the replaceAll method, and provide the regular expression, which is really simple in this case.
Then you can call the String.split method to find each element in the set.
String in = stdIn.nextLine();
// Need to escape the characters because
// these characters mean something special in regular expressions
String filtered = userInput.replaceAll("(\\[\\{\\}\\],"," ");
String[] numbers = filtered.split("\\s+");
ArrayList <Integer> myNumbers = new ArrayList <Integer> ( numbers.length );
for ( String number : numbers )
myNumbers.add ( Integer.parseInt ( number ) );
UPDATE
If you need to use a scanner, you can use a scanner for the String that has been filtered
Scanner s = new Scanner ( filtered );
ArrayList <Integer> myNumbers = new ArrayList < Integer > ();
while ( s.hasNext() )
{
myNumbers.add(s.nextInt());
}
Perhaps you should use Java's split method on a string.
EDIT:
If you are required to use scanner, you might want to start off something like:
String input = "foobar";
Scanner s = new Scanner(input);
and then probably iterate on s using a while loop and the hasNext method. Inside this loop, you will possibly need to use one of the next methods in Java's scanner api to work with each token as string. If you only want to print things out, then you don't really need to add tokens to an arraylist. You can directly use System.out.print(). In any case, its well worth working this out on your own and exploring the scanner api.
You could shorten your while statement by taking in straight "ints" instead of actually passing then converting strings, like:
while (stdIn.next() != '}') {
array.add(stdIn.nextInt());
}
However, you'd require some error handling to make sure you actually got ints just in case your user passed in something else. However, if you're wanting to print the integers as strings it may be better to use an String array instead of an Integer array.