Why wouldn't the code work in the for loop? - java

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);

Related

whats the simplest way to write a palindrome string using a while loop in java

I've searched about everywhere but I just can't find anything very concrete. I've been working on this code for awhile now but it keeps stumping me.
public static void main(String[] args) {
System.out.println(palindrome("word"));
}
public static boolean palindrome(String myPString) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a word:");
String word = in.nextLine();
String reverse = "";
int startIndex = 0;
int str = word.length() -1;
while(str >= 0) {
reverse = reverse + word.charAt(i);
}
}
There's a lot of ways to accomplish this using a while loop.
Thinking about simplicity, you can imagine how could you do this if you had a set of plastic separated character in a table in front of you.
Probably you'll think about get the second character and move it to the begin, then get the third and move to begin, and so on until reach the last one, right?
0123 1023 2103 3210
WORD -> OWRD -> ROWD -> DROW
So, you'll just need two code:
init a variable i with 1 (the first moved character)
while the value of i is smaller than total string size do
replace the string with
char at i plus
substring from 0 to i plus
substring from i+1 to end
increment i
print the string
The process should be:
o + w + rd
r + ow + d
d + row +
drow
Hope it helps
Here is an piece of code I write a while back that uses almost the same process. Hope it helps!
String original;
String reverse = "";
System.out.print("Enter a string: ");
original = input.nextLine();
for(int x = original.length(); x > 0; x--)
{
reverse += original.charAt(x - 1);
}
System.out.println("The reversed string is " +reverse);

How to check for a specific number of integers in a string

I have a program where i require the user to enter coordinates as a string. In order to make input easier to read and make inputs like (x,y) and x , y equal I first change all non numeric characters to " " then i try and use the .matches function to check for exactly two occurrences of integers
input = input.replaceAll("[^0-9]"," ");
Scanner lineRead = new Scanner(input);
System.out.println(input);
if(! (input.matches( "[//d] {2}" ) )
{
bad input
}
else
{
xPosition = lineRead.nextInt();
yPosition = lineRead.nextInt();
}
but no matter what I input the expression returns false. Im new to using regex is my syntax wrong or is this just not something I can do?
Rather than test the input against a regex, I believe the preferred way to use Scanner is to read the two ints you want, and catch certain exceptions if scanning does not succeed.
https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextInt()
e.g.
input = input.replaceAll("[^0-9]"," ");
Scanner lineRead = new Scanner(input);
System.out.println(input);
try {
xPosition = lineRead.nextInt();
yPosition = lineRead.nextInt();
} catch (
InputMismatchException |
NoSuchElementException |
IllegalStateException ex) {
bad input
}
If you do want a regex that tests the input for the presence of at least two integers, I think the following would do:
\d+.*\b\d+
That's, one or more digits (\d+), followed by anything (.*), followed by a word boundary (\b), followed by another one-or-more-digits (\d+)
Use \\s*\\d+\\s+\\d+\\s* instead of [//d] {2}.
You can avoid using a regex and just "searching" for the first and the second number. You start when you hit a number between 0 and 9 and stop, when you hit a non-digit. Repeat the same for the second number and you are good to go!
Scanner scanner = new Scanner(System.in);
String string = scanner.nextLine();
/* Search the first number */
int i = 0;
while (i < string.length() && !Character.isDigit(string.charAt(i))) i++;
int j = i;
while (j < string.length() && Character.isDigit(string.charAt(j))) j++;
int firstCoordinate = Integer.parseInt(string.substring(i, j));
/* Search the second number */
i = j + 1;
while (i < string.length() && !Character.isDigit(string.charAt(i))) i++;
j = i;
while (j < string.length() && Character.isDigit(string.charAt(j))) j++;
int secondCoordinate = Integer.parseInt(string.substring(i, j));

Java String Error Out Of Bounds

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()){

Input function get wrong value after recall in Java?

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.

StringIndexOutOfBoundsException Error

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!

Categories

Resources