How to read comma separated integer inputs in java - java

import java.io.*;
import java.util.*;
class usingDelimiters
{
public static void main(String args[])
{
Scanner dis=new Scanner(System.in);
int a,b,c;
a=dis.nextInt();
b=dis.nextInt();
c=dis.nextInt();
System.out.println("a="+a);
System.out.println("b="+b);
System.out.println("c="+c);
}
}
This program is working fine when my input is 1 2 3 (separated by space)
But, how to modify my program when my input is 1,2,3 (separated by commas)

You can use a delimiter for non-numerical items, which will mark any non-digit as delimiter.
Such as:
dis.useDelimiter("\\D");
The useDelimiter method takes a Pattern or the String representation of a Pattern.
Full example:
Scanner dis=new Scanner(System.in);
dis.useDelimiter("\\D");
int a,b,c;
a=dis.nextInt();
b=dis.nextInt();
c=dis.nextInt();
System.out.println(a + " " + b + " " + c);
dis.close();
Inputs (either or)
1,2,3
1 2 3
Output
1 2 3
Note
Don't forget to close your Scanner!
See the API for Patterns for additional fun delimiting your input.

you can use the nextLine method to read a String and use the method split to separate by comma like this:
public static void main(String args[])
{
Scanner dis=new Scanner(System.in);
int a,b,c;
String line;
String[] lineVector;
line = dis.nextLine(); //read 1,2,3
//separate all values by comma
lineVector = line.split(",");
//parsing the values to Integer
a=Integer.parseInt(lineVector[0]);
b=Integer.parseInt(lineVector[1]);
c=Integer.parseInt(lineVector[2]);
System.out.println("a="+a);
System.out.println("b="+b);
System.out.println("c="+c);
}
This method will be work with 3 values separated by comma only.
If you need change the quantity of values may you use an loop to get the values from the vector.

Related

How do I process different delimiters in a RegEx expression with Java?

I am working on creating a program for my course, in which I am required to divide the string: This;is;the;first;line;;This;is;the;second;line!;;;;Done!;;.
In the requirements, I need to read a single semicolon as a space, and a double semicolon as a new line. How do I create a regular expression in the useDelimiter() method that allows me to parse through and differentiate between both ; and ;;? Thank you!
Assignment Excerpt:
Instead of hard-coding the string, this time you will read it from the console. Study the useDelimiter() method and use it to set the delimiter for the scanner input. This time allow either colons or semicolons as the delimiters. One might prefer to use the String Tokenizer here, but don’t -- use the Scanner’s useDelimiter() method to set the delimiter in the Scanner and process each token as it comes.
import java.util.Scanner;
public class Hw3p2 {
public static void main(String[] args) {
// Initializes scanner class.
Scanner input = new Scanner(System.in);
// Prompts user for input.
System.out.println("Enter the string you wish to filter & parse: ");
// Reads user input.
String filterString = input.nextLine();
// Initiates new scanner reading the user inputted string.
Scanner a = new Scanner(filterString);
a.useDelimiter(";|;;");
System.out.printf("\n");
// Loop that parses through string while there are more tokens.
while(a.hasNext()) {
System.out.print(a.next());
}
}
}
The Expected output is to be:
You may use this code:
public class Hw3p2 {
public static void main(String[] args) {
// Initializes scanner class.
Scanner input = new Scanner(System.in).useDelimiter(";;");
// Prompts user for input.
System.out.print("Enter the string you wish to filter & parse: ");
// Reads user input.
while(input.hasNext()) {
String filterString = input.next();
//System.err.println("filterString: " + filterString);
// Initiates new scanner reading the user inputted string.
Scanner a = new Scanner(filterString).useDelimiter(";");
// Loop that parses through string while there are more tokens.
while(a.hasNext()) {
System.out.print(a.next() + " ");
}
System.out.println();
a.close();
}
input.close();
}
}
Output:
Enter the string you wish to filter & parse: This;is;the;first;line;;This;is;the;second;line!;;;;Done!;;
This is the first line
This is the second line!
Done!
Note use of outer scanner with delimiter ;; and an inner one with ;.

How to read a string input containing spaces using Scanner and print it out in Java?

How can I accept the string as input in Java from the user by using the Scanner class that includes spaces and printing the accepted input with spaces?
Here is my code so far:
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int i = scan.nextInt();
double j=scan.nextDouble();
String k=scan.next.split(' ');
// Write your code here.
System.out.println("String: " + k);
System.out.println("Double: " + j);
System.out.println("Int: " + i);
}
}
This is a--input
This is a--output
I don't quite understand what problem you are experiencing, but I advise you to read all strings like this:
String myString = scan.nextLine();
If you want to split it on every space, then just do it like this:
String[] mySplitString = myString.split(" ");
Note that the method above accepts a string variable and not a char variable. You have to store split strings into an array of strings (String[]), because the split method will generate one or multiple strings, depending on how many spaces there are in an input.
You can use nextLine() function of Scanner Class.
Like this:-
Scanner s = new Scanner(System.in);
String str = s.nextLine(); //for getting input
System.out.print(str); //for Printing
Hope this will help you.

Use scanner to read inputs next to a certain word

Here is an example of such input.
A 3
B 1
A 2 etc.
As shown above, each input is separated by a line and appears an indeterminate amount of times.
How do I only read the numbers next to the 'A' and convert it all into a string using Scanner?
You can write something like:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main29 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
String string = scanner.next();
int number = scanner.nextInt();
System.out.println(number);
}
}
}
output:
3
1
2
As you can see I just write a loop which works until scanner can read token from STDIN. Inside of loop I read String tokens use next method and then read Integer tokens use nextInt method.
I think now you can add and required logic to the loop i.e. print numbers after A as you wish.

A java program to find out the frequrncy of a word using Scanner class

Can any one tell me that how to use Scanner Class of Java to find the frequency of a word in a sentence.
I am confused as to enter a line in java i have to use nextInt() function but to compare need it to convert in char so how to do so.
For example:-
I enter on terminal window(Giving Input)
This is my cat.
Now i have to find the FREGUENCY of word "this" in the above sentence. Please can you give me some idea.REMEMBER THE RESTRICTION IMPOSED ON IT IS I HAVE TO USE ONLY SCANNER CLASS OF JAVA LIBRARY
PROGRAMME USING STREAM READER IS AS FOLLOWS-
import java.io.*;
class FrequencyCount
{
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the String: ");
String s=br.readLine();
System.out.println("Enter substring: ");
String sub=br.readLine();
int ind,count=0;
for(int i=0; i+sub.length()<=s.length(); i++)
//i+sub.length() is used to reduce comparisions
{
ind=s.indexOf(sub,i);
if(ind>=0)
{
count++;
i=ind;
ind=-1;
}
}
System.out.println("Occurence of '"+sub+"' in String is "+count);
}
}
alternative solution using pattern
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class JavaApplication20 {
public static void main(String [] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a sentence:\t");
String sentence = scanner.nextLine();
System.out.print("Enter a word:\t");
String word = scanner.nextLine();
Pattern p = Pattern.compile(word);
Matcher m = p.matcher(sentence);
int count = 0;
while (m.find()){
count +=1;
}
System.out.println("in your sentence the frequency of \""+word+"\" is:\t" + count);
}
}
try out this.
public class JavaApplication20 {
public static void main(String [] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a sentence:\t");
String sentence = scanner.nextLine();
System.out.print("Enter a word:\t");
String word = scanner.nextLine();
int count = 0;
while (!sentence.equals("")){
if(sentence.contains(word)){ // check if the word is in the sentence; if yes cut the sentence at the index of the first appearance of the word plus word length
// then check the rest of the sentence for more appearances
sentence = sentence.substring(sentence.indexOf(word)+word.length());
count++;
}
else{
sentence = "";
}
}
System.out.println("in your sentence the frequency of \""+word+"\" is:\t" + count);
}
}
You can enter a String too using Scanner Class . Here is your code that i modified , and it working . `
public static void main(String args[]) throws IOException
{
Scanner in=new Scanner(System.in);
System.out.println("Enter the String: ");
String s=in.nextLine();
System.out.println("Enter substring: ");
String sub=in.nextLine();
int ind,count=0;
for(int i=0; i+sub.length()<=s.length(); i++)
//i+sub.length() is used to reduce comparisions
{
ind=s.indexOf(sub,i);
if(ind>=0)
{
count++;
i=ind;
ind=-1;
}
}
System.out.println("Occurence of '"+sub+"' in String is "+count);
}
The nextLine() method of Scanner class let you input Strings.
Don't listen to #Uzochi. His answers may work, but they're way too complicated and may actually slow your program down.
For the Scanner class, there are multiple ways of reading in numbers or text:
nextInt() - scans in the next integer value
nextDouble() - scans in the next double value
nextLine() - scans in the next line of text
https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html - scroll down to method summary, and in the middle of all of the methods, you will find all of the "next" methods.
Note that there is a small bug with Scanner (at least with the last time I used it). Say you're using a Scanner called scan. If you call
scan.nextInt();
scan.nextLine();
(which reads in an integer and then a line of text), your Scanner will skip the call to nextLine(). This is a small bug that can easily be fixed by adding another nextLine(). It will catch the second nextLine.
In response to #Uzochi, there is a much simpler solution to your algorithm. Your algorithm is actually faster than his, although there are some small things that could make your program run a tiny bit faster:
1) Use a while loop instead of a for loop. Your use of indexOf() makes the current index of the String s you're at skip forward a lot, so there's virtually no point in having a for loop. You can easily change it into a while loop. Your conditions would be to keep checking if indexOf() returns a non-negative value (-1 means there is no value), and you increment that index value by 1 (like the for loop does automatically).
2) Smaller thing - you don't need the line:
ind=-1;
Your current code will always modify ind before it hits that if statement, so there is virtually no reason to have this line in the program.
EDIT - #Uzochi may be using Java's built in libraries, but for a beginner like OP, you should be learning how to use for and while loops to efficiently write code.

Handling user input using Scanner

I'm trying to retrieve user input through a single line of input: e.g 5,6,4,8,9 using scanner Delimiter for the comma.How do i retrieve an arbitrary amount of integers using this type of input? That is, without having to ask the user how many integers they wish to enter. Here is the code i have been using, but cannot have the while loop break when i want it to break. Note that i keep System.out to keep track of where the program is currently running. The one part that baffles is that, i can get the user inputs in this format, but the program stops and asks for user input once again, then if input is one integer, it asks for more input until user inputs a longer stream of inputs (at least 2,6 + enter) then outputs the string "called break" then "outside of while loop".
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class Lab1 {
/**
* #param args
* #throws IOException
* #throws NumberFormatException
*/
#SuppressWarnings("resource")
public static void main(String[] args) throws NumberFormatException, IOException {
// TODO Auto-generated method stub
ArrayList<Integer> numbers = new ArrayList<Integer>();
int numberList;
Scanner scanner = new Scanner(System.in);
scanner.useDelimiter(",");
System.out.print("Enter integers: ");
while(scanner.hasNext())//------------------------while loop------
{
if(scanner.hasNextInt())
{
numberList = scanner.nextInt();
numbers.add(numberList);
System.out.println(numbers.toString() + " " + numbers.size());
}
else
{
System.out.println("called break");
break;
}
System.out.println("Inside of while loop");
}//-------------------------------------------------end of while loop------
System.out.println("outside of the while loop now");
}
}
Input: 1,2,3,4,5
Enter integers: 1,2,3,4,5
[1] 1
Inside of while loop
[1, 2] 2
Inside of while loop
[1, 2, 3] 3
Inside of while loop
[1, 2, 3, 4] 4
Inside of while loop
I'm still inside the while loop even though there is no integer after the 5 and the programs is waiting for more input, now if i insert a non integer value in the end i get the same exact thing. after these two result, once the user inputs more value (1,2) the program exits the while loop and completes successfully. How do can i make the while loop break once i'm done entering integer using the comma delimiter method?
I know this not answers your question, but it's another way to do the intended:
Here the split(delimiter) method is used, which will return a String[] array. Then in a for loop, use Integer.parseInt() to convert the Strings into integers:
public static void main(String[] args)
{
ArrayList<Integer> numbers = new ArrayList<Integer>();
int numberList;
Scanner scanner = new Scanner(System.in);
scanner.useDelimiter(",");
System.out.print("Enter integers: ");
String[] parts = scanner.nextLine().split(",");
// Add int's to the array 'numbers'
for (String s : parts) {
numbers.add(Integer.parseInt(s)); // Convert String to Integer
}
}
I would recommend reading comma seperated numbers as a String using scanner.nextLine() , then splitting the String using "," , then using Integer.parseInt() to get integer values of numbers. This way, you can input as many numbers as you want without prior definition of "numberCount".

Categories

Resources