String index out of range even though the string is limited [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I am a student and I am learning Java.I recently got a question which said I had to find the largest word in a given string..I wrote a code but it is giving me an error that string index is out of bounds even though I limited it to the length of the string..Can someone help me with the code..Please use simple language(I am not an expert)
Code
import java.util.*;
class word
{
void def()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the string");
String s1=sc.nextLine();
int length=s1.length();
length++; //My name
int j=0; //0123456
int word=0;
int findex=0;
int lindex=0;
int lword=0;
for(int i=0;i<length;i++)
{
if(s1.charAt(i)==' ' && j==0)
{
lword=i;
findex=0;
lindex=i;
j=i;
}
else if(s1.charAt(i)==' ')
{
if(i-j-1>lword)
{
findex=j;
lindex=i;
lword=i-j-1;
}
j=i;
}
else if(i==length-1)
{
if(i-j-1>lword)
{
findex=j;
lindex=i;
}
}
}
System.out.println("Largest word is:"+s1.substring(findex,lindex+1));
}
}

By doing length++ you make sure that your length variable will be larger then the actual string length. at the last loop step there will be no char at s1.charAt(i)
Just remove the line with length++

Related

How do i fix it in Java [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
Hello i am trying to write a method that checks whether a
string is a valid password. I Suppose the password rules are as
follows:
A password must have at least ten characters.
A password consists of only letters and digits.
A password must contain at least three digits.
I wrote the code but i see this error i don't know why.
package javaapplication6;
import java.util.Scanner;
import javafx.beans.binding.Bindings;
public class JavaApplication6 {
public static boolean isvalidPassword(String nume){
int count = 0;
for(int i=0; i<nume.length();i++){
if(Character.isDigit(nume.charAt(i))){
count++;
}
}
if (count<3){
return false;
}
if (nume.length()<10){
return false;
}
for (int i = 0; i < nume.length(); i++) {
if (!Character.isLetter(nume.charAt(i)charAt(i)) && !Character.isDigit(nume.charAt(i))){
return false; }
}
return true;}
}
If you look closely at the line
if (!Character.isLetter(nume.charAt(i)charAt(i)) && !Character.isDigit(nume.charAt(i))){
you see, that charAt(i) is duplicate:
nume.charAt(i)charAt(i)
Remove one of the method calls and you should be fine.

Create a program that will input a heart symbol and will stop at the exclamation mark symbol (Call from another class with an argument) [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I showed this to my teacher and he said that I was 99% correct. The only problem is that I did not put an argument in the first class. I'm so confused because I don't think I've learned that part yet : (
Class 1:
import java.util.*;
public class hearts {
public static void hearts1(String[] args) {
char heart = '♥';
for (int i = 0; 1 < 254; i++)
{
System.out.print(heart++ + " ");
}
}
}
Class 2:
public class Caller {
public static void main(String[] args){
hearts.hearts1(args);
}
}
Generally I would advise you to not use "magical appeared" numbers in this sort of situation.
Furthermore you have created an endless loop because your loop condition is (1<254) which is alway true because 1 will always be smaller than 254.
Therefore I would write
for (char currentChar = heart; currentChar < '❣'; currentChar++)
{
System.out.print(currentChar + " ");
}
instead of
for (int i = 0; 1 < 254; i++)
{
System.out.print(heart++ + " ");
}
And generally said you are not using any arguments in your code...You are passing some arguments but you're never actually using them.
Maybe you should change your first class like this:
public static void hearts1(char startChar) {
char heart = startChar;
//...
}
And then change the calling to this:
hearts.hearts1('♥');
If you use this approach I would advise you to check if the given char-parameter (in Class1) is within a certain range of characters so you don't end up processing some chars you newver wanted to...
To take the idea with the scanner into consideration you could simply
public static hearts1() {
Scanner scanner = new Scanner(System.in);
System.outprinln("Enter starting char:");
String userInput = scanner.next();
char heart = userInput.charAt(0);
for (char currentChar = heart; currentChar < '❣'; currentChar++) {
System.out.print(currentChar + " ");
}
scanner.close();
}
But I don't advise this method because dependingon the user input it takes quite long for the program to print out the chars and furthermore it's really hard for the user to give the heart symbol as an input.
I hope this answers your question (partly)
Greetings Raven

Java - Having trouble converting char to string (beginner) [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I am trying to iterate through each character in a string that is inputted and check if any letter is a.
Here is my Java code:
import java.util.Scanner;
public class Input
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String input;
input = in.nextLine();
for (int i=0; i<input.length(); i++)
{
char chararcter = input.charAt(i);
String s = Character.toString(character); //the error is here
if (s.equals("a"))
{
System.out.println("You typed an A.");
}
}
}
}
For reference, here is a Python analog.
input=raw_input()
for i in range (0,len(input)):
if input[i] == "a":
print "You typed an A."
I apologize for the simplistic nature of this question; I'm very new to Java. Thank you for helping.
You've change the spelling in your declaration.
char character = input.charAt(i); // <-- not chararcter (extra rc).
You don't have to convert character to String. just simply do character comparison.
if (chararcter == 'a')
{
System.out.println("You typed an A.");
}

valid word counter out of bounds error [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
{
public static int WordCount (String cString)
{
String currentWord;
int index;
int spacePos;
int validWordCount=0;
boolean validWord;
char upClowC;
cString=cString.trim()+" ";
spacePos=cString.indexOf(" ");
validWord=true;
for(index=0;index<cString.length();index++)
{
currentWord=cString.substring(0,spacePos);
upClowC=Character.toUpperCase(currentWord.charAt(index));
if(upClowC<'A'||upClowC>'Z')
{
validWord=false;
}
}
if(validWord==true)
{
validWordCount++;
}
return validWordCount;
}
public static void main(String[] args)
{
String sentence;
System.out.println("enter a sentence:");
sentence=EasyIn.getString();
WordCount(sentence);
}
}
I'm trying to create a method which takes a sentence and picks out the valid words (i.e. no numbers or symbols), but I keep getting an out of bounds error.
I can't use an array.
Your problem is here:
currentWord = cString.substring(0, spacePos);
upClowC = Character.toUpperCase(currentWord.charAt(index));
currentWord gets shorter, but index is still running from 0 to the length of the string.
General notes:
Follow Java naming conventions and change the name of your method to begin with small letter
if(validWord) is enough when you want to compare something to true, otherwise it's like asking "is it true that the value is true" instead of simply "is the value true"
Next time post your stack trace to get better and sooner help
In your code, you are doing
spacePos = cString.indexOf(" ");
And then inside the loop:
currentWord = cString.substring(0,spacePos);
upClowC = Character.toUpperCase(currentWord.charAt(index));
Now, because of the loop, the index will take values from 0 to your string length minus 1. If your substring (currentWord) is smaller than your string - which probably is -, then currentWord.charAt(index) will try to index out of the bounds of the substring, which is why you get the error.

Output accumulates each iteration instead of resetting [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
The code runs properly the first time then run it again using the while loop and lets say the first time I entered AA and it becomes CC then it runs again I enter AA again it will come out with CCCC do it again it comes out with CCCCCC I don't want that I need it to not keep the data from the string each time it loops.
import java.util.*;
public class SecretCypher {
public static void main(String args[]) {
Scanner kb = new Scanner(System.in);
StringBuffer e = new StringBuffer();
System.out.println("Welcome to Secret Cypher!");
char loop = 'Y';
while(loop == 'Y' || loop == 'y') {
System.out.println("");
System.out.println("Enter your cypher in upper case.");
String s = kb.nextLine();
char[] cs = s.toCharArray();
for (int i = 0; i < cs.length; i++) {
e.append((char)('A' + (cs[i] - 'A' + 2) % 26));
}
if(s == s.toLowerCase()) {
System.out.println("Remember to use upper case letters!");
System.exit(0);//Also I was bored of using break and this works any where in the code.
}
System.out.println(e.toString());
System.out.println("Do you want to enter another cypher? > ");
String again = kb.nextLine();
if(again.charAt(0) == 'N') {
System.out.println("Hope you come back again!");
break;
}
}
}
}
You're reusing the same string buffer. If you keep putting things into the same buffer without clearing it, you're obviously going to get extraneous stuff from previous iterations.
Simply declare the StringBuffer inside the while loop so that it is created on each iteration.
Anyway, you should learn to use your debugger, instead of asking here for us to debug. If anything, using the debugger can offer extremely valuable insight into the troubles that you are having here.

Categories

Resources