why am I getting run time error:StringIndexOutOfBounds? - java

Doing my AP Computer Science homework right now but I am stuck with run-time errors. Does anyone know what is wrong with my code?
The program was working fine on Dr.Java but it shows run-time error on my website tester in edhesive...
class Main{
public static void main (String str[]) throws IOException {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a tweet:");
String tweet = scan.nextLine();
int hash = 0;
int attr = 0;
int link = 0;
int ch = 0;
if(tweet.length()>140)
{
System.out.println("Excess Characters: " + (tweet.length() - 140 ));
}
else
{
tweet=tweet.toLowerCase();
System.out.println("Length Correct");
for(ch=0; ch<tweet.length(); ch++)
{
if(tweet.charAt(ch) == '#' && ((ch++)<=(tweet.length())) && (tweet.charAt(ch++)!=' ' && tweet.charAt(ch++)!='\t'))
{
hash++;
}
if(tweet.charAt(ch) == '#' && ((ch++)<=(tweet.length())) && (tweet.charAt(ch++)!=' ' && tweet.charAt(ch++)!='\t'))
{
attr++;
}
if(tweet.charAt(ch) == 'h' && ((ch + 7)<=(tweet.length())))
{
String a = new String("http://");
String sub = new String(tweet.substring(ch, ch + 7));
if (sub.equals(a))
{link++;}
}
}
System.out.println("Number of Hashtags: " + hash);
System.out.println("Number of Attributions: " + attr);
System.out.println("Number of Links: " + link);
}
}
}

Because of ch++ the value of ch is getting incremented after checking this condition (ch++)<=(tweet.length()).
Explanation :
if(tweet.charAt(ch) == '#' && ((ch++)<=(tweet.length())) && (tweet.charAt(ch++)!=' ' && tweet.charAt(ch++)!='\t'))
{
hash++;
}
For above code there are 4 conditions (for i=0):
tweet.charAt(ch) ch = 0
((ch++)<=(tweet.length())) ch = 0, but ch++ so the value will be increamented after the condition check.
(tweet.charAt(ch++) ch=1 (becuase of Point No. 2)
tweet.charAt(ch++) ch = 2 (for the same reason).
Try this:
class Main{
public static void main (String str[]) throws IOException {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a tweet:");
String tweet = scan.nextLine();
int hash = 0;
int attr = 0;
int link = 0;
int ch = 0;
if(tweet.length()>140)
{
System.out.println("Excess Characters: " + (tweet.length() - 140 ));
}
else
{
tweet=tweet.toLowerCase();
System.out.println("Length Correct");
for(ch=0; ch<tweet.length(); ch++)
{
if(tweet.charAt(ch) == '#' && ((ch+1)<(tweet.length())) && (tweet.charAt(ch+1)!=' ' && tweet.charAt(ch+1)!='\t'))
{
hash++;
}
if(tweet.charAt(ch) == '#' && ((ch+1)<(tweet.length())) && (tweet.charAt(ch+1)!=' ' && tweet.charAt(ch+1)!='\t'))
{
attr++;
}
if(tweet.charAt(ch) == 'h' && ((ch + 7)<(tweet.length())))
{
String a = new String("http://");
String sub = new String(tweet.substring(ch, ch + 7));
if (sub.equals(a))
{link++;}
}
}
System.out.println("Number of Hashtags: " + hash);
System.out.println("Number of Attributions: " + attr);
System.out.println("Number of Links: " + link);
}
}
}

Related

Logic error while trying to solve adventofcode day 4

This is on day four of advent of code part two...
I tried out the sample input they gave and it was correct and I used the input I have and comes out wrong every time
What I see 1
What I see 2
There is more below but its what happens after you solve the first part
Advent of code day 4
Puzzle input
The input differs by user but the code should be the same no matter the input
byr (Birth Year) - four digits; at least 1920 and at most 2002.
iyr (Issue Year) - four digits; at least 2010 and at most 2020.
eyr (Expiration Year) - four digits; at least 2020 and at most 2030.
hgt (Height) - a number followed by either cm or in:
If cm, the number must be at least 150 and at most 193.
If in, the number must be at least 59 and at most 76.
hcl (Hair Color) - a # followed by exactly six characters 0-9 or a-f.
ecl (Eye Color) - exactly one of: amb blu brn gry grn hzl oth.
pid (Passport ID) - a nine-digit number, including leading zeroes.
cid (Country ID) - ignored, missing or not.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
File inputText = new File("src/input.txt");
Scanner sc = new Scanner(inputText);
ArrayList<ArrayList> ids = new ArrayList<>();
ArrayList<ArrayList> attributes = new ArrayList<>();
while (sc.hasNextLine()) {
String builtString = "";
String input = "1";
while(input.length() != 0 && sc.hasNextLine()) {
input = sc.nextLine();
builtString += input + " ";
}
String[] temp = builtString.split(" ");
ArrayList<String> tempIds = new ArrayList<>();
ArrayList<String> tempAttributes = new ArrayList<>();
for (String i : temp) {
tempIds.add(i.split(":")[0]);
tempAttributes.add(i.split(":")[1]);
}
ids.add(tempIds);
attributes.add(tempAttributes);
}
System.out.println(ids);
System.out.println(attributes);
int valid = 0;
for (int a = 0; a < ids.size(); a++) {
int has = 0;
for (int j = 0; j < ids.get(a).size(); j++) {
String id = ids.get(a).get(j).toString();
String attribute = attributes.get(a).get(j).toString();
if (id.contains("ecl")) {
if (attribute.contains("blu") || attribute.contains("brn") || attribute.contains("gry") || attribute.contains("grn") || attribute.contains("hzl") || attribute.contains("oth")) {
System.out.println(attribute + " is an eye color");
has++;
} else {
System.out.println(attribute + " is not an eye color");
}
has++;
}
if (id.contains("pid")) {
if (attribute.length() == 9) {
try {
Integer.parseInt(attribute);
System.out.println(attribute + " of pid attribute is valid ");
has++;
} catch (Exception e) {
System.out.println(attribute + " of pid attribute is not valid");
}
}
has++;
}
if (id.contains("eyr")) {
int at = Integer.parseInt(attribute);
if (at >= 2020 && at <= 2030) {
System.out.println(attribute + " attribute of eyr is valid");
has++;
} else {
System.out.println(attribute + " attribute of eyr is not valid");
}
has++;
}
if (id.contains("hcl")) {
boolean isValid = false;
if (attribute.contains("#")) {
for (char c : attribute.toCharArray()) {
if (attribute.length() == 7) {
if ((c >= 'a' && c <= 'f') || c == '#') {
isValid = true;
} else if (Character.isDigit(c)) {
isValid = true;
} else {
isValid = false;
break;
}
}
}
}
if (isValid) {
has++;
}
System.out.println(attribute + " hcl is " + isValid);
has++;
}
if (id.contains("byr")) {
int date = Integer.parseInt(attribute);
if (date >= 1920 && date <= 2002) {
System.out.println(attribute + " byr attribute is valid");
has++;
} else {
System.out.println(attribute + " byr attribute is not valid");
}
has++;
}
if (id.contains("iyr")) {
int date = Integer.parseInt(attribute);
if (date >= 2010 && date <= 2020) {
has++;
} else {
System.out.println(attribute + " iyr is false");
}
has++;
}
if (id.contains("hgt")) {
boolean isValid = false;
String type = attribute.replaceAll("[^A-Za-z]", "");
int amount = Integer.parseInt(attribute.replaceAll("[^0-9]", ""));
if (type.equals("in")) {
if (amount >= 59 && amount <= 76) {
isValid = true;
has++;
}
} else if (type.equals("cm")) {
if (amount >= 150 && amount <= 193) {
isValid = true;
has++;
}
}
System.out.println(attribute + " hgt is " + isValid);
has++;
}
}
System.out.println();
if (has >= 14) {
valid++;
}
}
System.out.println(valid);
System.out.println("End");
}
}
you forgot the 'amb' eye colour. If you add this to the if statement on line 41 it should work
if (attribute.contains("amb") || attribute.contains("blu") || attribute.contains("brn") || attribute.contains("gry") || attribute.contains("grn") || attribute.contains("hzl") || attribute.contains("oth")) {

print the word which has maximum number of vowel in java

I want to print the word which is containing maximum number of vowel. But Problem is that last word of sentence which is containing maximum number is not print. please help me solve that problem. My code is below.
When i enter input 'Happy New Year', Output is 'Yea' .But i want i output is 'Year'
import java.util.Scanner;
public class Abcd {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter The Word : ");
String sentence = sc.nextLine();
String word = "";
String wordMostVowel = "";
int temp = 0;
int vowelCount = 0;
char ch;
for (int i = 0; i < sentence.length(); i++) {
ch = sentence.charAt(i);
if (ch != ' ' && i != (sentence.length() - 1)) {
word += ch;
ch = Character.toLowerCase(ch);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
vowelCount++;
}
} else {
if (vowelCount > temp) {
temp = vowelCount;
wordMostVowel = word;
}
word = "";
vowelCount = 0;
}
}
System.out.println("The word with the most vowels (" + temp + ") is: " + " " + wordMostVowel);
}
}
You cut words at spaces (correct), but you also cut at the last character, even if it's not a space (so this character is never dealt with). And that's not correct.
Here is a possibility:
import java.util.Scanner;
public class Abcd {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the sentence : ");
String sentence = sc.nextLine();
String wordMostVowels = "";
int maxVowelCount = 0;
for (String word : sentence.split(" ")) {
int vowelCount = 0;
for (char c : word.toLowerCase().toCharArray()) {
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
vowelCount++;
}
}
if (vowelCount > maxVowelCount) {
maxVowelCount = vowelCount;
wordMostVowels = word;
}
}
System.out.println("The word with the most vowels (" + maxVowelCount + ") is: " + wordMostVowels);
}
}

Flesch Index program Java

I am writing this program that calculates the Flesch index of a passage in Java. A few things: I can't figure out how to make it to where you can input as many words as you like while hitting enter and it will not calculate (something like d tells it that no more input is coming). I am also having trouble with this boolean expression. I have tried & and && and it still doesn't work. I keep getting a message that says, "Syntax error on token "&&", throw expected"
import java.util.Scanner;
public class Flesch
{
public static void main (String [] args)
{
Scanner input = new Scanner (System.in);
// Declare variables for syllables and words
int totalWords = 0;
int totalSyllables = 0;
// Prompt user for a passage of text
System.out.println ("Please enter some text:");
String passage = input.nextLine();
// Words
for (int i = 0; i < passage.length(); i++)
{
if (passage.charAt(i) == ' ') {
totalWords++;
}
else if (passage.charAt(i) == '.') {
totalWords++;
}
else if (passage.charAt(i) == ':') {
totalWords++;
}
else if (passage.charAt(i) == ';') {
totalWords++;
}
else if (passage.charAt(i) == '?') {
totalWords++;
}
else if (passage.charAt(i) == '!') {
totalWords++;
}
else {
totalWords = totalWords;
}
}
System.out.println ("There are " + totalWords + " words.");
char syllableList [] = {'a', 'e', 'i', 'o', 'u', 'y'};
// Syllables
for (int k = 0; k < syllableList.length; k++)
{
for (int i = 0; i < passage.length(); i++)
{
if (passage.charAt(i) == syllableList[k]) && (passage.charAt(i) == syllableList[k]); {
totalSyllables = totalSyllables;
}
if (passage.charAt(i) == syllableList[1] + ' ') {
totalSyllables = totalSyllables;
}
if (passage.charAt(i) == syllableList[k]) {
totalSyllables++;
} else {
totalSyllables = totalSyllables;
}
}
}
System.out.println ("There are " + totalSyllables + " syllables.");
}
}
I know I will have to type in the calculations, but right now I was just trying to get it to count the number of words and syllables. Once this works, I will add in the calculation to find the Flesch index. Thanks for the help guys. For some reason I get an error on the line that says
if (passage.charAt(i) == syllableList[k]) && (passage.charAt(i) == syllableList[k]);
And I have no clue why I am getting this or how to fix it.

Java String Calculator

I'm trying to make a simple calculator in Java which takes input in the form of a string and does a simple '+' and '-' operation.
Single digit inputs work but my problem is when i try to implement this for double digit
input string is: 5+20+5+11
list 1 = [5, 20, 2, 0, 5, 11, 1]
list 2 = [+, +, +]
Answer:27
I need to find a way where after storing [5] in list1 how i can add [5,20] instead of [5,20,2,0] which the current code is doing.
public int calC(String input) {
int len = input.length();
ArrayList list1 = new ArrayList();
ArrayList list2 = new ArrayList();
for (int i = 0; i < len; i++) {
if ((input.charAt(i) != '+') && (input.charAt(i) != '-')) {
// check if the number is double-digit
if ((i + 1 <= len - 1)) {
if ((input.charAt(i + 1) != '+')&& (input.charAt(i + 1) != '-')) {
String temp = "";
temp = temp + input.charAt(i) + input.charAt(i + 1);
int tempToInt = Integer.parseInt(temp);
// adding the double digit number
list1.add(tempToInt);
}
// add single digit number
list1.add(input.charAt(i) - '0');
}
} else {
// adding the symbols
list2.add(input.charAt(i));
}
}
int result = 0;
result = result + (int) list1.get(0);
for (int t = 0; t < list2.size(); t++) {
char oper = (char) list2.get(t);
if (oper == '+') {
result = result + (int) list1.get(t + 1);
} else if (oper == '-') {
result = result - (int) list1.get(t + 1);
}
}
return result;
}
Edit: working version
#Ker p pag thanks for the updated methods
input string is: 5+20+5+11
[5, 20, 5, 11]
[+, +, +]
Answer:41
I'll need to try to implement this with stack as suggested but the current version works
static boolean isDigit(char check) {
if (Character.isDigit(check)) {
return true;
}
return false;
}
public static int calC(String input) {
int len = input.length();
ArrayList list1 = new ArrayList();
ArrayList list2 = new ArrayList();
for (int i = 0; i < len; i++) {
if ((i + 1 <= len - 1)) {
if (isDigit(input.charAt(i)) && isDigit(input.charAt(i + 1))) {
String temp = input.charAt(i) + "" + input.charAt(i + 1);
int toInt = Integer.parseInt(temp);
list1.add(toInt);
i = i+1;
} else if (isDigit(input.charAt(i))) {
list1.add(input.charAt(i)- '0');
} else {
list2.add(input.charAt(i));
}
}
}
int result = 0;
result = result + (int) list1.get(0);
for (int t = 0; t < list2.size(); t++) {
char oper = (char) list2.get(t);
if (oper == '+') {
result = result + (int) list1.get(t + 1);
} else if (oper == '-') {
result = result - (int) list1.get(t + 1);
}
}
return result;
}
Here is the code:
String a = "5+20-15+8";
System.out.println(a);
String operators[]=a.split("[0-9]+");
String operands[]=a.split("[+-]");
int agregate = Integer.parseInt(operands[0]);
for(int i=1;i<operands.length;i++){
if(operators[i].equals("+"))
agregate += Integer.parseInt(operands[i]);
else
agregate -= Integer.parseInt(operands[i]);
}
System.out.println(agregate);
If you want the result 41 for input string "5+20+5+11",
why not use ScriptEngineManager with JavaScript engine,
public double calC(String input) {
int result = 0;
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
return (Double)engine.eval(input);
}
But note that the return type is double here.
If you want only int as return type in this case, try with this
return new BigDecimal(engine.eval(input).toString()).intValue();
Another way to think about this:
public class InlineParsing {
public static void main(String []args){
String input = "5-2+20+5+11-10";
input = input.replace(" ","");
String parsedInteger = "";
String operator = "";
int aggregate = 0;
for (int i = 0; i < input.length(); i++){
char c = input.charAt(i);
if (Character.isDigit(c)) {
parsedInteger += c;
}
if (!Character.isDigit(c) || i == input.length()-1){
int parsed = Integer.parseInt(parsedInteger);
if (operator == "") {
aggregate = parsed;
}
else {
if (operator.equals("+")) {
aggregate += parsed;
}else if (operator.equals("-")){
aggregate -= parsed;
}
}
parsedInteger ="";
operator = ""+c;
}
}
System.out.println("Sum of " + input+":\r\n" + aggregate);
}
}
It's basically a state machine that traverses over each char.
Iterate over each char:
if current char is a digit, add to current number buffer
if current char is not a digit or we're parsing the last digit
if an operator has been parsed use that to add the newly parsed number to the sum
if no operator has been parsed, set sum to current parsed number
clear current number buffer
store current char as operator
I agree that stack is the best solution,but still giving an alternative way
of doing this.
String input = "5+20+11+1";
StringBuilder sb = new StringBuilder();
List<Integer> list1 = new ArrayList<Integer>();
List<Character> list2 = new ArrayList<Character>();
char[] ch = input.toCharArray();
for(int i=0;i<ch.length;i++)
{
if(ch[i]!='+')
{
sb.append(ch[i]);
}else
{
list2.add(ch[i]);
list1.add(Integer.valueOf(sb.toString()));
sb.setLength(0);
}
}
if(sb.length()!=0)
list1.add(Integer.valueOf(sb.toString()));
System.out.println(list1.size());
for(Integer i:list1)
{
System.out.println("values"+i);
}
for storing the input to the list you could try this snippet
for (int i = 0; i < input.length() - 1; i++) {
// make a method
// check if current character is number || check if current
// character is number and the next character
if (isDigit(input.charAt(i)) && isDigit(input.charAt(i + 1))) {
list.add(input.charAt(i) +""+ input.charAt(i + 1));
} else if (isDigit(input.charAt(i))) {
list.add(input.charAt(i));
}else{
operator.add(input.charAt(i));
}
}
//check if it is a number
public boolean isDigit(char input){
if(input == '1' ||
input == '2' ||
input == '3' ||
input == '4' ||
input == '5' ||
input == '6' ||
input == '7' ||
input == '8' ||
input == '9' ||
input == '0')
return true;
return false;
}
I could advise you to use Exp4j. It is easy to understand as you can see from the following example code:
Expression e = new ExpressionBuilder("3 * sin(y) - 2 / (x - 2)")
.variables("x", "y")
.build()
.setVariable("x", 2.3)
.setVariable("y", 3.14);
double result = e.evaluate();
Especially for the case of using more complex expression this could be a better choice.
private static int myCal() {
String[] digits = {
"1",
"2",
"3",
"4",
"5"
};
String[] ops = {
"+",
"+",
"+",
"-"
};
int temp = 0;
int res = 0;
int count = ops.length;
for (int i = 0; i < digits.length; i++) {
res = Integer.parseInt(digits[i]);
if (i != 0 && count != 0) {
count--;
switch (ops[i - 1]) {
case "+":
temp = Math.addExact(temp, res);
break;
case "-":
temp = Math.subtractExact(temp, res);
break;
case "*":
temp = Math.multiplyExact(temp, res);
break;
case "/":
temp = Math.floorDiv(temp, res);
break;
}
}
}
return temp;
}
You can check this code that I created using array only. I also tried several arithmetic problems also your given problem.
Please see also the comments within the method.
public static String Calculator(String str) {
// will get all numbers and store it to `numberStr`
String numberStr[] = str.replaceAll("[+*/()-]+"," ").split(" ");
// will get all operators and store it to `operatorStr`
String operatorStr[] = str.replaceAll("[0-9()]+","").split("");
int total = Integer.parseInt(numberStr[0]);
for (int i=0; i<operatorStr.length; i++) {
switch (operatorStr[i]) {
case "+" :
total += Integer.parseInt(numberStr[i+1]);
break;
case "-" :
total -= Integer.parseInt(numberStr[i+1]);
break;
case "*" :
total *= Integer.parseInt(numberStr[i+1]);
break;
case "/" :
total /= Integer.parseInt(numberStr[i+1]);
break;
}
if(i+2 >= operatorStr.length) continue; // if meets the last operands already
numberStr[i+1] = String.valueOf(total);
}
return String.valueOf(total);
}
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
ArrayList<Character> listOfOpertionsCharFORM = new ArrayList<>();
ArrayList<Character> listOfNumbersCharFORM = new ArrayList<>();
ArrayList<Integer> listOfNumbersINTEGERFORM = new ArrayList<>();
int Total = 0;
Scanner sc = new Scanner(System.in);
String input;
System.out.print("Please enter your math equation :");
input = sc.nextLine();
System.out.println("string is : " + input);
separator();
char[] convertAllToChar = input.toCharArray();
for (char inputToChar : convertAllToChar) {
System.out.println("convertAllToChar " + inputToChar);
}
for (int i = 0; i < input.length(); i++) {
if (convertAllToChar[i] == '+') {
listOfOpertionsCharFORM.add(convertAllToChar[i]);
}
if (convertAllToChar[i] == '-') {
listOfOpertionsCharFORM.add(convertAllToChar[i]);
}
if (convertAllToChar[i] == '*') {
listOfOpertionsCharFORM.add(convertAllToChar[i]);
}
if (convertAllToChar[i] == '/') {
listOfOpertionsCharFORM.add(convertAllToChar[i]);
}
if (Character.isDigit(convertAllToChar[i])) {
listOfNumbersCharFORM.add(convertAllToChar[i]);
}
}
separator();
for (Character aa : listOfOpertionsCharFORM) {
System.out.println("list Of Operations Char FORM " + aa);
}
separator();
for (Character aa : listOfNumbersCharFORM) {
System.out.println("list Of Numbers Char FORM " + aa);
}
separator();
for (Character aa : listOfNumbersCharFORM) {
if (aa == '0') listOfNumbersINTEGERFORM.add(0);
if (aa == '1') listOfNumbersINTEGERFORM.add(1);
if (aa == '2') listOfNumbersINTEGERFORM.add(2);
if (aa == '3') listOfNumbersINTEGERFORM.add(3);
if (aa == '4') listOfNumbersINTEGERFORM.add(4);
if (aa == '5') listOfNumbersINTEGERFORM.add(5);
if (aa == '6') listOfNumbersINTEGERFORM.add(6);
if (aa == '7') listOfNumbersINTEGERFORM.add(7);
if (aa == '8') listOfNumbersINTEGERFORM.add(8);
if (aa == '9') listOfNumbersINTEGERFORM.add(9);
}
for (Integer aaa : listOfNumbersINTEGERFORM) {
System.out.println("list Of Numbers INTEGER FORM " + aaa);
}
separator();
separator();
separator();
System.out.print(listOfNumbersINTEGERFORM);
System.out.print(listOfOpertionsCharFORM);
System.out.println();
System.out.println();
if (listOfNumbersINTEGERFORM.size() == (listOfOpertionsCharFORM.size() + 1)) {
for (int i = 0; i < listOfOpertionsCharFORM.size(); i++) {
System.out.println("i :" + i);
if (listOfOpertionsCharFORM.get(i) == '+') if (i == 0) {
Total = Total + listOfNumbersINTEGERFORM.get(i) + listOfNumbersINTEGERFORM.get(i + 1);
System.out.println("total : " + Total);
separatorShort();
} else {
Total = Total + listOfNumbersINTEGERFORM.get(i + 1);
System.out.println("total : " + Total);
separatorShort();
}
if (listOfOpertionsCharFORM.get(i) == '-') if (i == 0) {
Total = Total + listOfNumbersINTEGERFORM.get(i) - listOfNumbersINTEGERFORM.get(i + 1);
System.out.println("total : " + Total);
separatorShort();
} else {
Total = Total - listOfNumbersINTEGERFORM.get(i + 1);
System.out.println("total : " + Total);
separatorShort();
}
if (listOfOpertionsCharFORM.get(i) == '*') if (i == 0) {
Total = Total + listOfNumbersINTEGERFORM.get(i) * listOfNumbersINTEGERFORM.get(i + 1);
System.out.println("total : " + Total);
separatorShort();
} else {
Total = Total * listOfNumbersINTEGERFORM.get(i + 1);
System.out.println("total : " + Total);
separatorShort();
}
if (listOfOpertionsCharFORM.get(i) == '/') if (i == 0) {
Total = Total + listOfNumbersINTEGERFORM.get(i) / listOfNumbersINTEGERFORM.get(i + 1);
System.out.println("total : " + Total);
separatorShort();
} else {
Total = Total / listOfNumbersINTEGERFORM.get(i + 1);
System.out.println("total : " + Total);
separatorShort();
}
}
} else {
System.out.println("*********###############**********");
System.out.println("** your input not correct input **");
System.out.println("*********###############**********");
}
System.out.println("*** Final Answer *** : " + Total);
}
public static void separator() {
System.out.println("___________________________________");
}
public static void separatorShort() {
System.out.println("_____________");
}

why is indexof not working?

I have a program for a hangman game and the indexof is not working for me? its on line 30. I have been trying to figure it out but I cannot.if (guessedWord.indexOf(letter) >= 0). I will keep trying to find out what I did wrong
import java.io.PrintStream;
import java.util.Scanner;
public class Hangman
{
public static void main(String[] args)
{
String[] words = { "write", "program", "that", "receive", "positive" };
Scanner input = new Scanner(System.in);
char anotherGame;
do
{
int index = (int)(Math.random() * words.length);
String hiddenWord = words[index];
StringBuilder guessedWord = new StringBuilder();
for (int i = 0; i < hiddenWord.length(); i++) {
guessedWord.append('*');
}
int numberOfCorrectLettersGuessed = 0; int numberOfMisses = 0;
while (numberOfCorrectLettersGuessed < hiddenWord.length()) {
System.out.print("(Guess) Enter a letter in word " + guessedWord +
" > ");
String s = input.nextLine();
char letter = s.charAt(0);
if (guessedWord.indexOf(letter) >= 0) {
System.out.println("\t" + letter + " is already in the word");
} else if (hiddenWord.indexOf(letter) < 0) {
System.out.println("\t" + letter + " is not in the word");
numberOfMisses++;
} else {
int k = hiddenWord.indexOf(letter);
while (k >= 0) {
guessedWord.setCharAt(k, letter);
numberOfCorrectLettersGuessed++;
k = hiddenWord.indexOf(letter, k + 1);
}
}
}
System.out.println("The word is " + hiddenWord + ". You missed " + numberOfMisses + (numberOfMisses <= 1 ? " time" : " times"));
System.out.print("Do you want to guess for another word? Enter y or n> ");
anotherGame = input.nextLine().charAt(0);
}while (anotherGame == 'y');
}
}
You are passing in a char where String is expected. Try using String.valueOf(letter) like this:
if (guessedWord.indexOf(String.valueOf(letter)) >= 0) {
// Your code
}
StringBuilder#indexOf(char) is undefined. You could do
if (guessedWord.indexOf(Character.toString(letter)) >= 0) {
there's no indexOf(char) method for a StringBuilder.
guessedWord.indexOf(letter)
should be
if (guessedWord.toString().indexOf(letter) >= 0) {

Categories