I'm a newbie writing Java code. I haven't read about loops yet. I'm just up to if-else statements. My code works except when I enter a sentence only the first word is recognized. If I enter a sentence with no spaces it works perfectly. How can I get the code to see the whole sentence? Thanks!
import java.util.Scanner;
public class Program04
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Write a complete sentence with proper grammer:");
String sentence = keyboard.next();
boolean qMark = sentence.contains("?");
boolean wow = sentence.contains("!");
if (qMark)
System.out.println("Yes");
else if (wow)
System.out.println("Wow");
else
System.out.println("You always say that.");
}
}
Use
keyboard.nextLine();
instead of
keyboard.next();
have a look at the API, particularly the part about nextLine().
Scanner.next() only returns the next token, which, by default, is just one word (whitespace-delimited). If you want the whole sentence you can change the delimiter to '\n': keyboard.setDelimiter("\n");, or you can learn loops and then loop over the whole sentence.
Edit:
Or, as others have pointed out, nextLine(). That's more portable because macs use '\r', which won´ t be caught with what I said.
import java.util.Scanner;
public class Program04{
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
System.out.println("Write a complete sentence with proper grammer:");
String sentence = keyboard.nextline();
*//this graps full text but next ignores the other words after a space is given*
boolean qMark = sentence.contains("?");
boolean wow = sentence.contains("!");
if (qMark)
System.out.println("Yes");
else if (wow)
System.out.println("Wow");
else
System.out.println("You always say that.");
}
}
Related
I'm pretty new to Java coming from Python so please pardon my retardedness. I'm trying to make a simple if statement and it won't work :(. It ignores the if statement and goes straight else.
I've tried to use .contains and .equalsIgnoreCase in the if statement.
package me.johnminton;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
String species_animal;
System.out.println("Please enter your species: ");
species_animal = user_input.next();
if (species_animal.contains("Erectus")) {
System.out.println("random input statement");
}
else
{
System.out.println("okay");
}
}
}
I'm hoping for it output "random input statement" if I input Erectus in the first input. But instead, it goes straight to the else and outputs "okay".
The next() method just fetches a single word from the scanner, although you can change that behaviour by specifying a delimiter for the scanner.
In your case, if you type Eructussian or something similar, you'll get the result you want, but if you type Home Erectus, you won't.
I suspect you meant to use nextLine() instead of next(), which fetches an entire line of text.
The problem is that your scanner isn’t finishing without getting a return key. Try ‘user_input.nextLine()’ instead of ‘user_input.next()’
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.
This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 7 years ago.
So I just started taking my first classing in programming with Java, so don't hurt me for being a new guy. I understand this may be a simple thing to do, but I'm stuck on where to even begin. I want to make a program that simply counts the number of characters in a string using the Scanner utility. So far I have...
import java.util.scanner
class Counter
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Type a sentence, and I will tell you how many
characters are in it.");
String sentence = input.nextString();
And this is as far as I have gotten. What I want to do is the previous plus...
Char character;
and do something with that, maybe a for-loop, but I'm simply stumped.
And even if I did want to do this I wouldn't know how to go about it. Any ideas?
Thanks!
~Andrew
EDIT:
import java.util.Scanner;
class Counter
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Type a sentence, and I will tell you how many
characters are in it.");
String sentence = input.nextLine();
sentence = sentence.trim();
System.out.print("This sentence has " + sentence.length() + "
characters in it.");
}
}
Did not seem to work.
You have to use input.nextLine() instead of input.nextString() to capture the sentence given by the user.
You also have to use the trim() method on that sentence to delete the spaces given by the user in the front and back side of the sentence.
Ex: sentence.trim()
You can get the length of the sentence by the length() method.
Ex: sentence.length()
Now, I am giving you the full code to count letters of a given sentence:
import java.util.Scanner;
public class LetterCount
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Type a sentence, and I will tell you how many characters are in it.");
String sentence = input.nextLine();
System.out.print("This sentence has " + sentence.trim().length() + " characters in it.");
}
}
First of all, to read by Scanner you have to use input.nextLine(); instead of input.nextString();.
After, you can use .length() function to know how much positions have your String (how much chars have your String) so you won't have to convert it to any char or whatever.
System.out.println(sentence.length());
I expect it will be helpful for you!
"if" statement only allows to put numbers in it.
Is there a way to make it read letters?
I'm only in my fifth lesson of Java (I study in a uni and the teacher is very slow but I want to learn things fast)
for example.
import java.util.Scanner;
public class Java {
public static void main (String [] args) {
Scanner scan = new Scanner(System.in);
int answer1;
System.out.println("Do you like Java?");
answer1 = scan.nextInt();
if (answer1 == yes)
System.out.println("Cool ~");
else
System.out.println("Ehh...");
}
}
I want to put "yes" instead of the number 5.
So if the user types "yes" it will print "correct".
P.S. I didn't find a clear answer to that in the search engine.
It's not a duplicated thread as I'm trying to find a clear answer to that.
I need a detailed explanation about it.
I'm still a beginner, using those "high tech java words" won't help me.
You need to modify your program so that your scanner to reads a String instead of an int. You can do that as:
import java.util.Scanner;
public class Java {
public static void main (String [] args) {
Scanner scan = new Scanner(System.in);
String answer1;
System.out.println("Do you like Java?");
answer1 = scan.next();
if (answer1.equals("yes"))
System.out.println("Cool ~");
else
System.out.println("Ehh...");
}
}
I used next() for this since we only want one word (token), but be aware that there are other options for reading Strings.
Notice also that I've changed the test in the condition because it's now a String. See this answer for more on comparing Strings.
You need to modify your program so that your scanner to reads a String instead of an int. You can do that as:
import java.util.Scanner; public class Java {
public static void main (String [] args) {
Scanner scan = new Scanner(System.in);
String answer1;
System.out.println("Do you like Java?");
answer1 = scan.next();
if (answer1.equals("yes"))
System.out.println("Cool ~");
else
System.out.println("Ehh...");
} }
I used next() for this since we only want one word (token), but be aware that there are other options for reading Strings.
Notice also that I've changed the test in the condition because it's
now a String. See this answer for more on comparing Strings.
Ok, what if you want the program to read both words and numbers:
Here's my program (more in depth, when you see the full thing), but this is one of 5 parts (that look a like) where I'm having the program...
public static void Gdr1() {
try {
System.out.print("[Code: Gdr1] Grade 1: %");
Scanner gdr1 = new Scanner(System.in);
Z = gdr1.next();
Z = Double.toString(Grd1);
Grd1 = Double.parseDouble(Z);
if ((Grd1<100)&&(Grd1>=5)) {
Gdr2();
} else if ((Grd1>=100)&&(Grd1<125)) {
System.out.println(" System> Great Job "+Stu+"!");
Gdr2();
} else if (Grd1<5) {
System.out.println("I'm sorry, the lowest grade I am allowed to compute is 5...");
Gdr1();
} else if (Z.equalsIgnoreCase("restart")) {
restart01();
} else {
System.out.println("("+Z+") cannot be resolved in my system...");
Gdr1();
}
} catch (Exception e) {}
}
Now everything works in the program, besides for when the End-User's input = "restart", I know some of the code in the program seems complicated, but it does work (most of it), can anyone help me try to figure this out, its for my portfolio at my school due latest by 1/25/2017 # 11:59 pm.
The things like Z (constant String), ""+Stu+"" (variable input), and [Code: Gdr1] are there for a purpose...
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.