I'm pretty much a complete newbie when it comes to Java. I've dabbled a bit in python and VB.net, and that's about it.
I'm trying to write a program in java that literally reads the user's input and displays it back to them with this code:
import java.util.Scanner;
public class InputTesting
{
public static void main( String[] args )
{
Scanner input = new Scanner ( System.in );
String str1;
System.out.println("Input string: ");
str1 = input.nextString();
System.out.println( str1 );
}
}
And I get the error:
InputTesting.java:13: error: cannot find symbol
str1 = input.nextString();
^
symbol: method nextString()
location: variable input of type Scanner
1 error
Can someone tell what why it's not compiling? Thanks!
input.nextString();
There is no method called nextString in the Scanner class. That's why you're getting the error cannot find symbol.
Try
input.nextLine(); // If you're expecting the user to hit enter when done.
input.next(); // Just another option.
import java.util.Scanner;
public class InputTesting
{
public static void main( String[] args )
{
Scanner input = new Scanner ( System.in );
String str1;
System.out.println("Input string: ");
str1 = input.next();
System.out.println( str1 );
}
}
You may use one of input.nextXXX() as detailed in Scanner javadoc. to resolve compiler error
in your case
you may use input.nextLine(); get entire line of text.
By Default whitespace delimiter used by a scanner. However If you need to scan sequence of inputs separated by a delimiter useDelimiter can be used to set regex delim
public static void main(String[] args) {
try (Scanner input = new Scanner(System.in);) {
input.useDelimiter(";");
while (input.hasNext()) {
String next = input.next();
if ("DONE".equals(next)) {
break;
}
System.out.println("Token:" + next);
}
}
}
Input
1a;2b;3c;4d;5e;DONE;
Output
Token:1a
Token:2b
Token:3c
Token:4d
Token:5e
Just be cautious while scanning decimal and signed numbers as scanning is Locale Dependent
You need to rather use method nextLine(). This methods prints entire line. By using next() it will print only one word in your sentence.
// That's how i managed solution for input a string
import java.util.Scanner;
public class PalindromeWord {
public static void main(String[] args) {
//System.out.println("Enter a string: ");
Scanner input = new Scanner(System.in);
String S = input.next();
String reverseStr = "";
int strLength = S.length();
for (int i = (strLength - 1); i >=0; --i) {
reverseStr = reverseStr + S.charAt(i);
}
if (S.equals(reverseStr)) {
System.out.println("Yes");
}
else {
System.out.println("No");
}
}
}
Related
The program should allow a user to enter a string, a substring they wish to find and
another string with which they wish to replace the found substring.
The output of your program should be similar to the output given below:
Please enter a string: Hello world
Please enter the substring you wish to find: llo
Please enter a string to replace the given substring: ##
Your new string is: he## world
I am new to Java and cant find and so far this is what I have:
import java.util.Scanner;
public class searchReplace
{
static String word, substring, newWord;
static String output = "";
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Please enter a string: ");
word = input.next();
System.out.println("Please enter the substring you wish to find: ");
substring = input.next();
System.out.println("Please enter a string to replace the given substring: ");
newWord = input.next();
replace(substring,newWord);
input.close();
}
private static void replace(String substring, String newWord)
{
if(output.contains(newWord))
{
System.out.println(output);
}
else
{
output = word.replaceAll("substring","newWord");
replace(substring,newWord);
}
}
}
I Get The Error:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.contains(java.lang.CharSequence)" because "searchReplace.output" is null
at searchReplace.replace(searchReplace.java:33)
at searchReplace.main(searchReplace.java:21)
For your goal, you need to use just:
output = word.replace(substring, newWord);
instead of:
word.replaceAll("substring", "newWord");
You don't need to make any recursion. Replace function will replace your substring inside word with the newWord for each occurence.
Recursion is not needed:
public static void main(String [] args) {
try (Scanner scanner = new Scanner(System.in)) {
System.out.println("Enter String: ");
String input = scanner.nextLine();
System.out.println("String to replace: ");
String toReplace = scanner.nextLine();
System.out.println("Replace with: ");
String replaceWith = scanner.nextLine();
System.out.println(input.replaceAll(toReplace, replaceWith));
}
}
i have figured out a way to replace vowels into * but it only converts the first line
input:
break
robert
yeah
output:
br**k
here is the code
public class Solution {
public static void main(String[] args) {
String enterWord;
Scanner scan = new Scanner (System.in);
enterWord = scan.nextLine();
enterWord = enterWord.replaceAll("[aeiou]", "*");
System.out.println(enterWord);
}
}
is there any way that it reads all three words?
Your code works as you want (in:break robert yeah out: br**k r*b*rt y**h) on my env(Windows10, java1.8.0_271), maybe you can set a breakpoint on enterWord = enterWord.replaceAll("[aeiou]", "*"); and check is the enterWord recived whole input string.
You need a loop to keep getting and processing the inputs. Also, I suggest you use (?i) with the regex to make it case-insensitive.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String enterWord, answer = "y";
Scanner scan = new Scanner(System.in);
do {
System.out.print("Enter a word: ");
enterWord = scan.nextLine();
enterWord = enterWord.replaceAll("(?i)[aeiou]", "*");
System.out.println("After replacing vowels with * it becomes " + enterWord);
System.out.print("Do you wish to conntinue[y/n]: ");
answer = scan.nextLine();
} while (answer.equalsIgnoreCase("y"));
}
}
A sample run:
Enter a word: hello
After replacing vowels with * it becomes h*ll*
Do you wish to conntinue[y/n]: y
Enter a word: India
After replacing vowels with * it becomes *nd**
Do you wish to conntinue[y/n]: n
For a single string spanning multiple lines, the method, String#replaceAll works for the entire string as shown below:
public class Main {
public static void main(String[] args) {
String str = "break\n" +
"robert\n" +
"yeah";
System.out.println(str.replaceAll("(?i)[aeiou]", "*"));
}
}
Output:
br**k
r*b*rt
y**h
Using this feature, you can build a string of multiple lines interactively and finally change all the vowels to *.
Demo:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String text = "";
Scanner scan = new Scanner(System.in);
StringBuilder sb = new StringBuilder();
System.out.println("Keep enter some text (Press Enter without any text to stop): ");
while (true) {
text = scan.nextLine();
if (text.length() > 0) {
sb.append(text).append(System.lineSeparator());
} else {
break;
}
}
System.out.println("Your input: \n" + sb);
String str = sb.toString().replaceAll("(?i)[aeiou]", "*");
System.out.println("After converting each vowel to *, your input becomes: \n" + str);
}
}
A sample run:
Keep enter some text (Press Enter without any text to stop):
break
robert
yeah
Your input:
break
robert
yeah
After converting each vowel to *, your input becomes:
br**k
r*b*rt
y**h
So below is my code. I'm trying to use the Scanner class to read an input from the console, and then print out each token on a separate line. But there's a small problem where the user has to input twice. An example of what happens is given below the code
import java.util.Scanner;
public class StringSort {
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a string: ");
String str = scanner.nextLine();
int i = 0;
while (i< str.length()) {
i++;
System.out.println("" + scanner.next());
}
scanner.close();
}
}
Example:
Enter a string:
what is love
what is love
what
is
love
To do what you want use the Scanner class to read an input from the console, and then print out each token on a separate line you can use the String::split method
String str = scanner.nextLine();
String [] arr = str.split (" ");
for (String x : arr) {
System.out.println (x);
}
A more efficient implementation of the above code would be as follows:
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
System.out.println(sc.next());
}
This would avoid use of extra space as done by #ScaryWombat
Scanner should be propertly closed:
try (Scanner sc = new Scanner(System.in)) {
while (sc.hasNext()) {
System.out.println(sc.next());
}
}
I was solving HackerRank "30 Days Of Code" problem 8.
This is the code I wrote:
import java.util.*;
import java.io.*;
public class Directory
{
public static void main(String args[])throws NoSuchElementException
{
Scanner sc=new Scanner(System.in);
//System.out.println("Enter number");
int n=sc.nextInt();
sc.nextLine();
Map<String,String> Directory= new HashMap<String,String>();
for (int i=0;i<n;i++)
{
//System.out.println("Enter name and phone number");
String name=sc.next();
String ph=sc.next();
sc.nextLine();
Directory.put(name,ph);
}
while(sc.hasNext())
{
String s = sc.next();
sc.nextLine();
String phoneNumber = Directory.get(s);
System.out.println((phoneNumber != null) ? s + "=" + phoneNumber : "Not found");
}
}
}
When I run this code with the custom input I get an error as follows:
Exception in thread "main" java.util.NoSuchElementException: No line
found at java.util.Scanner.nextLine(Scanner.java:1585) at
Directory.main(Directory.java:23)
I think this is occurring due to the "sc.nextLine()" in the while loop. But I'm not able to figure out why. I had learnt from here that I should use sc.nextLine() after using sc.next() so that the control is transferred to the next line of input. Any ideas where I am going wrong?
From Documentation:
public String next() Finds and returns the next complete token from
this scanner. A complete token is preceded and followed by input that
matches the delimiter pattern
And also from the Documentation of Scanner:
A Scanner breaks its input into tokens using a delimiter pattern,
which by default matches whitespace
And whitespace includes \n and \r.
So as a conclusion, using nextLine() to workaround the newline problem is valid in case of nextInt() but it is not in case of using next().
I think this will work for you. Try it :)
You do not need this line sc.nextLine();
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter number");
int n=sc.nextInt();
Map<String,String> directory= new HashMap<>();
for (int i=0;i<n;i++)
{
System.out.println("Enter name and phone number");
String name=sc.next();
String ph=sc.next();
sc.nextLine();
directory.put(name,ph);
}
while(sc.hasNext())
{
String s = sc.next();
sc.nextLine();
String phoneNumber = directory.get(s);
System.out.println((phoneNumber != null) ? s + "=" + phoneNumber : "Not found");
}
}
I'm working on a Chat Bot project, and I'm almost done, other than the fact that whenever I enter an input, it returns multiple outputs depending on the length of the input X.
Here is the source code:
import java.util.*;
public class ChatBot
{
public static String getResponse(String value)
{
Scanner input = new Scanner (System.in);
String X = longestWord(value);
if (value.contains("you"))
{
return "I'm not important. Let's talk about you instead.";
}
else if (X.length() <= 3)
{
return "Maybe we should move on. Is there anything else you would like to talk about?";
}
else if (X.length() == 4)
{
return "Tell me more about " + X;
}
else if (X.length() == 5)
{
return "Why do you think " + X + " is important?";
}
return "Now we are getting somewhere. How does " + X + " affect you the most?";
}
private static String longestWord(String value){
Scanner input = new Scanner (value);
String longest = new String();
"".equals(longest);
while (input.hasNext())
{
String temp = input.next();
if(temp.length() > longest.length())
{
longest = temp;
}
}
return longest;
}
}
This is for testing the Chat Bot:
import java.util.Scanner;
public class Test {
public static void main (String [ ] args)
{
Scanner input = new Scanner (System.in);
ChatBot e = new ChatBot();
String prompt = "What would you like to talk about?";
System.out.println(prompt);
String userInput;
userInput = input.next();
while (!userInput.equals("Goodbye"))
{
System.out.println(e.getResponse(userInput));
userInput = input.next();
}
}
}
I am also trying to modify the Bot so it counts the number of times it has responded; and also modify it so it randomly returns a random response depending on the length of the input. Any help will be much appreciated. Thank You!
You are using the Scanner.next method which only returns the next word in the string. So if you input a string with multiple words, your bot will respond to each of them.
You can use Scanner.nextLine() to get the entire input string, instead of only 1 word.
To count the number of times your bot has responded, you can create a field in the bot class:
private int responseCount = 0;
Then if you change yout getResponse method from a static method to an instance method, you can update this value from this method:
public String getResponse(String value)
{
String X = longestWord(value); //Your longestWord should also not be static.
this.responseCount++;
if (value.contains("you"))
{
...
Regarding counting the responses, just modify your main method:
import java.util.Scanner;
public class Test {
public static void main (String [ ] args)
{
int numberOfResponses = 1;
Scanner input = new Scanner (System.in);
ChatBot e = new ChatBot();
String prompt = "What would you like to talk about?";
System.out.println(prompt);
String userInput;
userInput = input.next();
while (!userInput.equals("Goodbye"))
{
System.out.println(e.getResponse(userInput));
userInput = input.nextLine();
numberOfResponses++;
}
input.close();
System.out.println(numberOfResponses);
}
}
If I have the time I will edit my post in a few minutes to check your problem regarding the double appearences of a response. You also forgot to close the Scanner.
EDIT: It actually happens because scanner has as a default the delimiter set to be on whitespace. so if you input a text with a whitespace, the while loop runs twice for one user input. Just use the nextLine() command.
Why is this code:
Scanner input = new Scanner (System.in);
In your getResponse method? Its not used at all. Take a closer look at your methods as they are holding some strange code.