Java - How to read integers separated by a space into an array - java

I am having trouble with my project because I can't get the beginning correct, which is to read a line of integers separated by a space from the user and place the values into an array.
System.out.println("Enter the elements separated by spaces: ");
String input = sc.next();
StringTokenizer strToken = new StringTokenizer(input);
int count = strToken.countTokens();
//Reads in the numbers to the array
System.out.println("Count: " + count);
int[] arr = new int[count];
for(int x = 0;x < count;x++){
arr[x] = Integer.parseInt((String)strToken.nextElement());
}
This is what I have, and it only seems to read the first element in the array because when count is initialized, it is set to 1 for some reason.
Can anyone help me? Would it be better to do this a different way?

There is only a tiny change necessary to make your code work. The error is in this line:
String input = sc.next();
As pointed out in my comment under the question, it only reads the next token of input. See the documentation.
If you replace it with
String input = sc.nextLine();
it will do what you want it to do, because nextLine() consumes the whole line of input.

String integers = "54 65 74";
List<Integer> list = new ArrayList<Integer>();
for (String s : integers.split("\\s"))
{
list.add(Integer.parseInt(s));
}
list.toArray();

This would be a easier way to do the same -
System.out.println("Enter the elements seperated by spaces: ");
String input = sc.nextLine();
String[] split = input.split("\\s+");
int[] desiredOP = new int[split.length];
int i=0;
for (String string : split) {
desiredOP[i++] = Integer.parseInt(string);
}

There are alternate ways to achieve the same. but when i tried your code, it seems to work properly.
StringTokenizer strToken = new StringTokenizer("a b c");
int count = strToken.countTokens();
System.out.println(count);
It prints count as 3. default demiliter is " "
I dont know how are you getting your input field. May be it is not returning the complete input in string format.
I think you are using java.util.Scanner for reading your input
java doc from scanner.
A Scanner breaks its input into tokens using a delimiter pattern,
which by default matches whitespace. The resulting tokens may then be
converted into values of different types using the various next
methods.
Hence the input is returning just one Integer and leaving the rest unattended
Read this. Scanner#next(), You should use Scanner#nextLine() instead

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
.
.
.
StringTokenizer st = new StringTokenizer(br.readLine());
int K = Integer.parseInt(st.nextToken());
int N= Integer.parseInt(st.nextToken());

Related

Hanging Letter Program

I was practicing problems in JAVA for the last few days and I got a problem like this:
I/p: I Am A Good Boy
O/p:
I A A G B
m o o
o y
d
This is my code.
System.out.print("Enter sentence: ");
String s = sc.nextLine();
s+=" ";
String s1="";
for(int i=0;i<s.length();i++)
{
char c = s.charAt(i);
if(c!=32)
{s1+=c;}
else
{
for(int j=0;j<s1.length();j++)
{System.out.println(s1.charAt(j));}
s1="";
}
}
The problem is I am not able to make this design.My output is coming as each character in each line.
First, you need to divide your string with space as a delimiter and store them in an array of strings, you can do this by writing your own code to divide a string into multiple strings, Or you can use an inbuilt function called split()
After you've 'split' your string into array of strings, just iterate through the array of strings as many times as your longest string appears, because that is the last line you want to print ( as understood from the output shared) i.e., d from the string Good, so iterate through the array of strings till you print the last most character in the largest/ longest string, and exit from there.
You need to handle any edge cases while iterating through the array of strings, like the strings that does not have any extra characters left to print, but needs to print spaces for the next string having characters to be in the order of the output.
Following is the piece of code that you may refer, but remember to try the above explained logic before reading further,
import java.io.*;
import java.util.*;
public class MyClass {
public static void main(String args[]) throws IOException{
//BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Scanner sc = new Scanner(System.in);
String[] s = sc.nextLine().split(" ");
// Split is a String function that uses regular function to split a string,
// apparently you can strings like a space given above, the regular expression
// for space is \\s or \\s+ for multiple spaces
int max = 0;
for(int i=0;i<s.length;i++) max = Math.max(max,s[i].length()); // Finds the string having maximum length
int count = 0;
while(count<max){ // iterate till the longest string exhausts
for(int i=0;i<s.length;i++){
if(count<s[i].length()) System.out.print(s[i].charAt(count)+" "); // exists print the character
else System.out.print(" "); // Two spaces otherwise
}
System.out.println();count++;
}
}
}
Edit: I am sharing the output below for the string This is a test Input
T i a t I
h s e n
i s p
s t u
t

countTokens() always returns 1 with user input

Before we begin, I don't believe this is a repeat question. I've read the question entitled StringTokenzer countTokens() returns 1 with any string, but that does not address the fact that a properly delimited string is counted correctly, but a properly delimited input is not.
When using the StringTokenizer class I've found that the countTokens method returns different outcomes depending on the whether the argument in countTokens was a defined String or a user defined String. For example, the following code prints the value 4.
String phrase = "Alpha bRaVo Charlie delta";
StringTokenizer token = new StringTokenizer(phrase);
//There's no need to specify the delimiter in the parameters, but I've tried
//both code examples with " " as the delimiter with identical results
int count = token.countTokens();
System.out.println(count);
But this code will print the value 1 when the user enters:Alpha bRaVo Charlie delta
Scanner in = new Scanner(System.in);
String phrase;
System.out.print("Enter a phrase: ");
phrase = in.next();
StringTokenizer token = new StringTokenizer(phrase);
int count = token.countTokens();
System.out.println(count);
Use in.nextLine() instead of in.next();
Scanner in = new Scanner(System.in);
String phrase;
System.out.print("Enter a phrase: ");
phrase = in.nextLine();
System.out.print(phrase);
StringTokenizer token = new StringTokenizer(phrase);
int count = token.countTokens();
System.out.println(count);
Print phrase and check that in.next() is returning "Alpha".
As suggested above, Use in.nextLine().
You could try using an InputStreamReader, instead of the Scanner:
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String phrase = "";
System.out.print("Enter a phrase: ");
try {
phrase = in.readLine();
} catch (IOException e) {
e.printStackTrace();
}
StringTokenizer token = new StringTokenizer(phrase);
int count = token.countTokens();
System.out.println(count);
nextLine() of Scanner also got the job done for me, though.
If you want the delimiter to be a space-character specifically, you might want to pass it to the constructor of StringTokenizer. It will use " \t\n\r\f" otherwise (which includes the space-character, but might not work as expected if e.g. the \n-character is also present inside the phrase).
If you check the value of phrase, after invoking in.next(), you will see that's equal to "Alpha". By definition, Scanner's next() reads the next token.
Use in.nextLine() instead.

Java String - How to get chars until and after space

I'm load to variable string using:
Scanner scanner = new Scanner(System.in);
x = scanner.nextLine();
String always looks like: "Random Example". I want to grab first word (before space) for one variable and second word (after space) to next one variable. Can someone show me example?
You can get split a String using .split(String s) and put it in a String[]
String editMe;
Scanner user_input = new Scanner( System.in );
editMe = user_input.nextLine();
String[] edit1 = editMe.split(" ");
If you would like to see the values in the System you can use
int i =0;
for(String s:edit1)
{
System.out.println(s);
i++;
}
See more information on the String variable and how to use it here.
Input obtained from scanning the input stream can be split based on the space character.
Scanner scanner = new Scanner(System.in);
String x = scanner.nextLine();
String array[] =x.split(" ");
In this way, the words are stored in array.

Java Scanner while loop

I'm trying to take in a string input which consists of multiple lines of numbers separated by ',' and ';' .
Example:
1,2;3,4;5,6;
9,8;7,6;
0,1;
;
Code:
ArrayList<Integer> alist = new ArrayList<>();
String delims = ";|\\,";
int i = 0;
Scanner input = new Scanner(System.in);
input.useDelimiter(delims);
while (input.hasNext()) {
alist.add(i, input.nextInt());
System.out.print(i + ' ');
System.out.print(alist.get(i) + '\n');
i++;
}
System.out.print('x');
When I run this in eclipse:
1,2;3,4;5,6; ( <= what i typed in console)
321133123413351436153716 ( <= output)
I'd expect something more like:
0 1
1 2
2 3
3 4
4 5
5 6
x
Why am I getting this sort of output?
One problem is that System.in is basically an infinite stream: hasNext will always return true unless the user enters a special command that closes it.
So you need to have the user enter something that tells you they are done. For example:
while(input.hasNext()) {
System.out.print("Enter an integer or 'end' to finish: ");
String next = input.next();
if("end".equalsIgnoreCase(next)) {
break;
}
int theInt = Integer.parseInt(next);
...
For your program, you might have the input you are trying to parse end with a special character like 1,2;3,4;5,6;end or 1,2;3,4;5,6;# that you check for.
And on these lines:
System.out.print(i + ' ');
System.out.print(alist.get(i) + '\n');
It looks like you are trying to perform String concatenation but since char is a numerical type, it performs addition instead. That is why you get the crazy output. So you need to use String instead of char:
System.out.print(i + " ");
System.out.print(alist.get(i) + "\n");
Or just:
System.out.println(i + " " + alist.get(i));
Edit for comment.
You could, for example, pull the input using nextLine from a Scanner with a default delimiter, then create a second Scanner to scan the line:
Scanner sysIn = new Scanner(System.in);
while(sysIn.hasNextLine()) {
String nextLine = sysIn.nextLine();
if(nextLine.isEmpty()) {
break;
}
Scanner lineIn = new Scanner(nextLine);
lineIn.useDelimiter(";|\\,");
while(lineIn.hasNextInt()) {
int nextInt = lineIn.nextInt();
...
}
}
Since Radiodef has already answered your actual problem(" instead of '), here are a few pointers I think could be helpful for you(This is more of a comment than an answer, but too long for an actual comment):
When you use Scanner, try to match the hasNextX function call to the nextX call. I.e. in your case, use hasNextInt and nextInt. This makes it much less likely that you will get an exception on unexpected input, while also making it easy to end input by just typing another delimiter.
Scanners useDelimiter call returns the Scanner, so it can be chained, as part of the initialisation of the Scanner. I.e. you can just write:
Scanner input = new Scanner(System.in).useDelimiter(";|\\,");
When you add to the end of an ArrayList, you don't need to(and usually should not) specify the index.
int i = 0, i++ is the textbook example of a for loop. Just because your test statement doesn't involve i does not mean you should not use a for loop.
Your code, with the above points addressed becomes as follows:
ArrayList<Integer> alist = new ArrayList<>();
Scanner input = new Scanner(System.in).useDelimiter(";|\\,");
for (int i = 0; input.hasNextInt(); i++) {
alist.add(input.nextInt());
System.out.println(i + " " + alist.get(i));
}
System.out.println('x');
Edit: Just had to mention one of my favorite delimiters for Scanner, since it is so suitable here:
Scanner input = new Scanner(System.in).useDelimiter("\\D");
This will make a Scanner over just numbers, splitting on anything that is not a number. Combined with hasNextInt it also ends input on the first blank line when reading from terminal input.

User enters numbers separated by spaces, tabs, or new lines

I am in an beginner java programming class and am stuck on something I know should be simple, but it's killing me. The user is prompted to enter any number of x,y values and can be entered separated by a space, a tab, or a new line. So it can be entered like this:
1.0 1.0 2.0 2.0 3.0 3.0 etc...
or
1.0 (tab) 1.0 (tab) 2.0 (tab) 2.0 (tab) etc...
or
1.0 1.0
2.0 2.0
3.0 3.0
etc...
Well that's fine and great but I don't know how to separate these numbers. I'm thinking of having an x var and a y var and would like to separate them into this, but how do I do this? My first thought was maybe an array but we haven't even covered those yet. I feel like this is ridiculously easy and I'm just missing it
If you take the input as a String you could do something like
String[] input = inputString.split(" ");
Then convert each element to your desired type.
You're going to want to use a regular expression for this - find all white space in the string, then split on that.
String[] vals = t1.split("[\\s]+");
\s is the whitespace character regex search pattern.
You can split a string up by space using the following:
String[] parts = userinput.split(" ");
You can split a string up by tab using the following:
String[] parts = userinput.split("\t");
You can split a string up by line return using the following:
String[] parts = userinput.split("\n");
note: you may beed to add a '/r' to the above \n
So, find your delimiter, split your string by that using one of the above (or more if needed)
then you should have all your data in a String array
I can offer you to use scanner. You can set your delimeters that can be entered.
Scanner s = new Scanner("This is a , test word \n ");
s.useDelimiter(",|\\n");
while(s.hasNext()){
System.out.println(s.next());
}
Here you go. [ \t] is a regular expression meaning either a space or a tab.
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
while (line != null && !line.isEmpty())
{
String[] arr = line.split("[ \t]");
for (int i = 0; i < arr.length; i += 2)
{
doSomething(Double.parseDouble(arr[i]), Double.parseDouble(arr[i+1]));
}
line = br.readLine();
}
}
static void doSomething(double x, double y)
{
System.out.println("x is "+x+", y is "+y);
}
You may want to also include some error checking.
you can use BufferedReader + Scanner to read data that are separated by spaces or newlines:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Scanner input = new Scanner(br);
& read the numbers one by one using Scanner , which will wait until it meets a number then read it no matter what is separating them a space or a new line
int numbersCount = 5; //numbersCount is the count of the numbers you are wanting to read from the input , so if you are waiting 5 numbers then it will be 5.
int[] numbers = new int[numbersCount];
for (int i=0;i<numbersCount;i++)
{
numbers[i] = input.nextInt();
}
so the array numbers will contain all the numbers you want isA
hope this helps

Categories