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()){
Related
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'm trying to make a short program that converts any string into T H I S F O N T.
For example: "This is a test sentence" turns into "T H I S I S A T E S T S E N T N C E"
I have a StringBuilder inside a while loop, but using finale.insert(i, '\t'); doesn't work.
import java.util.Scanner;
public class Executable {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String x;
int i = 0;
System.out.print("Input text here: ");
x = input.nextLine();
StringBuilder finale = new StringBuilder(x.toUpperCase());
while(i > finale.length()) {
if(finale.substring(i, i) == " ") {
i += 2;
finale.insert(i, '\t');
}
}
System.out.println(finale);
}
}
Any help?
You have a few issues with your code. Before I present an implementation that works, let's look at those other issues.
Your while loop checks if i > finale.length(). Since i = 0 the while loop never has a chance to begin.
You are comparing strings using == and this is not correct. == is used to confirm two objects are equal, not the value of two strings. You would need to use string.equals() instead.
You're doing too much in your loop anyway. Using a simple for loop can accomplish the goal quite simply.
Here is a new loop you can use instead of what you have:
for (int i = 1; i < finale.length(); i++) {
finale.insert(i++, " ");
}
The output: T H I S F O N T
For those unfamiliar with for loops, here's a very simple breakdown of how the above is structured.
The for loop is defined in three parts:
for (variable_to_increment; repeat_until_this_condition_is_met; modify_variable_on_each_iteration) {
// Code to be executed during each pass of the loop
}
First, we define a variable that we can track on each loop: int i = 1. By setting i = 1, we are going to skip the first character in the string.
The next statement, i < finale.length() means that we want to keep repeating this loop until we reach the length of our string. For example, if the string is 5 characters long and we've run the loop 4 times, i now equals 5 and is no longer less than the string's length, so the loop ends.
The last part is i++. This tells Java what we want to do with i after each loop. In this case, we want to increment the value by 1 each time the loop repeats.
Everything inside the brackets is, obviously, the code we want to execute on each loop.
You're saying while i>finale.length() but i is initialized as 0. You never enter the while loop.
Some issues with your code (see inline comments):
import java.util.Scanner;
public class Executable {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String x;
int i = 0;
System.out.print("Input text here: ");
x = input.nextLine();
StringBuilder finale = new StringBuilder(x.toUpperCase());
while(i > finale.length()) { // this condition is incorrect. Initially
// this condition will always be false
// if you input some sentence. It should be
// i < finale.length()
if(finale.substring(i, i) == " ") { // here preferably you should use
// equals method to compare strings
i += 2;
// you are only incrementing the i if the ith
// substring equals " ". Firstly, substring(i,i)
// will return empty string because the second argument
// is exclusive
finale.insert(i, '\t');
}
}
System.out.println(finale);
}
}
If you want to have an alternate method (not very optimal) for doing what you want to do, you can try the following approach:
import java.util.Scanner;
public class Executable {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String x;
int i = 0;
System.out.print("Input text here: ");
x = input.nextLine();
String finale = x.toUpperCase().replaceAll(" ","").replaceAll("", " ");
System.out.println(finale);
}
}
First, convert the string to uppercase --> then remove all spaces between the words --> then insert spaces between all letters. The code line which does this is,
String finale = x.toUpperCase().replaceAll(" ","").replaceAll("", " ");
Here is a sample run:
Input text here: This is a sentence
T H I S I S A S E N T E N C E
The correct way with your method would be, just increment until you have twice the size of the initial String
while (i < x.length() * 2) {
finale.insert(i, '\t');
i += 2;
}
An easier way would be with a classic for-loop:
StringBuilder finale = new StringBuilder();
for (char c : x.toUpperCase().toCharArray()) {
finale.append(c).append('\t');
}
Use a for loop since you know the number of iterations:
Scanner input = new Scanner(System.in);
String x;
System.out.print("Input text here: ");
x = input.nextLine();
StringBuilder finale = new StringBuilder(x.toUpperCase());
int len = finale.length();
for (int i = 1; i < 2 * len; i+=2 ) {
finale.insert(i, '\t');
}
System.out.println(finale);
You are comparing strings with ==. Never do that; use equals instead.
For future readers: this job can be done elegantly using Java 8 Streams:
String result = str.chars()
.filter(i -> i != ' ')
.mapToObj(t -> (char) t)
.map(Character::toUpperCase)
.map(Character::valueOf)
.collect(Collectors.joining(" ");
import java.util.Scanner;
public class Project2 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String word;
String c;
int x, count, count1;
System.out.println("Please enter a word:");
word=in.nextLine();
x=word.length();
for(count=0;count<x;count++) {
count1=x;
count1--;
c=word.substring((count1)-1,count1);
System.out.println(c);
}
}
}
All this program does is print out the second to last character of the word that the user enters. I'm confused as to why it is doing this and want to know how to print out the whole word backwards. Someone help please.
You don't need a loop to reverse a string.
Ref - StringBuilder#reverse
Scanner in = new Scanner(System.in);
System.out.println(new StringBuilder(in.nextLine()).reverse());
If you want to print characters in reverse, then forget the substring-ing.
String word = in.nextLine();
int x = word.length();
for(count = x - 1; count >= 0; count--) {
System.out.println(word.charAt(count));
}
Take count1=x; assignment out of the loop. Also make count--; after printing the letter.
You are correct up until x = word.length(). It is printing the second from last character because you keep setting the value of count1 to length of word and you substract it by 1. Therefore, it keeps referring to the second last character. To fix that, do the following instead:
count1=x;
for(count=0;count<x;count++) {
c=word.substring((count1)-1,count1);
System.out.println(c);
count1--;
}
Every time the loop is running, you are resetting the count1 value to x (count1=x). So c will always be the same value.
To make this work, try taking count1 = x out of the loop so that every time the loop is running, count1 value will be reduced as expected providing the required sub-string.
Into the loop for(count=0;count<x;count++)
Every loop you did the same thing
count1=x;
count1--;
c=word.substring((count1)-1,count1);
System.out.println(c);
This block has no relation with the loop!
Thats why you are getting the second last character!
To fix this:
Solution 1: (Just reverse the String)
word=in.nextLine();
System.out.println(new StringBuilder(word).reverse());
or Solution 2: (Using loop using your code)
x=word.length();
for(count= x-1; count >= 0; count--) {
c = word.substring((count)-1, count);
System.out.print(c);
}
If at all you want to do it the hard way by traversing, do the following changes.
for(count=x;count>=0;count--) {
System.out.println(word.substring(count - 1,count));
}
Update: You can use charAt#String to easily get the character at some position.
for(count=x-1;count>=0;count--) {
System.out.println(word.charAt(count));
}
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!
I need to concatenate output from a loop. User input will determine for how long it will last. I'm am trying to generate a password with generating a random number and then converting the number into ASCII character (all lowercase characters currently). Instead of having multiple for() how is it possible to concatenate the out put into one string based on the user input?
import java.util.Random;
import java.util.Scanner;
public class Password
{
public static void main (String[] args)
{
int randNum=0;
int min=97;
int max=122;
int az=0;
String b="";
String c="";
Scanner in= new Scanner (System.in);
Random randNumlist= new Random();
System.out.println("lowercase letters [a]");
String input= in.next();
System.out.println(" how many characters (max 14)");
int input2=in.nextInt();
if ( input.equalsIgnoreCase("A"))
{
while(!(randNum>=96 && randNum<=123))
{
for (int n=1; n <=input2; n++)
{
randNum= randNumlist.nextInt((max-min)+1)+min;
az =+randNum;
char p= (char)az;
b = new StringBuilder().append("").append(p).toString();
System.out.println(b);
}
}
}
}
}
Example input: a or A
2nd Example input: numbers 1-14
Example output:
a
e
b
h
Desired output: aebh
Several points:
Your for loop is pointless. You initialise n to input2 then loop until n == input2 meaning one iteration
Your while loop is pointless and will only also iterate once as randNum is set to between 96 and 123 in the first iteration
Declare your StringBuilder outside of the loop. Currently you create one for each iteration (which is only once) which means the previous String will be lost. Then in your loop just call the append method.
Print after the loop by calling the toString() method of your StringBuilder.
So something like this
StringBuilder sb = new StringBuilder()
//Start Loop
sb.append("Your character here");
//End Loop
System.out.println(sb.toString());