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.
Related
My goal is to read and print the words separately from standard input, without having to store them in an array or list.
I want this:
input: sun moon cloud
output:
sun moon cloud (each word in a different line)
The following program keep waiting after printing "cloud". I don't know what the problem is
`
import java.util.Scanner;
class RandomWord{
public static void main(String[] args){
String palavra;
Scanner s = new Scanner(System.in);
while(s.hasNext()){
palavra = s.next();
System.out.println(palavra);
}
}
}
`
You continuously reading the scanner.
You have to read by scanner out of loop. For example 3 times invoking s.next().
Or create some loop end condition, for example text, "END".
If you pass all words in one line use .readLine()
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.
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.
How do I use Scanner to read in a series of Strings from the keyboard, all on one line, and concatenate them.
Here is the code I have so far:
import java.util.Scanner;
public class Exam12Practice {
public static void main(String[] args)
{
Scanner input=new Scanner(System.in);
String words="";
System.out.println("enter a word");
while(input.hasNext())
{
words = words.concat(input.next());
}
System.out.println(words);
}
}
Your code already does what you are asking. To get it to work
Type in your words
Press Enter
Press CTRL-Z (^D on *nix systems)
Some points to note:
input.hasNext() will always return true for STDIN so just pressing Enter on its own won't work.
You could have used input.readLine() and split the words for your exercise.
Most people would probably prefer to use StringBuilder because of the improved performance it provides over String.concat.
Please have a look at the following code. It is my attempt to manage the given numbers in ascending order.
import java.io.*;
import java.util.*;
import java.util.ArrayList;
public class TurboSort
{
public static void main(String[]args)
{
List<Integer> numbers = new ArrayList();
Scanner scan = new Scanner(System.in);
while(scan.hasNextInt())
{
numbers.add(scan.nextInt());
}
Collections.sort(numbers);
System.out.println(numbers);
}
}
insert the input as 2,1,6,7,3
Hit enter.
Now, the scanner hasn't exited from the while loop because it is not giving any output. What am I doing here wrong? Even if you manage to get it, the output is surrounded by brackets like " [1] [2] [3] ". Why is that? Is that is because I didn't call 'Integer.parseInt()' ?. Please help me with those 2 questions.
Thanks.
The result of hitting enter will be a line separator, whose characters are treated as delimiters (by default, see Character.isWhitespace()) and are skipped. Thus the Scanner is waiting for further input, which never arrives and the hasNextInt() will block. Enter something which is not an integer, like a . for example, to cause the loop to terminate:
1 2 5 3 7 .
This loop will never exit (as long as you enter integers) as there is no break condition
while(scan.hasNextInt()){
numbers.add(scan.nextInt());
}
If you want your loop to stop, say for example you need to acquire only 5 integers then you could do this:
while(scan.hasNextInt()){
numbers.add(scan.nextInt());
if(numbers.size() == 5) break;
}
The Scanner continues to scan until the end of input has reached, or until it fails to read (e.g. when a non integer is detected in the text).
Hit ctrl + D after you hit enter.
You can separate the numbers any white space.
If you want to have the input on only 1 line like 2,1,6,7,3, probably would be easier to use nextLine() of the scanner:
Scanner scan = new Scanner(System.in);
String consoleInput = scan.nextLine();
This will terminate the scanner, once you hit enter. At this point, you have the input in a String, you have to parse that string and get out all the numbers.
Also note that you have forgotten to parameterize your ArrayList().
Here's a possible adaptation of your source code:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String consoleInput = scan.nextLine();
List<Integer> numbers = new ArrayList<Integer>();
if (consoleInput.length() > 0 && consoleInput.contains(",")) {
String[] numbersAsStrings = consoleInput.split(",");
for (String tNumberAsString : numbersAsStrings) {
try {
int tNumber = Integer.parseInt(tNumberAsString);
numbers.add(tNumber);
} catch (NumberFormatException nfe) {
System.out.println(tNumberAsString + " is not a number");
}
}
Collections.sort(numbers);
System.out.println(numbers);
} else {
System.out.println("Nothing to sort!");
System.out.println(numbers);
}
}
}
Your code should work. You just need to add a way to break out of the loop. It also is a good idea to keep your scanned value in a local variable in case you need to reference it again.
maybe add:
while(scan.hasNextInt()){
int i=scan.nextInt();
if(i==-1)
break;
numbers.add(i);
}