Splitting a scanner string - java

import java.io.IOException;
import java.util.Scanner;
public class web_practice {
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
Scanner scanner = new Scanner(System.in);
String input = scanner.next();
int l = input.indexOf(' ');
String cmd = input.substring(0, l);
String end = input.substring(l);
if (cmd.equals("define"));
java.awt.Desktop.getDesktop().browse(java.net.URI.create("http://dictionary.reference.com/browse/" + end));
}
}
I was trying to make a code to find the definition of a word by connecting it to dictionary.com and checking if they say the word "define" as the first word?
The splitting is not working.

public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
Scanner scanner = new Scanner(System.in);
String input = scanner.next();
int words[] = input.split(' ');
if (words[0].equalsIgnoreCase("define")) {
java.awt.Desktop.getDesktop().browse(java.net.URI.create("http://dictionary.reference.com/browse/" + words[0]));
}
}

import java.io.*;
public class Sol {
public static void main(String[] args) throws IOException
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String[] input = new String[2];
input = in.readLine().split(" ");
int a;
int b;
a = Integer.parseInt(input[0]);
b = Integer.parseInt(input[1]);
System.out.println("You input: " + a + " and " + b);
}
}

this code will work for you
String[] strArr = input.split(" ") ;
if(strArr[0].equals("define"){
}

Your problem is that you are using Scanner which default behavior is to split the InputStream by whitespace. Thus when you call next(), your input string contains the command only, not the whole line. Use Scanner.nextLine() method instead.
Also take a note that String end = input.substring(l); will add a space into the end string. You probably want to use String end = input.substring(l+1);. Here's the fixed main method:
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
int l = input.indexOf(' ');
if(l >= 0) {
String cmd = input.substring(0, l);
String end = input.substring(l+1);
if (cmd.equals("define"));
java.awt.Desktop.getDesktop().browse(
java.net.URI.create("http://dictionary.reference.com/browse/" + end));
}
}

Scanner scanner = new Scanner(System.in);
String input = scanner.next();;
String[] inputs = input.split(" ");
if (inputs[0].equalsIgnoreCase("define")){ java.awt.Desktop.getDesktop().browse(java.net.URI.create("http://dictionary.reference.com/browse/" ));}

The problem I see in your code is using scanner.next(); the next() method will read the next token without space for ex for console input define blabla the value of input variable would be define ie without space so in your case there is no space character so input.indexOf(' '); will return -1 giving exception for substring() a quickfix would be change the line scanner.next(); to scanner.nextLine(); which would read the whole line rather than token.

Related

how to print the number of "and" words in a file for java

I am supposed to print the number of "and" words in a file, but I only know how to count the number of tokens and lines in a file. My program can only print the number of tokens in a file...
import java.util.*;//for Scanner
import java.io.*;//for file
public class Hamlet2
{
public static void main (String[] args) throws FileNotFoundException
{
File filename = new File("hamlet.txt");
Scanner read = new Scanner(filename);
int andCount = 0;//to count word "and"
while(read.hasNext())//read words
{
String token = read.Next();
andCount++;
}
System.out.println("Total number of "and" words: " + andCount);
}
}
What about this?
public static int countWord(File fileName, String word) throws FileNotFoundException
{
int count = 0;
fileName = file.trim();
Scanner scanner = new Scanner(fileName);
while (scanner.hasNext()) {
String nextWord = scanner.next().trim();
if (nextWord.equals(word)) {
++count;
}
}
return count;
}

How to use hasNext() from the Scanner class?

Input Format
Read some unknown n lines of input from stdin(System.in) until you reach EOF; each line of input contains a non-empty String.
Output Format
For each line, print the line number, followed by a single space, and then the line content received as input:
Sample Output
Hello world
I am a file
Read me until end-of-file.
Here is my solution. The problem being I am not able to proceed till EOF.
But the output is just:
Hello world
Here is my code:
public class Solution {
public static void main(String[] args) {
check(1); // call check method
}
static void check(int count) {
Scanner s = new Scanner(System.in);
if(s.hasNext() == true) {
String ns = s.nextLine();
System.out.println(count + " " + ns);
count++;
check(count);
}
}
}
Your code does not work because you create a new Scanner object in every recursive call.
You should not use recursion for this anyways, do it iteratively instead.
Iterative version
public class Solution {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int count = 1;
while(s.hasNext()) {
String ns = s.nextLine();
System.out.println(count + " " + ns);
count++;
}
}
}
Recursive version
public class Solution {
private Scanner s;
public static void main(String[] args) {
s = new Scanner(System.in); // initialize only once
check(1);
}
public static void check(int count) {
if(s.hasNext()) {
String ns = s.nextLine();
System.out.println(count + " " + ns);
check(count + 1);
}
}
}
Change
if (s.hasNext() == true) {
String ns = s.nextLine();
System.out.println(count + " " + ns);
count++;
System.out.print(count);
check(count);
}
to:
while (s.hasNext()) {
String ns = s.nextLine();
System.out.println(count + " " + ns);
count++;
System.out.print(count);
check(count);
}
while loops continues until the data exists, where as if checks for only once.
Scanner is kind of a BufferedReader (I'm not telling about inheritance or something. I'm telling they both have buffers. Scanner has just a small one). So after you enter text in the Console, those are read() from System.in and stored in the buffer inside the Scanner.
public static void main(String[] args) {
Scanner s1 = new Scanner(System.in);
s1.hasNext();
Scanner s2 = new Scanner(System.in);
while(true){
System.out.println("Read line:: " + s2.nextLine());
}
}
Use the following input to the Scanner:
line 1
line 2
line 3
line 4
You will get the output:
Read line:: e 1
Read line:: line 2
Read line:: line 3
Read line:: line 4
I think you might know the reason to this output. Some characters of the first line are in the Scanner s1. Therefore don't create 2 Scanners to take input from same Stream.
You can change your code as follows to get required output.
private static Scanner s;
public static void main(String[] args) {
s = new Scanner(System.in);
check(1); // call check method
}
static void check(int count) {
if (s.hasNextLine()) {
String ns = s.nextLine();
System.out.println(count + " " + ns);
count++;
check(count);
}
}
You can use s.hasNextLine() instead of s.hasNext() as you are reading line by line.
No need to use s.hasNextLine()==true as that statement will be true if and only if s.hasNextLine() is true.
You can give EOF character to the console using Ctrl+Z in Windows system and Ctrl+D in Unix. As I know, you can't send EOF character using the output window of NetBeans.
If using recursion is a requirement, you can use a helper function:
static void check(int count) {
Scanner s = new Scanner(System.in);
check(count, s);
}
static void check(int count, Scanner scanner) {
if(!scanner.hasNext()) {
return;
}
String ns = scanner.nextLine();
System.out.println(count + " " + ns);
check(++count, scanner);
}
Notice how new Scanner(System.in) is only called once.
public static void main(String[] args) {
List<String> eol = new ArrayList<String>();
Scanner in=new Scanner(System.in);
int t=1;
while(in.hasNext()){
eol.add(in.nextLine());
}
for (String i:eol){
System.out.println(t+" "+i);
t++;
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int count = 1;
while(scan.hasNext()){
System.out.println(count++ + " " + scan.nextLine());
}
}
Here is the error free program.
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int count = 1;
while(scan.hasNext()) {
String s = scan.nextLine();
System.out.println(count + " " + s);
count++;
}
}
}
Scanner scanner = new Scanner(System.in);
int i = 1;
while(scanner.hasNext()) {
System.out.println(i + " " + scanner.nextLine());
i++;
}
Use while instead of if,but recursive version is better.Here is iterative version:
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner sc=new Scanner(System.in);
{
int i=0;
while(sc.hasNext()==true)
{
i=i+1;
String s=sc.nextLine();
System.out.println(i+" "+s);
};
}
}
}
java.util.Scanner.hasNext() basically helps you to read the input. This method returns true if this Scanner has another token of any type in its input. Returns false otherwise.
Check below code snippet,
while(sc.hasNext()) {
System.out.println(i + " " + sc.nextLine());
i++;
}
You can find complete code at below link,
https://github.com/hetalrachh/HackerRank/blob/master/Practice/Java/Introduction/EndOfFile.java
you can try like this to get desired result:
public class EOF {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
for(int i =1;scan.hasNext();i++) {
String line = scan.nextLine();
System.out.println(i + " " + line);
}
scan.close();
}
}
public class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
for(int i=1; scan.hasNext() ;
System.out.println(i++ +" "+scan.nextLine()));
}
}

how to take a value main method and use it in different method

Basically, I want to use to put a value into main and set it up so I can use the word/words entered into main so I can use the code.
public static String L33TLanguageSupport(String s) {
Scanner scan =new Scanner (s);
char o = 0;
char O=0;
char e=0, E=0, a=0, A= 0;
return s
.replace(o, (char) 0)
.replace(O,(char) 0)
.replace(e, (char) 3)
.replace(E,(char) 3)
.replace(a, (char)4)
.replace(A, (char)4);
}
public static void main (String[] arg) {
System.out.println(L33TLanguageSupport("cow life" ));
}
You need to read the user input using Scanner in your desired method, then retrieve the result into a variable and send it to another method.
Adapted from your posted code:
public static String L33TLanguageSupport(String s) {
//remove this from here
//Scanner scan =new Scanner (s);
//do what it must do...
}
public static void main (String[] arg) {
//System.out.println(L33TLanguageSupport("cow life" ));
//creating the scanner to read user input
Scanner scanner = new Scanner(System.in);
//showing a nice message to user
System.out.print("Enter a word: ");
//reading the user input (the whole line until user press Enter key)
String input = scanner.readLine();
//applying the method to user input
String output = L33TLanguageSupport(input);
//showing to user the result of the processing
System.out.println("Result: " + output);
//closing the scanner resources
scanner.close();
}
You could get the same by doing java main cow life and then passing in those arguments to the L33tLanguagesupport object concat'd together.
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
for(String arg : args) sb.append(arg).append(" ");
System.out.println(sb.toString().trim());
}

Removing inserted numbers from a String in java

Ok, so i have created a program that defines if the inserted word is a palindrome or not.
But i need help on removing numbers that where to be inserted in the string.
import java.util.*;
import java.util.Scanner;
class Palindrome
{
public static void main(String args[])
{
String reverse = "";
Scanner scan = new Scanner(System.in);
System.out.print("Type a sentence and press enter: ");
String input = scan.nextLine();
// use regex to remove the punctuation and spaces
String Input = input.replaceAll("\\W", " ");
System.out.println(Input);
int length = input.length();
for ( int i = length - 1 ; i >= 0 ; i-- )
reverse = reverse.replaceAll("\\W", "") + input.charAt(i);
System.out.println(reverse);
if (input.equals(reverse))
System.out.println("Entered string is a palindrome.");
else
System.out.println("Entered string is not a palindrome.");
}
}
If you want to remove digits, try input.replaceAll("[0-9]","")
Try this........
public class T1 {
public static void main(String[] args){
String s = "1234ajhdhols233adfjal";
String[] arr = s.split("\\d");
String sx = new String();
for(String x : arr){
sx = sx+x;
}
System.out.println(sx);
}
}
Example:
public static void main(String[] args) {
String s = "1234ajhdhols233adfjal";
String str = s.replaceAll("\\d", "");
System.out.println(str);
}

Getting the number of occurrences of one string in another string

I need to input a two strings, with the first one being any word and the second string being a part of the previous string and i need to output the number of times string number two occurs. So for instance:String 1 = CATSATONTHEMAT String 2 = AT. Output would be 3 because AT occurs three times in CATSATONTHEMAT. Here is my code:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String word8 = sc.next();
String word9 = sc.next();
int occurences = word8.indexOf(word9);
System.out.println(occurences);
}
It outputs 1 when I use this code.
Interesting solution:
public static int countOccurrences(String main, String sub) {
return (main.length() - main.replace(sub, "").length()) / sub.length();
}
Basically what we're doing here is subtracting the length of main from the length of the string resulting from deleting all instances of sub in main - we then divide this number by the length of sub to determine how many occurrences of sub were removed, giving us our answer.
So in the end you would have something like this:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String word8 = sc.next();
String word9 = sc.next();
int occurrences = countOccurrences(word8, word9);
System.out.println(occurrences);
sc.close();
}
You could also try:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String word8 = sc.nextLine();
String word9 = sc.nextLine();
int index = word8.indexOf(word9);
sc.close();
int occurrences = 0;
while (index != -1) {
occurrences++;
word8 = word8.substring(index + 1);
index = word8.indexOf(word9);
}
System.out.println("No of " + word9 + " in the input is : " + occurrences);
}
Why no one posts the most obvious and fast solution?
int occurrences(String str, String substr) {
int occurrences = 0;
int index = str.indexOf(substr);
while (index != -1) {
occurrences++;
index = str.indexOf(substr, index + 1);
}
return occurrences;
}
Another option:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String word8 = sc.next();
String word9 = sc.next();
int occurences = word8.split(word9).length;
if (word8.startsWith(word9)) occurences++;
if (word8.endsWith(word9)) occurences++;
System.out.println(occurences);
sc.close();
}
The startsWith and endsWith are required because split() omits trailing empty strings.

Categories