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
Related
I am new to Stackoverflow and this is my first time asking a question. I have searched my problem thoroughly, however, could not find an appropriate answer. I am sorry if this has been asked. Thank you in advance.
The question is from Hyperskill.com as follows:
Write a program that reads five words from the standard input and outputs each word in a new line.
First, you need to print all the words from the first line, then from the second (from the left to right).
Sample Input 1:
This Java course
is adaptive
Sample Output 1:
This
Java
course
is
adaptive
My trial to solve it
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
/* I have not initialized the "userInput" String.
* I know that String is immutable in Java and
* if I initialize it to an empty String ""
* and read a String from user.
* It will not overwrite to the "userInput" String.
* But create another String object to give it the value of the user input,
* and references the new String object to "userInput".
* I didn't want to waste memory like that.
*/
String userInput;
String[] userInputSplitFirstLine = new String[3];
String[] userInputSplitSecondLine = new String[2];
Scanner scan = new Scanner(System.in);
userInput = scan.nextLine();
userInputSplitFirstLine = userInput.split("\\s+");
userInput = scan.nextLine();
userInputSplitSecondLine = userInput.split("\\s+");
for(String firstLineSplitted: userInputSplitFirstLine) {
System.out.println(firstLineSplitted);
}
for(String secondLineSplitted: userInputSplitSecondLine) {
System.out.println(secondLineSplitted);
}
scan.close();
}
}
If you try the sample input above, the output will match the sample output above. However, if you write more than 3 words to the first line and/or more than 2 words to the second line, the userInputSplitFirstLine array of size 3 will store more than 3 words. Same goes with the userInputSplitSecondLine array also. My first question is how can an array of size 3 (userInputSplitFirstLine) and an array of size 2 (userInputSplitSecondLine) can hold more than 3 and 2 elements, respectively? My second question is that how can I restrict/limit the number of words that the user can insert in a line; for example, the first line only accepts 3 words and the second line only accepts 2 words?
Also the answer to this question suggested by Hyperskill.com is as follows:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String wordOne = scanner.next();
String wordTwo = scanner.next();
String wordThree = scanner.next();
String wordFour = scanner.next();
String wordFive = scanner.next();
System.out.println(wordOne);
System.out.println(wordTwo);
System.out.println(wordThree);
System.out.println(wordFour);
System.out.println(wordFive);
}
}
You can use next method of scanner object to read string and then it can be printed easily on new line.
while(true){
if(scanner.hasNext()){
System.out.println(scanner.next());
}
else{
break;
}
}
I think this should do the work. Don't hesitate to ask, if you have some questions.
import java.util.Scanner;
class App {
public static void main(String[] args) {
final StringBuffer line = new StringBuffer();
final StringBuffer words = new StringBuffer();
try (final Scanner sc = new Scanner(System.in)) {
while (sc.hasNextLine()) {
final String currentLine = sc.nextLine();
line.append(currentLine).append(System.lineSeparator());
for (final String word : currentLine.split("\\s+")) {
words.append(word).append(System.lineSeparator());
}
}
} finally {
System.out.println(line.toString());
System.out.println();
System.out.println(words.toString());
}
}
}
My first question is how can an array of size 3 (userInputSplitFirstLine) and an array of size 2 (userInputSplitSecondLine) can hold more than 3 and 2 elements, respectively?
The array here:
String[] userInputSplitFirstLine = new String[3];
is not the same one as the one you got from split:
userInputSplitFirstLine = userInput.split("\\s+");
When you do the above assignment, the old array that was in there is basically "overwritten", and now userInputSplitFirstLine refers to this new array that has a length independent of what the old array had. split always return a new array.
My second question is that how can I restrict/limit the number of words that the user can insert in a line; for example, the first line only accepts 3 words and the second line only accepts 2 words?
It really depends on what you mean by "restrict". If you just want to check if there are exactly three words, and if not, exit the program, you can do this:
userInputSplitFirstLine = userInput.split("\\s+");
if (userInputSplitFirstLine.length != 3) {
System.out.println("Please enter exactly 3 words!");
return;
}
You can do something similar with the second line.
If you want the user to be unable to type more than 3 words, then that's impossible, because this is a command line app.
By the way, the code in the suggested solution works because next() returns the next "word" (or what we generally think of as a word, anyway) by default.
hope this will help you!
public class pratice1 {
public static void main (String[]args) {
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String input1 = sc.nextLine();
char[]a =input.toCharArray();
char[]a1 = input1.toCharArray();
System.out.println(input +""+ input1);
int a2=0;
if(input!=null) {
for(int i=0;i<input.length();i++) {
if(a[i]==' ') {
a2=i;
for(int j=0;j<a2;j++) {
System.out.println(a[i]);
a2=0;
}
}
else System.out.print(a[i]);
}System.out.println("");
for(int i=0;i<input1.length();i++) {
if(a1[i]==' ') {
a2=i;
for(int j=0;j<a2;j++) {
System.out.println(a1[i]);
a2=0;
}
}
else System.out.print(a1[i]);
}
}
}
}
To solve the problem:
Write a program that reads five words from the standard input and
outputs each word in a new line.
This was my solution:
while(scanner.hasNext()){
System.out.println(scanner.next());
}
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)
I'm very new to Java but this has had me stumped for the last half an hour or so. I'm reading in lines from a text file and storing them as String Arrays. From here I'm trying to use the values from within the arrays to be used to initialise another class I have. To initialise my Route class (hence using routeName) I need to take the first value from the array and pass it as a string. When I try to return s[0] for routeName, I'm given the last line of from my text file. Any ideas on how to fix this would be greatly appreciated. I'm in the process of testing still so thats why my code is barely finished.
My text file is as follows.
66
Uq Lakes, Southbank
1,2,3,4,5
2,3,4,5,6
and my code:
import java.io.*;
import java.util.*;
public class Scan {
public static void main(String args[]) throws IOException {
String routeName = "";
String stationName = " ";
Scanner timetable = new Scanner(new File("fileName.txt"));
while (timetable.hasNextLine()) {
String[] s = timetable.nextLine().split("\n");
routeName = s[0];
}
System.out.println(routeName);
}
}
The method you are calling timetable.nextLine.split("\n") will return the Array of String.
So every time when you call this method is overwrites your array with new line in file and as the last line is added finally in your array you are getting the lat line at the end.
below is the code you can use.
public static void main(String[] args) throws FileNotFoundException {
String routeName = "";
Scanner timetable;
int count = 0;
String[] s = new String[10];
timetable = new Scanner(new File("fileName.txt"));
while (timetable.hasNextLine()) {
String line = timetable.nextLine();
s[count++] = line;
}
routeName = s[0];
System.out.println(routeName);
}
Scanner.nextLine() returns a single line so splitting by '\n' will always give a single element array, e.g.:
timetable.nextLine().split("\n"); // e.g., "1,2,3,4,5" => ["1,2,3,4,5"]
Try splitting by the ',' instead, e.g.:
timetable.nextLine().split(","); // e.g., "1,2,3,4,5" => ["1", "2", "3", "4", "5"]
NOTE: If you are intending for the array to contain individual lines, then check out this SO post.
Scanner s = new Scanner(new File(filename));
List<String> lines = new ArrayList<String>(); // A List can be dynamically resized
while(s.hasNextLine()) lines.add(s.nextLine()); // Store each line in the list
String[] arr = lines.toArray(new String[0]); // If you really need an Array, use this
Your while loop itterates over all lines and sets the current line to the routeName. Thats why you habe the last line in you string. What you could do is calling a break, when you habe read the first line oft the file. Then you will have the first line.
I'm trying to use a Delimiter to pull out the first numbers in a document with 31 rows looking something like "105878-798##176000##JDOE" and put it in an int array.
The numbers I'm interesed in are "105878798", and the number of numbers is not consistent.
I wrote this but can't figure out how to change the line when i reach the first delimiter (of the line).
import java.util.*;
import java.io.*;
public class Test {
public static void main(String[] args) throws Exception {
int n = 0;
String rad;
File fil = new File("accounts.txt");
int[] accountNr = new int[31];
Scanner sc = new Scanner(fil).useDelimiter("##");
while (sc.hasNextLine()) {
rad = sc.nextLine();
rad.replaceAll("-","");
accountNr[n] = Integer.parseInt(rad);
System.out.println(accountNr[n]);
n++;
System.out.println(rad);
}
}
}
Don't use the scanner for this, use the StringTokenizer and set the delimiter to ##, then just keep calling .nextElement() and you will get the next number no matter how long it is.
StringTokenizer st2 = new StringTokenizer(str, "##");
while (st2.hasMoreElements()) {
log.info(st2.nextElement());
}
(Of course, you can iterate in different ways..)
I would suggest for each line use line.split("[#][#]")[0] (of course haldle your exceptions).
also, rad.replaceAll(...) returns a new String, because String is an imutable object. you should execute parseInt on the returned String and not on rad.
just use the following instead of the equivalent 2 lines in your code:
String newRad = rad.replaceAll("-","");
accountNr[n] = Integer.parseInt(newRad);
Okay, so I'm making a program and I want to take an input for a license plate # (Numbers and Letters) and what I'm looking to do is, take the input in one line, and be able to separate the Numbers and Letters in the input into two different variables, one Int and one String.
public class CarRental {
public static String model;
public static String plate;
public static int platenum;
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Car Model:");
model = input.nextLine();
System.out.println("License Plate: ");
plate = input.nextLine();
...
I want to assign the numbers from the input to the int and keep the characters in the string plate?
What would be the way I can do this?
Any help is greatly appreciated.
You usually use regex for these types of things. Have a look at Java regex (http://docs.oracle.com/javase/tutorial/essential/regex/)
Use this:
How to split a string between letters and digits (or between digits and letters)?
Like this for example:
licensePlate = "JGY7433";
licensePlateLetters = licensePlate.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)")[0];
licensePlateNumber = Integer.parseInt(licensePlate.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)")[1]);
Here is an example using regular expressions:
String s = "A1B2C3";
List<String> letters = new ArrayList<String>();
List<Integer> numbers = new ArrayList<Integer>();
Pattern pLetters=Pattern.compile("([A-Za-z])"), pNumbers=Pattern.compile("(\\d)");
Matcher mLetters=pLetters.matcher(s), mNumbers=pNumbers.matcher(s);
while (mLetters.find()) { letters.add(mLetters.group(1)); }
while (mNumbers.find()) { numbers.add(Integer.parseInt(mNumbers.group(1))); }
System.out.println("OK: letters=" + letters); // => OK: letters=[A, B, C]
System.out.println("OK: numbers=" + numbers); // => OK: numbers=[1, 2, 3]