I tried to use the contains method to search for a word in a sentence but it only works for the first word in the sentence.
For example when searching for 'Shakira' in "liked Shakira's photo" my program cannot find it. On the other hand, searching for 'liked' in the same sentence works.
This is the code I'm using:
package fules;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class fule {
public static int i,x,n,k,ba,sh,fe;
public static void main(String[] args) throws FileNotFoundException {
File s=new File("C:/Users/taha/Desktop/tt.in");
Scanner m=new Scanner(s);
fule obj=new fule();
i=m.nextInt();//test case
n=m.nextInt();
k=m.nextInt();
for (int l=0;l<6;l++){
boolean q=contains((m.next()),("taha"));
if(q) {
ba++;
}
boolean w=contains((m.next()),("Shakira"));
if(w)
sh++;
}
boolean e=contains((m.next()),("Fegla"));
if(e) {
fe++;
}
System.out.println("ba="+ba+" sh="+sh+" fe="+fe);
m.close();
}
static boolean contains (String s1,String s2)
{
return s1.contains(s2);
}
}
and this is
the inputs in( tt.in)
1
6 2
liked Badr's photo
liked Shakira's photo
liked Badr's photo
liked Fegla's photo
liked Shakira's photo
commented on Shakira's photo
Can somebody please help me?
You are getting the input with the next() method which Finds and returns the next complete token from this scanner. Therefore you only read the first word of the sentence.
Try to replace next() with nextLine().
And if you want to compare the same String against multiple patterns, store that String in a variable. Currently each of your calls to contains() reads a new String from the scanner.
You should write something like this :
String input = m.nextLine();
boolean q=contains(input,"Badr");
if(q)
{
ba++;
}
boolean w=contains(input,"Shakira");
if(w)
sh++;
}
boolean e=contains(input,"Fegla");
if(e)
{
fe++;
}
This would find "Shakira" in "liked Shakira's photo".
Of course, there are more efficient ways to write the same code.
String input = m.nextLine();
if (input.contains("Badr"))
ba++;
if (input.contains("Shakira"))
sh++;
if (input.contains("Fegla"))
fe++;
Related
I have a class Container where a user should be able to input any number of words until he types nothing. I have addWord(Word) method where each input is added to an ArrayList words every time do/while loop is run. I am passing user input value as a parameter to addWord() method each time loop runs.
Now I want to to display all elements of an array using display() method once the do/While loop has stopped running. But for some reason when i try to call method display(), it just shows an empty array [].
Is there any way you can help?
import java.util.ArrayList;
import java.util.List;
public class Container {
private List<String> words;
public Container() {
}
public List<String> getWords() {
return words;
}
public void setWords(List<String> words) {
this.words = words;
}
public void addWord(String word) {
words = new ArrayList<String>();
words.add(word);
}
public void display() {
System.out.println(words);
}
}
Main method:
import java.util.Scanner;
public class ContainerMain
{
public static void main(String[] args)
{
Container one = new Container();
Scanner myScan = new Scanner(System.in);
String word = "s";
do
{
word = myScan.nextLine();
one.addWord(word);
}
while (!word.equals(""));
if (word.equals("")) {
one.display();
}
else {
System.out.println("No hope fam");
}
}
}
Look at your addWord method:
public void addWord(String word) {
words = new ArrayList<String>();
words.add(word);
}
Each time you call that, it's going to create a new list - so you can never end up with more than one word in it.
The first line, initializing words, should be in your constructor (or as a field initializer). Then remove the line from addWord - ideally making the words field final at the same time, to avoid mistakes like this in the future, and remove the setWords method unless you really need it for something else.
That's all that wrong in Container (although it's not clear that it's really providing any value beyond just using a List<String> directly). As noted in comments, currently your do/while loop in main will add an empty string at the end. Also, there's no point in checking whether word is empty or not after the loop - it has to be, otherwise you wouldn't have exited the loop!
I've been teaching myself Java with http://www.cs.princeton.edu/courses/archive/spr15/cos126/lectures.html as a reference. They have a library called algs4 and it has several classes including StdIn, which I'm trying to implement below.
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;
public class Tired
{
public static void main(String[] args)
{
//I thought this while statement will ask for an input
//and if an input is provided, it would spell out each character
while (!StdIn.hasNextChar()) {
StdOut.print(1); //seeing if it gets past the while conditional
char c = StdIn.readChar();
StdOut.print(c);
}
}
}
//This is from StdIn class. It has a method called hasNextChar() as shown below.
/*
public static boolean hasNextChar() {
scanner.useDelimiter(EMPTY_PATTERN);
boolean result = scanner.hasNext();
scanner.useDelimiter(WHITESPACE_PATTERN);
return result;
}
*/
If i run the code, it does ask for an input, but regardless of what i type in, nothing happens and nothing gets printed out.
I see that even StdOut.print(1); doesnt get printed out, so for some reason, it just gets stuck on while
It looks like the issue is with the condition for your while loop:
!StdIn.hasNextChar()
This says to continue as long as there isn't a next char. But you want to continue while there is one, so get rid of that ! and you should be good.
Here is some alternative code that works similarly. Not the best coding but works.
import java.util.Scanner;
public class test{
static Scanner StdIn = new Scanner(System.in);
static String input;
public static void main(String[] args){
while(true){
if(input.charAt(0) == '!'){ // use ! to break the loop
break;
}else{
input = StdIn.next(); // store your input
System.out.println(input); // look at your input
}
}
}
}
I've been doing a ton of research on this for the past few hours, with no luck. I am pretty sure this is a problem with .next() or .nextLine() (according to my searches). However, nothing has helped me solve my problem.
When I run the code below, I have to type in input twice, and only one of the inputs is subsequently added to the arrayList (which can be seen when you print the contents of the arrayList).
import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;
public class Tester{
public static void main(String[] args) {
AddStrings();
}
public static void AddStrings() {
Scanner console = new Scanner(System.in);
ArrayList<String> strings = new ArrayList<String>(); //this arraylist will hold the inputs the user types in in the while loop below
while(true) {
System.out.println("Input file name (no spaces) (type done to finish): ");
if(console.next().equals("done")) break;
//console.nextLine(); /*according to my observations, with every use of .next() or .nextLine(), I am required to type in the same input one more time
//* however, all my google/stackoverflow/ reddit searches said to include
//* a .nextLine() */
//String inputs = console.next(); //.next makes me type input twice, .nextLine only makes me do it once, but doesn't add anything to arrayList
strings.add(console.next());
}
System.out.println(strings); //for testing purposes
console.close();
}
}
Problem with your code is that you are doing console.next() two times.
1st Inside if condition and
2nd while adding to ArrayList.
Correct Code :
public class TestClass{
public static void main(String[] args) {
AddStrings();
}
public static void AddStrings() {
Scanner console = new Scanner(System.in);
ArrayList<String> strings = new ArrayList<String>(); //this arraylist will hold the inputs the user types in in the while loop below
while(true) {
System.out.println("Input file name (no spaces) (type done to finish): ");
String input = console.next();
if(input.equals("done")) break;
strings.add(input);
System.out.println(strings);
}
System.out.println(strings); //for testing purposes
console.close();
}
}
In your code, you are asking for two words to be inserted. Just remove one of them.
Use it this way:
String choice = console.next();
if (choince.equals('done')) break;
strings.add(choice);
I have a problem creating a student class which contains a constructor which takes a Scanner string of a format "Brookes 00918 X12 X14 X16 X21". The conditions should be that there should be a student name and student number and the course codes should start with an "X". I have thrown IncorrectFormatExceptions in the case that they are not satisfied. However when I create a test class and enter a string and press enter , for example "abc 123" it doesn't produce an output which is usually the case.
Update: I've changed the code to use a String array tokens however now with the toString() method using "123 abc X12" it gives a Null Pointer Exception. It works when I put "123 abc" in the constructor
Update:Seems to work now forgot to initialize the arrayList
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Student extends UniversityPerson{
private String studentNumber="";
private List<String> courses=new ArrayList<String>();
private String studentName="";
public int checkNoofletters(char[] chararray){
int noofletters=0;
for (char c:chararray){
if (Character.isLetter(c)){
noofletters++;
}
}
return noofletters;
}
public String courseListinStr(){
String stringo="";
for (String c:courses){
stringo+=c;
stringo+=" ";
}
return stringo;
}
public Student(Scanner scanner) throws IncorrectFormatException{
int studentNumberCount=0;
int studentNameCount=0;
Scanner s=scanner;
String input=s.nextLine();
String[] tokens=input.split("\\s");
for (int i=0; i<tokens.length; i++){
char[] chars=tokens[i].toCharArray();
if (checkNoofletters(chars)==chars.length){//if the number of letters is equal to the character length
if (studentNameCount==1){throw new IncorrectFormatException("Can only have 1 student name");}
studentNameCount++;
this.studentName=tokens[i];
continue;
}
if (tokens[i].matches("[0-9]+")){//add to the studentNumbers list
if (studentNumberCount==1){throw new IncorrectFormatException("Can only have 1 student number");}
studentNumberCount++;
this.studentNumber=tokens[i];
continue;
}
if (!tokens[i].startsWith("X")){
throw new IncorrectFormatException("Course code must start with an 'X'");
}
System.out.println(tokens[i]);
courses.add(tokens[i]);
}
if (studentNumber=="" || studentName==""){
throw new IncorrectFormatException("Must have 1 student Number and Student Name");
}
}
#Override
public String toString() {
//return String.format("%s %s", studentName,courseListinStr());
return String.format("Student: %s %s", studentName,studentNumber);
}
#Override
public boolean equals(Object o) {
// TODO Auto-generated method stub
return false;
}
}
The best way would be to do something like this:
Scanner s=scanner;
String input = s.nextLine();
String[] tokens=input.split("\\s");
Now you can test all your conditions:
if (tokens.size() < yourNumber) throw new Exception("add here");
if (tokens[2].charAt(0)!='X') throw new Exception("add here");
and so on; it should be rather easy to create your Student Object based on your requirements.
Your program is full of errors and I'll list some of them after answering why it doesn't print anything: if you dump all threads you'll see that the main thread is stuck at next(), which blocks until next token is available, and effectively never leaves the constructor of the first student
if (s.hasNextInt()){
studentNumbers.add(s.nextInt());
s.next();
continue; // <--------- this line
}
I think this is not the only error in your program, so maybe you'd better throw the entire parsing away and restart from scratch.
You should create exactly one Scanner object for each input stream, not one for parsed object
You should not pass the scanner to the Student constructor
You should not put any algorithm in a constructor: make a separate object instead
To simplify your program introduce a Parser class
public class Parser {
public Parser(Reader in) {}
public boolean hasNext() {}
public Student next() {}
}
and inside next() make the parser deal with entire lines (Scanner.hasNextLine and Scanner.nextLine()) instead of individual tokens, otherwise you'll have to define a custom protocol to mean EOR (end of record)
Dealing with lines is easier to think about, program and test. Once you have the full record, you can further tokenize it with a simple String.split(), or directly use regular expressions.
I didn't go through, your whole code. But, I would suggest you to use StringTokenizer or split function and store it in temp array. Then, traverse through your temp array and validate the data.
In Java, where should I aim (I enjoy figuring it out myself) to get, with sample data:
I am Sam I am a
the output:
I am Sam I am - letter to remove a
I m Sm I m
Basically, it is to "Remove all instances of the specified removal letter from the original sentence"
As this is for a class, I am limited with what I can do. For this assignment I am stuck with the given classes/constructors and am not allowed to make any more unless it is noted, which in my case, is to create another constructor class; Anyway, that has been the real challenge as it is hard to get help (No matter how many times I've googled!) with it being so specific and I new to the language.
Here is what I was given:
import static java.lang.System.*;
public class LetterRemover
{
private String sentence;
private char lookFor;
public LetterRemover()
{
//call set
}
//add in second constructor
public void setRemover(String s, char rem)
{
sentence = s;
lookFor = rem;
}
public String removeLetters()
{
String cleaned=sentence;
return cleaned;
}
public String toString()
{
return sentence + " - letter to remove " + lookFor;
}
}
This is what I've done so far:
import java.util.Scanner;
import static java.lang.System.*;
public class LetterRemover
{
private String sentence;
private String lookFor;
public LetterRemover()
{
//I am not sure what this means
}
//add in second constructor
public void setRemover(String s, String rem)
{
sentence = s;
lookFor = rem;
}
public String removeLetters()
{
sentence = sentence.replaceAll(lookFor,"");
String cleaned=sentence;
return cleaned;
}
public String toString()
{
return sentence + " - letter to remove " + lookFor;
}
}
I tried changing the char to a string for the "lookfor" to use the replace all method which seemed after a lot of research and the best way to get the letters out.
Is there any noticeable mistakes and where should I look to fix them? I do not really want the right code, or for anyone to "do" the work for me. I really want to try and figure it out. But I need a little help in pointing in the right direction to get my desired output :)
Let me know if there is any other details or whatnot, this is also , this is also my first time using the site. There were many similar questions to this, but as I really am a beginner I struggled to understand people's explanations
--Edit--
Moving to my runner class, this is what I wrote, trying to get for the desired output. I am not really sure how to deal with output as I really have just started learning to write them myself.
I keep getting a void error though:
import static java.lang.System.*;
public class LetterRemoverRunner
{
public static void main( String args[] )
{
LetterRemover test = new LetterRemover
(test.setRemover("I really want dumplings","l"));
}
}
Try the below code and confirm this is what your requirement is.
LetterRemoverRunner.java
public class LetterRemoverRunner {
public static void main(String args[])
{
LetterRemover test = new LetterRemover ();
test.setRemover("I really want dumplings","l");
System.out.println(test.toString());
System.out.println("Removed :"+test.removeLetters());
}
}
LetterRemover.java
public class LetterRemover
{
private String sentence;
private String lookFor;
public LetterRemover()
{
//I am not sure what this means
}
public void setRemover(String s, String rem)
{
this.sentence = s;
this.lookFor = rem;
}
public String removeLetters()
{
sentence = sentence.replaceAll(lookFor,"");
String cleaned=sentence;
return cleaned;
}
public String toString()
{
return sentence + " - letter to remove " + lookFor;
}
}
I'm pleased you suggested you don't want the answer - much better way to learn!
I'm not sure you've understood constructors yet. You're line:
LetterRemover test = new LetterRemover
(test.setRemover("I really want dumplings","l"));
Is going to give you a null pointer error because it's calling setRemover on test before test has been constructed. You should be constructing the object with its sentence and lookFor values before calling setRemover.
Here are some things you might want to look at:
The String.indexOf method will look for a certain character or string and tell you where to find it (or if it isn't in the string at all).
The String.substring method allows you to take part of a string using string positions
You can build a new string by concatenating substrings together
Using a while loop you can continue using indexOf until the target cannot be found.
As you've pointed out, you can also use one of the replace methods to replace the target with "".