Using a method to find the letter in the inputted integer - java

"Write and test the method that returns a letter of the alphabet from a given word, it the position is given. (Hint: use the method that begins with static char getLetter (String txt, int n)."
I've been staring at this question for 20 minutes, can't seem to understand what it wants me to do.
This is what I have so far:
// The "Divide_raminAmiri" class.
public class Divide_raminAmiri
{
public static void main (String[] args)
{
String word;
int location;
System.out.println ("Enter a word.");
word = In.getString ();
System.out.println ("Enter the location of the letter.");
location = In.getInt ();
} // main method
public static void test (char c)
{
System.out.println (word.charAt (location));
}
} // Divide_raminAmiri class
I'm confused. I think what it wants me to do is use methods to find the letter at the location provided, but I'm getting errors. Any help appreciated!

Okay so I'm not gonna give the full solution since this seems to be some kind of an exercise.
What might help you:
The way you are doing it, you can't access the variable word in the test-method because it is only visible to the main-method, that's why we use parameters so you can pass variables to other methods.
Speaking of parameters, your method is asked to have two parameters, one being the String and one being an int, your test-method only has a char as parameter (?)
Your program starts and ends in the main-method, since you don't call your test-method there, it never gets executed.
Hints for your actual problem:
You can get a char at position x from a String with the method
char myChar = myString.charAt(x);
A char can be cast to an int with
int asciiValue = (int) myChar;
My last hint: Big letters have an ASCII-Value starting at 65 (='A'), small letters of 97 (='a').
Hope that helped, if you got any more questions feel free to ask.

Related

How can I fix an invalid character constant when comparing characters?

import java.util.*;
public class StudentWelcome
{
public static void main(String[]args)
{
Scanner in = new Scanner(System.in);
System.out.print("Please enter your student login");
char ident = in.next().charAt(0,1);
if (ident == '19')
{
System.out.println("Welcome Freshman")
}
else if (ident == '18')
{
System.out.println("Welcome Sophomore")
}
else if (ident.equals(17))
{
System.out.println("Welcome Sophomore")
}
else if (ident.equals)
}
}
I am basically trying to determine what year someone is by input"19johndo" or "17daquanra" and print the correct welcome statement. eclipse shows an error on line 13 that says invalid character constant. What should I do?
#VGR is right in the comment above, this is basic "introduction to Java" stuff. But since StackOverflow is a Q&A resource, and this is a Q, I'll provide an A.
There is no charAt(int, int) method on a String, so that line won't even compile. If you're really interested in the first 2 characters of the input String, then use substring(0, 2). That will return a String, not a char so you'll need to change the type of your ident variable. You'll also have to update how you compare ident in the if statements, since you're trying to compare against a (invalid) char literal. But chars can't be more than one character, so you need to compare against String literals, for example:
if (ident.equals("19")) {
That will get your code to compile and maybe even work correctly, but it's still not the best way to do what it seems like you're trying to do. But trying to discuss better implementations is beyond the scope of this question.

How to use indexOf? Please help a beginner out

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;
}
}

charAt method is returning an integer. Need to convert to int

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.

Simple Recursion Issue Back ways

public class recursionExcercise4
{
public static void main (String[] args)
{
boolean statement=false;
String ch="";
String a="I am bubbles who is a little slugger and loves apple and yellow."
BacktoBacks(a,ch,statement);
}
public static void BacktoBacks(String sentence, String ch, boolean statement)
{
String newLine="",word="";
System.out.print(sentence.charAt(0));
if(sentence.charAt(0)=='.') System.out.println();
if(sentence.length()>1)
{
int num=sentence.substring(1).indexOf(" ");
word = sentence.substring(0,num);
System.out.println(word);
}
BacktoBacks(newLine,ch,statement);
}
}
That is the code.
The lines inside the if statement loop were added by me so you can change that but nothing else can be changed. The if statement on top must remain there. Also, I am trying to avoid loops as it makes it too easy then. Any way to do this? I tried it but need help.
The objective is to print out the words from the string that have double letters. This should also be printed backwards. So like this:
Yellow
Apple
Slugger
Little
Bubbles
Your help is much appreciated.
Thanks!!
So you need a function to check whether a word contains double letters,
public boolean hasDoubleLetters(String word){
// test
}
and based on its outcome, print the word after the recursive call. And you have to pass the correct argument to the recursive call.

readCharArray() Method is not working

I have a problem with a method which i want to use to read a complete line of characters.
First of all i'm using the following package for my method:
package chararray;
import java.util.*;
import java.util.regex.*;
import java.text.*;
public class Console
{
private static Scanner sc;
private Console()
{
}
public static char[] readCharArray()
throws NoSuchElementException, IllegalStateException
{
sc = new Scanner(System.in);
String text = sc.nextLine();
return text.toCharArray();
}
}
And that's the main code where i include the package. My compiler (BlueJ) is telling me: "incompatible types - found char[] but expected char". But normally my method should work for char[]? Any suggestions what i'm doing wrong here?
import chararray.Console;
public class kundenverwaltung
{
public static void main (String args[])
{
int nk;
System.out.print("Wie viele Kunden möchten Sie erfassen?: ");
nk = Console.readInt();
char [][] kundenregister;
kundenregister = new char [nk][4];
for (int i = 0; i < nk; ++i)
{
System.out.print("Kundennummer: ");
kundenregister [i][0] = Console.readCharArray();
System.out.print("Name des Kunden: ");
kundenregister [i][1] = Console.readCharArray();
System.out.print("Vorname des Kunden: ");
kundenregister [i][2] = Console.readCharArray();
System.out.print("Adresse des Kunden: ");
kundenregister [i][3] = Console.readCharArray();
}
}
}
Look at this line:
kundenregister[i][0] = Console.readCharArray();
The expression kundenregister[i][0] refers to a char variable - not a char array.
It's not clear what you're trying to do - and in particular why you need the values as char arrays rather than as strings - but this would make it work:
char[][][] kundenregister = new char[nk][4][];
Having a 3-dimensional array is almost always a mistake. I would strongly suggest that you refactor the code to:
Use strings instead of char arrays
Encapsulate the 4 values into a type with properties for the number, name, first name and address
Create a List<Customer> or whatever... perhaps using ArrayList<T> as the implementation. Then you don't even need to know the number of customers beforehand... the user could just hit return (or whatever) to indicate that they'd finished.
Your variable kundenregister is declared as an array of arrays of chars. That means that for each x and y, kundenregister[x][y] is a single char (the yth character of the xth array of characters). Yet you are trying to assign it an entire array of characters.
I'm not sure what your goal is here so I can't suggest an easy fix. You either want to assign the result to some index of kundenregister or declare kundenregister as a 3-dimensional array.
I'm not exactly sure what you're trying to do here so I can't offer a full solution, but the immediate problem causing the error is in your kundenverwaltung class, in the for loop.
You're trying to assign Console.readCharArray() to kundenregister[i][0], which is where the type mismatch occurs since Console.readCharArray() returns a char[], and kundenregister[i][0] is of type char.
To help you understand this: kundenregister is essentially a 2d grid, where each slot is a single char. kundenregister[i][0] refers to one of those slots, so when you write kundenregister[i][2] = x, x has to be a char otherwise it won't work.

Categories