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

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

Related

Not able to assign a text for a string in array using split method

I have a question about my split function inside the file reading function.
Here is my code. I tried to use split to put these text in to array. But the problem is I have this error. java.lang.NumberFormatException: For input string: "Sug" at java.base/java.lang.NumberFormatException.forInputString
public static SLL<train> readFile() {
SLL<train> list = new SLL();
try {
FileReader fr = new FileReader("Train.dat");
BufferedReader br = new BufferedReader(fr);
String line = "";
while (true) {
line = br.readLine();
if (line == null) {
break;
}
String[] text = line.split(" | ");
String tcode = text[0];
String train_name = text[1];
int seat = Integer.parseInt(text[2]);
int booked = Integer.parseInt(text[3]);
double depart_time = Double.parseDouble(text[4]);
String depart_place = text[5];
train t = new train(tcode, train_name, seat, booked, depart_time, depart_place);
list.addLast(t);
}
br.close();
fr.close();
} catch (Exception e) {
e.printStackTrace();
}
return list;
This is my text file:
"SUG" should be added into train name because I declared train_name as a string.I think this error only appears when declaring the wrong data type, "12" should be added into seat, "3" should be added into booked, and so on. Can you guys explained to me what happened to "SUG". Thanks a lot :(
Note that String.split(regex) uses a regex to find the split location, i.e. it splits before and after any match produced by the regular expression.
Furthermore, in regex the pipe (|) has the special meaning "or" so your code right now reads as "split on a space or a space". Since this splits on spaces only, splitting "B03 | Sug | 12 ..." will result in the array ["B03","|","Sug","|","12",...] and hence text[2] yields "Sug".
Instead you need to escape the pipe by either using line.split(" \\| ") or line.split(Pattern.quote(" | ")) to make it "split on a sequence of space, pipe, space". That would then result in ["B03","Sug","12",...].
However, you also might need to surround Integer.parseInt() etc. with a try-catch block or do some preliminary checks on the string because you might run into a malformed file.
In addition to what #Thomas has said, it would be a whole lot easier to use a Scanner
sc.useDelimiter("\\s*\\|\\s*");
while (sc.hasNext()) {
Train t = new Train(sc.next(), sc.next(), sc.nextInt(), sc.nextInt(), sc.nextDouble(), sc.next());
}
Naming is important in Java for readability and maintenance
Note class names begin upper case in Java. There's no place for underscores except for as separators for blocks of capitals in the name of a constant.

InputStreamReader, Buffered Reader, Java issue with reading standard input

I have a standard input that contains lines of text. Each line contains 2 numbers that are separated by a comma. I need to separate the two numbers so that I can use them in another function. I don't know what would be a good way to read each line, separate the numbers and then use them to call function until there are no more lines to be read. I read the documentation regarding InputStreamReader and BufferedReader, however, since I'm relatively new to java they didn't make much sense.
public static void main(String[] args) throws IOException {
InputStreamReader reader = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(reader);
try {
double num1 = Double.parseDouble(in.readLine());
double num2 = Double.parseDouble(in.readLine());
Main.function(num1,num2);
}
When you call in.readLine() then you get a string, probably something like "42.1,100.2". The next step would be splitting the string and after that you can convert the split string(s) to numbers.
String line = in.readLine(); // read one line
String[] parts = line.split(","); // split the line around the comma(s)
double num1 = Double.parseDouble(parts[0]); // convert the first part to double
double num2 = Double.parseDouble(parts[1]); // convert the second part to double
Main.function(num1, num2);
Note that this only reads from one line in the file (many lines -> looping) and that this only works correctly when the input is well formatted. You probably want to lookup the trim() method on String.
Double is not recognize the commas instead you will have to take the input string and replace all commas with empty strings. e.g. you have this input
String input = "123,321.3" ;
input = input.replaceAll("," , "");
in result you will have this
input -> "123321.3"
Then you can parse the string to double.
Hope it will help.
Regards , Erik.

Is there a function in Java that allows you to transform a string to an Int considering the string has chars you want to ignore?

I'm doing a project for a Uni course where I need to read an input of an int followed by a '+' in the form of (for example) "2+".
However when using nextInt() it throws an InputMismatchException
What are the workarounds for this as I only want to store the int, but the "user", inputs an int followed by the char '+'?
I've already tried a lot of stuff including parseInt and valueOf but none seemed to work.
Should I just do it manually and analyze char by char?
Thanks in advance for your help.
Edit: just to clear it up. All the user will input is and Int followed by a + after. The theme of the project is to do something in the theme of a Netflix program. This parameter will be used as the age rating for a movie. However, I don't want to store the entire string in the movie as it would make things harder to check if a user is eligible or not to watch a certain movie.
UPDATE: Managed to make the substring into parseInt to work
String x = in.nextLine();
x = x.substring(0, x.length()-1);
int i = Integer.parseInt(x);
Thanks for your help :)
Try out Scanner#useDelimiter():
try(Scanner sc=new Scanner(System.in)){
sc.useDelimiter("\\D"); /* use non-digit as separator */
while(sc.hasNextInt()){
System.out.println(sc.nextInt());
}
}
Input: 2+33-599
Output:
2
33
599
OR with your current code x = x.substring(0, x.length()-1); to make it more precise try instead: x = x.replaceAll("\\D","");
Yes you should manually do it. The methods that are there will throw a parse exception. Also do you want to remove all non digit characters or just plus signs? For example if someone inputs "2 plus 5 equals 7" do you want to get 257 or throw an error? You should define strict rules.
You can do something like: Integer.parseInt(stringValue.replaceAll("[^\d]","")); to remove all characters that are no digits.
Hard way is the only way!
from my Git repo line 290.
Also useful Javadoc RegEx
It takes in an input String and extracts all numbers from it then you tokenize the string with .replaceAll() and read the tokens.
int inputLimit = 1;
Scanner scan = new Scanner(System.in);
try{
userInput = scan.nextLine();
tokens = userInput.replaceAll("[^0-9]", "");
//get integers from String input
if(!tokens.equals("")){
for(int i = 0; i < tokens.length() && i < inputLimit; ++i){
String token = "" + tokens.charAt(i);
int index = Integer.parseInt(token);
if(0 == index){
return;
}
cardIndexes.add(index);
}
}else{
System.out.println("Please enter integers 0 to 9.");
System.out.print(">");
}
Possible solutions already have been given, Here is one more.
Scanner sc = new Scanner(System.in);
String numberWithPlusSign = sc.next();
String onlyNumber = numberWithPlusSign.substring(0, numberWithPlusSign.indexOf('+'));
int number = Integer.parseInt(onlyNumber);

Count words in a String that is NOT in a string array without using split method

I need to count the words in a String. For many of you that seems pretty simple but from what I've read in similar questions people are saying to use arrays but I'd rather not. It complicates my program more than it helps as my string is coming from an input file and the program cannot be hardwired to a specific file.
I have this so far:
while(input.hasNext())
{
String sentences = input.nextLine();
int countWords;
char c = " ";
for (countWords = 0; countWords < sentences.length(); countWords++)
{
if (input.hasNext(c))
countWords++;
}
System.out.println(sentences);
System.out.println(countWords);
}
The problem is that what I have here ends up counting the amount of characters in the string. I thought it would count char c as a delimiter. I've also tried using String c instead with input.hasNext but the compiler tells me:
Program04.java:39: incompatible types
found : java.lang.String[]
required: java.lang.String
String token = sentences.split(delim);
I've since deleted the .split method from the program.
How do I delimit (is that the right word?) without using a String array with a scanned in file?
Don't use the Scanner (input) for more than one thing. You're using it to read lines from a file, and also trying to use it to count words in those lines. Use a second Scanner to process the line itself, or use a different method.
The problem is that the scanner consumes its buffer as it reads it. input.nextLine() returns sentences, but after that it no longer has them. Calling input.hasNext() on it gives you information about the characters after sentences.
The simplest way to count the words in sentences is to do:
int wordCount = sentences.split(" ").length;
Using Scanner, you can do:
Scanner scanner = new Scanner(sentences);
while(scanner.hasNext())
{
scanner.next();
wordCount++;
}
Or use a for loop for best performance (as mentioned by BlackPanther).
Another tip I'd give you is how to better name your variables. countWords should be wordCount. "Count words" is a command, a verb, while a variable should be a noun. sentences should simply be line, unless you know both that the line is composed of sentences and that this fact is relevant to the rest of your code.
Maybe, this is what you are looking for.
while(input.hasNext())
{
String sentences = input.nextLine();
System.out.println ("count : " + line.split (" ").length);
}
what you are trying to achieve is not quite clear. but if you are trying to count the number of words in your text file then try this
int countWords = 0;
while(input.hasNext())
{
String sentences = input.nextLine();
for(int i = 0; i< sentences.length()-1;i++ ) {
if(sentences.charAt(i) == " ") {
countWords++;
}
}
}
System.out.println(countWords);

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

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());

Categories