So I want to know what indexOf() does. As I want to use it in my program it find out how many vowels are in a word that the user inputs.
public static boolean methodCheck(char a){
return "AEIOUaeiou".indexOf(a) != -1;
}
But that doesnt seem to work at all hahah. as I have no idea what indexOf() actually does. anyway here is my program so far(sorry if its bad I'm really new). I left 5 questions too that would help me a lot! please and thank you for your help :D
import java.util.Scanner;
public class vowelCounter {
private static String input = methodInput(); //1. is there any other way to make a global Scanner?
public static void main(String[] args){
System.out.println("Enter word");
System.out.println(input);
System.out.println("This word has" + methodCheck('a')); //2. what should i put in my parameters?
}
public static boolean methodCheck(char a){
return "AEIOUaeiou".indexOf(a) != -1; //3. what does this line do?
}
public static String methodInput(){
Scanner keyboard = new Scanner(System.in);
String input = keyboard.nextLine();
return input;
//4. the output is 'hastrue' why is that?
//5. how can i make this program better?
}
}
If you don't know what a method does, then the solution is to go look at what it does. For example, the java documentation will tell you that
public int indexOf(int ch)
Returns the index within this string of the first occurrence of the specified character
In either case, if no such character occurs in this string, then -1 is returned.
How you're using it is not necessarily wrong, considering how the method returns -1 if the character wasn't found. But if you want to check how many vowels there are in a word that the user enters, it wouldn't be right to check whether the word they entered is in the string of vowels.
All the standard Java libraries, classes and methods have Javadoc that describes what they do.
All you need to do is look up the Javadoc and they describe it.
In this case the Javadoc is at: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#indexOf(int)
Your first step with any question like this should always be the documentation, then if that doesn't work try doing a web search looking for examples. For example 5 seconds on google putting in "java indexOf example" found me:
http://www.tutorialspoint.com/java/java_string_indexof.htm
Then if that doesn't work you can try asking the question here.
When you have the word boolean before the name of a method, that means that the method will return either the value true or the value false. And it's this true or false value that your program is printing out, on the same line as "This word has".
This particular method will return true if the character you pass to it is a vowel, or false otherwise. The method indexOf tells you which character of a String is the first one that is equal to the value that you pass in to the method. It returns 0 for the first character, 1 for the second character and so on. It returns -1 if none of the characters match. In this case, you're just checking whether the value returned by indexOf is or isn't -1 - in other words, whether the character is or isn't in the String "AEIOUaeiou".
indexOf(String str) Returns the index within this string of the first occurrence of the specified substring. If no such value of str exists, then -1 is returned.
For examples :
int num1 = "AEIOUaeiou".indexOf("a"); // it gives 5
int num2 = "AEIOUaeiou".indexOf("A"); // It gives 0
int num3 = "AEIOUaeiou".indexOf("z"); // It gives -1
1 Don't do that! Create a scanner in main, read input with it and then call your method(s).
2 How about countVowels(input)? You'd need to write an static int countVowels(String input) method.
3 Returns true since you pass in 'a'.
4 See number 3.
5 See number 2, and add a static boolean isVowel(char a).
Here is what the indexOf method does
string.indexOf(searchvalue,start)
Parameters
searchvalue : Required. The string to search for
start : Optional. Default 0. At which position to start the search
Return Value
Number : The position where the specified searchvalue occurs for the first time, or -1 if it never occurs
In simple terms, the index of method checks the first occurence of the value passed to it from the start position(if specified) and returns the position at which the value was first encountered in the string.
eg.
String s = "AEIOUaeiou";
s.indexOf("a"); //This would get a value of 5.
s.indexOf("v"); //This would get a value of -1, since it doesn't have the character v
To answer your questions,
You can directly declare the scanner as private and use it in the
entire program
`private static Scanner input = new Scanner(System.in);`
you can write a method that receives the String input by the user
and then checks if the String contains any of the vowels. You can
use indexOf or contains methods to check for the each vowel using
the indexOf method.
Already described above.
A better way to do it would be as follows.
public class vowelCounter{
public static void main (String[] args) {
Scanner keyboard = new Scanner (System.in); // No need to declare it as global. You use it only once.
System.out.println ("Enter word : "); //Prompt the user to enter a word
String input = keyboard.nextLine (); //Fetch the word that the user enters into a String
System.out.println ("This word has" + countVowel (input)); // Pass the string to the method to check if it has vowels.
}
private static int countVowel (String a) {
int count = 0;
String s = a.toLowerCase (); // convert the string to lower case so that you only have to check for the lower case characters
// Here you would need to check the number of times each vowel exists in the String and incremenet the count everytime.
return count;
}
}
Related
My program has a String inputted Eg. hello i am john who are you oh so i see you are also john i am happy
my program then has a keyword inputted Eg. i (the program doesn't like capitals or punctuation yet)
then it reads the initial String and finds all the times it mentions the keyword + the word after the keyword, Eg. i am, i see, i am.
with this is finds the most common occurrence and outputs that second word as the new keyword and repeats. this will produce
i am john/happy (when it comes to an equal occurrence of a second word it stops (it is meant to))
What i want to know is how i find the word after the keyword.
package main;
import java.util.Scanner;
public class DeepWriterMain {
public static void main(String[] args) {
String next;
Scanner scanner = new Scanner(System.in);
System.out.println("text:");
String input = scanner.nextLine();
System.out.println("starting word:");
String start = scanner.nextLine();
input.toLowerCase();
start.toLowerCase();
if (input.contains(start)) {
System.out.println("Loading... (this is where i find the most used word after the 'start' variable)");
next = input.substring(5, 8);
System.out.println(next);
}else {
System.out.println("System has run into a problem");
}
}
}
If you use split to split all your words into an array, you can iterate through the array looking for the keyword, and if it is not the last in the array, you can print the next word
String arr [] = line.split(" ");
for (int i = 0; i < arr.length -1; i++) {
if (arr[i].equalsIgnoreCase(keyword)) {
sop(arr[i] + " " arr[i + 1]);
}
if it is not the last in the array, iterate only to length - 1
The String class includes a method called public int indexOf(String str). You could use this as follows:
int nIndex = input.indexOf(start) + start.length()
You then only need to check if nIndex == -1 in the case that start is not in the input string. Otherwise, it gets you the position of the first character of the word that follows. Using the same indexOf method to find the next space provides the end index.
This would allow you to avoid a linear search through the input, although the indexOf method probably does one anyway.
So I am trying to split my String input by /, -, and space, and within the dateConversion method, I am trying to call upon the third term in my String array called terms. If my array only has 2 elements, I receive an error, and I understand why; the issue is that even if I declare the third element of the array before I split my original input, the program still crashes. It should print out the last if statement instead.
Scanner in=new Scanner(System.in);
System.out.println(message);
String input=in.nextLine();
if(input.equals("quit"))
{
System.out.println("Bye!");
return null;
}
else
return input;
public static void dateConversion(String input){
String[] terms=new String[2];
terms[2].equals(null);
terms=input.split("-|/| ");
if(terms[2].equals(null))
System.out.println("Wrong format. Enter again.\n");
}
The program should either continue if the third term of the array exists (and it does just fine when I test it), but if it intentionally doesn't exist, the last if statement should print instead of the program crashing. Is there some other way I can declare terms[2] so it doesn't crash?
If you declare an array with two spaces like you have done --> String terms = new String[2]. Then there will be tow spaces created: terms[0] and terms[1]. The indexing starts at 0, not 1.
This initial part is just supposed to take a mixed fraction like 1 1/2 and convert it to 3/2
What I have is below, the problem is that when I run it it gives me an error. said error is
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(Unknown Source)
at Calculator.main(Calculator.java:18)
Code begins below:
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
// prompt user for fraction string
// receive and store in variable
// convert to improper fraction
//print
System.out.println("Enter a fraction:"); //prompt for string
Scanner input = new Scanner(System.in); //Receive
String fractionAsString = input.next(); //store in variable
int getSpace = fractionAsString.indexOf('_'); //should fine where java spaces for the initial entering of fractoin
int getSlash = fractionAsString.indexOf('/'); //should find divisor (like in 1 1/2)
String firstString= fractionAsString.substring(0, getSpace+1);//converting string to int
String secondString=fractionAsString.substring(getSpace, getSlash);
String thirdString=fractionAsString.substring(getSlash+1);
int wholeNumber=Integer.parseInt(firstString);
int numerator=Integer.parseInt(secondString);
int denominator=Integer.parseInt(thirdString);
int newResult=wholeNumber*denominator;
int finalResult=numerator+newResult;
System.out.println(finalResult+"/"+denominator);
input.close();
}
}
The problem is input.next(). Since you need the whole string which the user entered you should use nextLine() not next().
Reason:
next() takes space as the default delimiter.
nextLine() takes return as the default delimiter.
Be warned there are other problems in your code. You may want to print variables to know what is stored in them.
Happy Learning!
In your code, next() takes space as the default delimiter, Use nextLine() as it takes return as the default delimiter. By the way use some custom operator like underscore(_) to represent whole-number instead of using space. And split the string to get wholeNumber, numerator and denominator.
I need to check the array to see if the user input is already present, and display a message as to whether it is or isn't there. The first part is working, but I tried to create a method for the word check, and I'm not sure if I'm on the right path or not, cheers.
import java.util.Scanner;
public class InputLoop {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String array[] = new String[10];
int num = array.length, i = 0;
System.out.println("Enter a word");
for (i = 0; i < num; i++) {
while (scan.hasNextInt()) // while non-integers are present...
{
scan.next(); // ...read and discard input, then prompt again
System.out.println("Bad input. Enter a word");
}
array[i] = scan.next();
WordCheck();
}
}
public void WordCheck(String[] i) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter another word");
if (scan.next().equals(array[i])) {
System.out.println("The word has been found");
} else {
System.out.println("The word has not been found");
}
}
}
Right. You've clearly gone down a bad thought process, so let's just clear the slate and have a re-think.
Step one: You want to take some user input
Step two: Compare it with all previous user inputs to see if it's present.
If it is present, return a message indicating that value has been inputted.
otherwise ignore the input and continue execution
Repeat step one.
The solution
So, let's review what you've got, and how you need to change it.
public static void main(String[] args)
If I were you, I would avoid calling methods directly from here. If you do, every method will need to be static, which is a pointless adjustment in scope for the functionality of your class. Create a new instance of your class, inside the main method, and move this code to the class' constructor. This will remove the need to make every single method static.
Scanner scan = new Scanner(System.in);
String array[] = new String[10];
Okay, so you've created a scanner object that takes input from the System.in stream. That's a reasonable thing to do when taking input from the keyboard. You've also created an array to contain each item. If you only want the user to be able to type in 10 values, then this is fine. Personally, I would use an ArrayList, because it means you can take in as many user inputs as the user desires.
Secondly, you want a function to compare the input, with all other inputs. What you have at the moment clearly isn't working, so let's have another go at it.
You will need some input, userInput, and a collection to compare it against, allInputs.
allInputs needs to be accessible from any point in the program, so it's probably wise to make it into a field, rather than a local variable.
Then, because you're comparing userInput against all values, you're going to need a foreach loop:
for(String s : allInputs)
{
if(s.equals(userInput))
{
// Output message code.
}
}
Now the trick is fitting this inside a loop that works with this program. That is up to you.
One simple solution is to use a Set:
Set<String> words = new HashSet<String>();
Add words with the add() method and check if a word is already added with contains(word) method.
EDIT
If you must use Arrays you can keep the array sorted and do a binary search:
Arrays.sort(words);
boolean isAlreadyAdded = Arrays.binarySearch(words, newWord) >= 0;
You're going to have to loop through the entire array and check if scan.next() equals any of them - if so return true - as such:
String toCheck = scan.next();
for (String string : i) { //For each String (string) in i
if (toCheck.equals(i)) {
System.out.println("The word has been found");
return;
}
}
System.out.println("The word has not been found");
This supposes you call WordCheck(), passing the array to it - this method also has to be static for you to call it from the main() method.
You can use the arraylist.contains("name") method to check if there is a duplicate user entry.
I'm creating a method that will take the given input and set the value to "plate". I then proceed to use the charAt method and try to take the characters(letters/String) input and set it to a new value. But i'm told to set it to a char value. When I run aprint statement with it, the output is just a bunch of integers, or in my case (for the code i'm going to show) it outputs "195" when I put the license plate as abc 123. Also, the model doesn't do anything(or atleast isnt supposed to). If anyone could tell me what exactly i'm doing wrong it would be a great help.
Here is my code so far:
import java.util.Scanner;
public class CarRental {
public static String model;
public static String plate;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Car Model:");
model = input.nextLine();
System.out.println("License Plate: ");
plate = input.nextLine();
char one = plate.charAt(0);
char two = plate.charAt(1);
System.out.println(two + one);
}
}
To make my issue clear, what I'm hoping to do is, assign the actual letters I type into the input to a separate value. I'm using the charAt method and it is returning integers.
if anyone could offer a suggestion it would help alot!
Thanks,
Sully
the + operator treats 2 chars as ints, try
System.out.println("" + two + one);
You can just use
Character.toChars(X)
Where x is your number to convert to char and then display said chars once they've been converted.