I'm trying to create a program that prompts user to input a word and it would return the length of the words. However I'm having issues with "String word;", as I keep getting the error that local variable may not have been initialized.
import javax.swing.JOptionPane;
public class FunctionsTest {
public static void main(String[] args) {
String word;
JOptionPane.showMessageDialog(null, "The length of the word is" + findLength (word));
}//End of Main Method
public static int findLength(String word) {
String str = new String(word);
return str.length();
}//End of findLength Method
}
the "word" has no value,it's null, you need give "word" some value:
String word = "abc";
There is no user input being prompted, therefore the String word will never have a value. Create a user input prompt, and have the string equal to the value of the input.
Related
I'm trying to create a program in BlueJ that allows the reader to type any word, then print out: that word, the length of the word, and whether or not the word contains "ing". I've figured out how to print the word and its length, but I can't figure out how to include whether "ing" is in the word.
Here is my code:
import java.util.*;
public class One
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String str = "";
System.out.println("Type in a word");
str = sc.nextLine();
//System.out.println(str);
System.out.println(str.length());
}
}
How can I tell whether "ing" is included in the word?
You can do that using the contains() method on your resulting string:
if (str.contains("ing")) System.out.println("Contains ING");
If you need to match either lowercase or uppercase, you can just convert str to upper case and check that instead:
if (str.toUpperCase().contains("ING")
When I run this program, it does not return anything yet no errors occur. I'm trying to create a method that will return the number of words I previously entered into the array once I enter "".
import java.util.ArrayList;
import java.util.Scanner;
public class ArrayCounter {
public static int CountItems(ArrayList<String> list ) {
int i = list.size();
return i;
}
public static void main (String args[]) {
ArrayList<String> Names = new ArrayList<String>();
Scanner input = new Scanner(System.in);
while(true) {
System.out.println("Hey gimme a word");
String word = input.nextLine();
if (word.equals("")) {
System.out.println("The number of values entered were:");
break;
} else {
Names.add(word);
}
}
CountItems(Names);
input.close();
}
}
You're ignoring the result returned from CountItems.
The println should be:
System.out.println("The number of values entered were: " + CountItems(Names));
As an aside, methods names in Java should start with a lowercase, so CountItems should instead be countItems.
Your CountItems method returns the item count, but you are ignoring the result. You need some kind of System.out.println(CountItems(Names)) to print the result to the console.
Also, please consider renaming CountItems to countItems and Names to names to follow the naming conventions for Java.
package chapter6;
import java.util.Scanner;
public class formal_greeting {
public static void main(String[] args) {
String title;
String name;
String mr = null;
String miss = null;
String ms = null;
String mrs = null;
Scanner input = new Scanner(System.in);
System.out.print("Enter your name: ");
name = input.next();
System.out.print("Enter your title: ");
title = input.next();
if (title.equalsIgnoreCase(mr)) {
System.out.println("Hello sir");
}else if (title.equalsIgnoreCase(miss)) {
System.out.println("Hello ma'am");
}else if (title.equalsIgnoreCase(ms)) {
System.out.println("Hello ma'am");
}else if (title.equalsIgnoreCase(mrs)) {
System.out.println("Hello ma'am");
}else {
System.out.println("Hello " + name);
}
}
}
I can't figure out why my if statements won't work. so far it only displays (Hello "name") can someone please tell me what is wrong with my if statement???
Problem is not in the if statements.Change your method input.next() to input.nextLine() .Because using next() you will get only what you entered before the space. But if you use nextLine() the Scanner will read the entire input line.For more reference click here.
Hope this helps
You need to know the difference between a String variable and a string literal.
In your code, mr is a string variable. The value that it stores is null as you can see from this line:
String mr = null;
In the if statement, you test whether the user input is equal to the value string variable. Let's say you entered "Mr" in the console:
User input Value of the mr variable
"Mr" null
Are they the same? No.
The same goes for all the if statements. Finally the execution comes to the else and executes the stuff there since every if statement failed.
What you need to do is to use a string literal instead of a string variable.
A string literal is denoted by double quotes:
"This is a string literal"
So your if statements would look like:
if (title.equalsIgnoreCase("mr")) {
/* ⬆︎ ⬆︎
Quotes here!
*/
Alternatively, you can use variables as well. But you should not give them a value of null. Instead, give them a string literal:
String mr = "mr";
// etc.
This way, you don't need to change your if statement.
Write a method called hasComma that takes a name as an argument and that returns a boolean indicating whether it contains a comma. If it does, you can assume that it is in last name first format. You can use the indexOf String method to help you.
Write a method called convertName that takes a name as an argument. It should check whether it contains a comma by calling your hasComma method. If it does, it should just return the string. If not, then it should assume that the name is in first name first format, and it should return a new string that contains the name converted to last name comma first format. Uses charAt, length, substring, and indexOf methods.
In your main program, loop, asking the user for a name string. If the string is not blank, call convertName and print the results. The loop terminates when the string is blank.
However, my program doesn't return the converted name. If I type in a name like John Smith, the program just ends, rather than returning Smith, John.
public static void main(String[] args) {
String name;
Scanner reader = new Scanner (System.in);
System.out.println("Type a name, then press ENTER.");
name = reader.nextLine();
if (name == null) {
return;
} else {
convertName(name);
}
}
public static boolean hasComma(String name) {
return name.indexOf(',') >= 0;
}
public static String convertName(String name) {
if (hasComma(name)) {
return name;
} else {
int index = name.indexOf(' ');
String first = name.substring(0, index);
String last = name.substring(index + 1);
String convertedName = last + ", " + first;
return convertedName;
}
}
You are not printing the output of your method.
Instead of
convertName(name);
write
System.out.println(convertName(name));
This is a problem I've encountered several times, and always wondered why.
For my code below as an example, if a string of whitespace is entered, the method will not print. However, after the next input with a value string containing characters, it will print all the whitespace strings and the valid character containing string. Why is this delayed and stored in memory?
Example for the code below:
Enter " " returns nothing.
Enter " " returns nothing.
Enter "SwiggitySwooty" returns " " \n " " \n "SwiggitySwooty"
Explaination: The whitespace containing strings are delayed until a valid character string is entered.
Extra info: I use intellij, also happens when not sending the string to a method. I've also had this happen during a while(input.hasNext()) statement, in which I try to catch an invalid input as a string, when I want to take an integer. If I enter 'n' amount of legitimate integers, and then a string, it would print out my "please enter an integer" that 'n' amount of times like in this code.
Lastly, if anyone thinks of a better title for this, let me know so I can change it for more exposure for those with similar questions. Thank you.
Let me know if you guys need anything else!
/**
* Created by JacobHein on 4/19/15.
*/
import java.util.Scanner;
public class FizzString {
/*TODO
* Given a string str, if the string starts with "f" return "Fizz".
If the string ends
* with "b" return "Buzz". If both the "f" and "b" conditions are true, return
* "FizzBuzz". In all other cases, return the string unchanged. */
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
while(input.hasNext()) {
System.out.println(fizzString(input.nextLine()));
}
}
public static String fizzString(String str) {
String result=str;
int l=str.length();
if (str.charAt(0)=='f'||str.charAt(l-1)=='b') {
result="";
if (l>0) {
if (str.charAt(0)=='f') {
result="Fizz";
}
if (str.charAt(0)=='b') {
result="Buzz";
}
if (l>1) {
/*technique: continue the process if l>1 (within l>0 if statement),
prevents breaking the program.*/
if (str.charAt(l-1)=='b') {
result="Buzz";
}
if (str.charAt(0)=='f'&&str.charAt(l-1)=='b') {
result="FizzBuzz";
}
}/*end l>1*/
}/*end l>0*/
}/*end charAt if*/
return result;
}
}
I believe this is what you're looking for:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String inputLine = "";
do {
inputLine = input.nextLine();
System.out.println(fizzString(inputLine));
System.out.println("");
} while (inputLine.length() > 0);
System.out.println("Goodbye");
}
public static String fizzString(String str) {
// Given a string
// If both the "f" and "b" conditions are true, return FizzBuzz
if (str.startsWith("f") && str.endsWith("b")) {
return "FizzBuzz";
}
// If the string starts with "f" return "Fizz".
if (str.startsWith("f")) {
return "Fizz";
}
// If the string ends with "b" return "Buzz".
if (str.endsWith("b")) {
return "Buzz";
}
// In all other cases, return the string unchanged.
return str;
}
Results:
The problem is the behavior of the Scanner class:
The next and hasNext methods and their primitive-type companion methods
(such as nextInt and hasNextInt) first skip any input that matches the
delimiter pattern, and then attempt to return the next token. Both
hasNext and next methods may block waiting for further input. Whether a
hasNext method blocks has no connection to whether or not its
associated next method will block.
Internally, the Scanner class is performing the following operation:
while (!sourceClosed) {
if (hasTokenInBuffer())
return revertState(true);
readInput();
}
The method hasTokenInBuffer() skips all the delimiter tokens (by default is \p{javaWhitespace}+), so only when the class found a non-delimiter token, it returns true in the hasNext() method.
For example, if you type this content: "\n\n\n5\n" and then execute nextInt() method, you'll obtain a result of 5, because Scanner automatically skips all the return line characters.
If you want to find some string into a line, try with the method java.util.Scanner.findInLine instead of nextLine().
Use the patterns: ^f(.)* to look for every line that starts with a f character and the pattern (.)*b$ to look for every line that ends with a b character.