I'm new to JAVA and am working on a task to:
Take as input a user string
Take as input a user integer
Use the integer as an increment value
Return all character values in the string starting from 0 ending at the last character available after incrementing.
I'm getting correct results in terminal immediately followed by the dreaded StringOutOfBoundsException error. I'm not able to see where I am attempting to access a character in the string that is out of bounds and would be grateful for your expertise locating my error. Here is a snippet of my code:
import java.util.*;
public class EveryOtherCharacter
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
//initialize all variables to be used in this program
String userEntry;//store user word as a String
String error=("Invalid Entry!");//notify of error
String purpose=("Enter a word and an increment value and we'll\nreturn each character in your word using the number you provided".)
int increment;//store increment integer from user
int userEntryCount;//store total count of chars in userEntry
char value;//get character at increment value from userEntry
System.out.println("========================START PROGRAM=============================");
System.out.println(purpose);
System.out.println();//whitespace
System.out.print("Enter a word: ");
userEntry=input.nextLine();
userEntryCount = userEntry.length();
System.out.print("Enter an increment value: ");
increment=input.nextInt();
System.out.println();//whitespace
value=userEntry.charAt(0);
System.out.print(value);
for (int count=0; count <= userEntryCount; count++)
{
value=userEntry.charAt(increment);
userEntry=userEntry.substring(increment);
System.out.print(value);
}
if (increment > userEntryCount && increment <= 0)
{
System.out.println(error);
}
System.out.println();//whitespace
System.out.println("=========================END PROGRAM==============================");
}
}
Here is an example of what my terminal output looks like after running this program. Notice that the correct output is present immediately before the exception error:
java EveryOtherCharacter
========================START PROGRAM=============================
Enter a word and an increment value and we'll
return each character in your word using the number you provided
Enter a word: whyisthissohard
Enter an increment value: 3
wihsaException in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 3
at java.lang.String.charAt(String.java:658)
at EveryOtherCharacter.main(EveryOtherCharacter.java:57)
You're cutting through whyisthissohard by 3 each time. But you are looping through whyisthissohard's length in total.
for (int count=0; count <= userEntryCount; count++)
{
value=userEntry.charAt(increment);
userEntry=userEntry.substring(increment);
System.out.print(value);
}
First loop : value = 'i' ; userEntry = "isthissohard" ;
Second loop : value = 'h' ; userEntry = "hissohard";
Third loop : value = 's' ; userEntry = "sohard";
Fourth loop : value = 'a' ; userEntry = "ard";
Fifth loop => Error
I think when the instructions say "Use the integer as an increment value", you should be using it as an actual increment value like so.
public static void main(String[] args) {
String s = "whyisthissohard";
int skip = 3;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i += skip) { // <--- Increment value
sb.append(s.charAt(i));
}
//Return all character values in the string
System.out.println(sb.toString()); // wihsa
}
You could also print them all in the for-loop instead of adding to another string, if you want.
I ended up solving this using a while loop as follows:
while (n < length)//where n=userNumber & length=length of user word
{
character=userEntry.charAt(n);//character becomes the character of the word at the increment value
System.out.print(character);//print value of character at increment
userEntry=userEntry.substring(n);//set userEntry to value of new string starting at n
length = userEntry.length();//count the total number of characters in the new substring
}
After going through the logic of the for loop, I realized i had created and was trying to increment the value of i and that wasn't necessary. You all were a really big help in making think through the problem. I appreciate your help!
Related
I am a student and kind of new to Java. For my homework I have to:
Ask the user to input a number (at least 7) using a do while loop.
Using a for loop I am required to ask the user to input that number of words.
Then I have to check if one of the words fulfills the given conditions:
The word must:
Start with an uppercase letter
End with a number
Contain the word "cse".
I am asked to create a method inside some code homework that does a specific task, the method should check all the required conditions, the name of the method should be countTest and it accepts the String as a parameter.
I will show you my code but I don't know how to create this specific method.
Output format
System.out.println("There as a total number of words " + count + " and
the ones that fulfill the condition are: " + condition);
The problem is, I dont know how to create the method or constructor or whatever it is called that calls all of the 3 methods inside it, and then connect that particular method to the main method!
I hope you guys can understand I am new to this, thank you in advance!
public class D6_6 {
public static void main(String[]args){
Scanner sc = new Scanner(System.in);
System.out.println("Type a number that is at least 7");
int number = sc.nextInt();
int count = 0;
int condition = 0;
do{
if(number<7){
System.out.println("You should type a number that is at least 7 or higher");
number = sc.nextInt();
}
}
while(number<7);
sc.nextLine();
String str;
for(int i =0; i<number; i++){
System.out.println("Type a word");
str = sc.nextLine();
count++;
}
}
public boolean countTest(String str) {
}```
To check if the word start with an uppercase:
You can do that by first selecting the character you want to check by str.charAt(0). This will return a char that is the first letter of the input str.
To check if this char is an uppercase letter, you can easily use char.isUppercase(). This will return a boolean. You have to replace char by the name of the variable were you put the char of str.charAt(0) in.
To check if the last character is a number:
You can do that again by first selecting the last character by str.charAt(str.length()-1), were string.length-1 is the number of the last character.
To check if this character is a number, you can use the ascii table. Every character has it's own number. So if you want to check if your character is between 0 and 9, you can use char >= 48 || char <= 57 (look up in the ascii table). Again, char is the name of the variable were you put the char of str.charAt(str.length()-1) in.
To check if the word contains "cse":
There is a very easy method for that: str.contains("cse") will return a boolean that is true when "cse" is in the word and false when the word does not contain "cse".
I hope it is clear for you now!
I think I did it, thank you guys very much, I appreciate it!
public class D6_6 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Type a number that is at least 7");
int number = sc.nextInt();
int count = 0;
int condition = 0;
do {
if (number < 7) {
System.out.println("You should type a number that is at least 7 or higher");
number = sc.nextInt();
}
}
while (number < 7);
sc.nextLine();
String str;
for (int i = 0; i < number; i++) {
System.out.println("Type a word");
str = sc.nextLine();
count++;
if((countTest(str))){
condition++;
}
}
if(count == 0){
System.out.println("No words typed");
} else {
System.out.println("Total number of words typed: " + count + ", which fulfill the condition: "+ condition);
}
}
public static boolean countTest(String str) {
return Character.isUpperCase(str.charAt(0)) && str.charAt(str.length() - 1) >= 48 || str.charAt(str.length() - 1) <= 57 || str.contains("cse");
}
}```
Homework problem got the first 4 questions got stuck on this last one. If the user inputted hello as the string and 3 as the integer it's supposed to print "helheh" when I try it prints "helhehehehehe"
Question:Write a program that reads a string and an integer, n, from the user. Output a string made of the first n characters of the string, followed by the first n-1 characters of the string, and so on. You may assume that n is between 0 and the length of the string, inclusive.
I tried having it add to the string with i-1 in the substring section but that didn't work.
System.out.println("Please input a string: ");
string = in.next();
System.out.println("Please input an integer: ");
n = in.nextInt();
int lenstring = string.length();
String tring = string.substring(0,n);
for(int i = lenstring; i>0; i--)
{
con += string.substring(0,n-1);
}
System.out.println(tring+con);
Here, try this:
for( int i = n; i > 0; i-- )
con += string.substring( 0, i );
System.out.println( con );
I have not tried it, but I believe it should work.
In any case, if you just think about it, it may help you understand what you need to do and why you need to do it this way and not some other way.
Try replacing the for statement with
for(int i=0; i<n; i++)
{
con += string.substring(0,n-i);
}
If you want first characters of a string, the first argument to substring must be 0. It is. Check.
If you want n, n-1, ... 1 characters of a string, the second argument to substring must be n, n-1, ... 1. In your loop, it obviously not. Your loop should be from n to 1 (or 0, but concatenating an empty string makes no sense).
you could use the n for the loop
System.out.println("Please input a string: ");
String string = in.next();
System.out.println("Please input an integer: ");
int n = in.nextInt();
String con = "";
String tring = string.substring(0,n);
for(; n>0; n--)
{
con += string.substring(0,n-1);
}
System.out.println(tring+con);
Write a java programm to print a output like this
input : d3f4cf5
output dddffffcfcfcfcfcf
for(int i=0; i<str.length();i++)
{
if(Character.isDigit(str.charAt(i)))
{r = str.charAt(i);
for(r=1;r<=i;r++) {
System.out.println(str.substring(t, i));
t = ++i;
}
}
if (i==str.length()-1) {
for (r = 1; r <= i; r++) {
System.out.println(str.substring(t));
}
}
}
Well, as Ronald suggested you could split your string and run over the arrays.
For how to split have a look here: Java - Split String by Number and Letters
Let's assume we then just have the array ["d","3","f","4","cf","5"]. You then could do something like this:
for( int i = 0; i < array.length; i += 2 ) {
String letters = array[i];
int count = Integer.parseInt( array[i + 1] );
//loop and print here
}
Note that this always expects the string to start with at least one letter and end with a number. If it doesn't you'd have to handle that explicitly, i.e. don't print anything for the first number if it starts with a number (that could be done by just "printing" an empty string n times) and assume a count of 1 if the input ends with letters.
If you can't use regular expressions for some reason you could also do it while iterating over the characters of the string. You'd then use a combination of the following steps:
If the character is a letter you're in string building mode. You add the character to a temporay string. Initially that temporary string would be empty.
If the character is a digit you're in counting mode. You add the digit to a temporary counter (which you'd first multiply with 10 if you want to support more than one digit numbers). The counter would initially have the value 0.
When you switch from counting mode to string building mode you print the current temporary string as often as you've counted, then reset the counter to 0 and the temporary string to empty ("") and repeat step 1 (you add the current character to the temp string).
When you hit the end of the input you do the same as in step 3. If you need to support input ending in letters you'd probably want to assume a count of 1 so before executing step 3 you'd set the counter (which should still be 0) to 1.
If your input is well formed something like below should work:
public static void main(String[] args){
String input = "d3f4cf5";
System.out.println(uncompress(input));
}
private static String uncompress(String input) {
//Split input at each number and keep the numbers
// for the given input this produces [d3, f4, cf5]
String[] parts = input.split("(?<=\\d+)");
StringBuilder sb = new StringBuilder();
for(String str : parts){
// remove letters to get the number
int n = Integer.parseInt(str.replaceAll("[^0-9]", ""));
// remove numbers to get the letters
String s = str.replaceAll("[0-9]", "");
// append n copies of string to sb
sb.append(String.join("", Collections.nCopies(n, s)));
}
return sb.toString();
}
I am exercising for my course in java and the task is to write a program which has the input of a list separeted with spaces. And the key is to turn the list around, i.e. put the first place on the last second on the one before last and truncate the negatives. But I am keep getting this error of StringIndexOutOfBounds. What seems to be the problem?
public static void main(String args[])
{
Scanner in = new Scanner (System.in);
System.out.println("Insert the list: ");
String input = in.nextLine();
String out = out(input);
System.out.println(out);
}
public static String out (String input){
String reverse = "";
int counter = 0;
while (counter<=input.length()){/*
String min = input.charAt(counter) + input.charAt(counter+1);
int num = Integer.parseInt(min) ;
if ( num>=0 ){*/
reverse+= input.charAt(counter);
counter++;
/*}*/
}
return reverse;
}
I suspect your StringIndexOutOfBounds comes from the fact you are iterating from index 0 to index input.length, so 1 too many.
For the sake of charAt the Strings in Java are 0-indexed, so you start counting from 0 (what you would call 'first' in plain English). In such a situation, the last character is at index length-1.
So, to be specific. Your next thing to fix is the condition in the while loop. I think your intention was to say:
while (counter < input.length()) {
...
Any String has characters from index 0 to length-1. If you would try to do charAt(length), you would end up with StringIndexOutOfBounds.
Change the while line to below & it should work:
while (counter<input.length()){
I have a problem is when i input value for array 2d with value valid, everything done but when i input wrong value for totalRow or totalColumn variable then my Input function forced me to input double and get value in 2nd.
It is my code:
public static void input() {
Scanner sc = new Scanner(System.in);
try {
System.out.println("Input total totalRow: ");
totalRow = sc.nextInt();
// verify value input must be a positive integer and greater than zero
if (totalRow <= 0) {
System.out.println("Input value must be a positive integer and greater than zero!");
input();
}
System.out.println("Input total totalColumn: ");
totalColumn = sc.nextInt();
// verify value input must be a positive integer and greater than zero
if (totalRow <= 0) {
System.out.println("Input value must be a positive integer and greater than zero!");
input();
}
// check case array must be square array
if (totalRow != totalColumn) {
System.out.println("Array must be square!");
input();
}
} catch (InputMismatchException e) {
// print message when user input other than integer
System.out.println("Please input an integer!");
input();
}
// initialize array with totalRow and totalColumn
array = new char[totalRow][totalColumn];
// input value for array
for (int i = 0; i < totalRow; i++) {
for (int j = 0; j < totalColumn; j++) {
array[i][j] = sc.next().charAt(0);
}
}
}
Example: I enter 2 and a for totalRow and totalColumn: message appear and i re-enter is 2 and 2, but i have entered 1 2 3 4 5 6 7 8 for array and value get from 5.
You have a couple of things here that are making your code to fail:
Typo: you are checking totalRow <= 0 twice (copy paste error for sure)
If condition not met, then you call input again:
doing this will make a recursive implementation of the method, that can lead to a not desired repetition of the sequence, driving crazy the user and the developer
you are forgetting that scanner.nextInt does not consume the last newline character of your input
I would suggest to modify the Code by doing something like:
if (totalRow <= 0) {
System.out.println("Input value must be a positive integer and greater than zero!");
//input();
}
System.out.println("Input total totalColumn: ");
totalColumn = sc.nextInt();
sc.nextLine();
// verify value input must be a positive integer and greater than
// zero
if (totalColumn <= 0) {
System.out.println("......
There is a problem with Recursion algorithm. Even it works for a correct input, foe a wrong input it will repeatedly ask for values. Since when you make any mistake Input() function will start again from the beginning. So if you want to use recursion better to use separate functions for input_Total_Column() and input_Total_Row() .
And there is also a copy paste error. You are checking totalColumn<=0 twice in your code.
//Your code//
`for (int i = 0; i < totalRow; i++) {
for (int j = 0; j < totalColumn; j++) {
array[i][j] = sc.next().charAt(0);
}
}
}`
if you enter the values in a raw this seems to be a incorrect logic. charAt(0) will return a charactor at the inedex 0(Only . So always it wold be returning the charactor at begining. Try it like this.
string array_input= sc.nextLine();
split the string using .split() function.
then you can easily convert the values to integer using Integer.parseInt() at corresponding string value.