Output for reversing a string does not come as expected - java

Chandu is a bad student. Once his teacher asked him to print the reverse of a given string. He took three hours to solve it. The teacher got agitated at Chandu and asked you the same question. Can you solve it?
Input
The first line contains an integer T, denoting the number of test cases.
Each test case contains a string S, comprising of only lower case letters.
Output
For each test case, print the reverse of the string S.
Constraints
1 <= T <= 10
1 <= |S| <= 30
Input Sample Output(Plaintext Link)
2
ab ba
aba aba
Time Limit
1 sec(s) for each input file.
Memory Limit
256 MB
Source Limit
1024 KB
MyApproach1
MyApproach2
To reverse a string I used XOR logic to reverse the string.
#Edit
public static void main(String args[] ) throws Exception
{
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
for (int i = 1; i <= T; ++i)
{
String input = sc.next();
int len = input.length();
StringBuilder input1 = new StringBuilder(len);
int end = input.length()-1;
int start = 0;
while (start<end)
{
input1.setCharAt(start,input.charAt(start)^input.charAt(end));
input1.setCharAt(end,input.charAt(end)^input.charAt(start));
input1.setCharAt(start,input.charAt(start)^input.charAt(end));
++start;
--end;
}
System.out.println(input1.toString());
}
}
I am still getting the following error.
How do I correct this?

For approach 1, all you need to do is remove the call to sc.nextLine() and everything will be fine. That's because each line contains a "token" i.e. a word, delimited by whitespace. That's what sc.next() will return. No need to call nextLine() after that.
For your approach 2, you should carefully read the API documentation of StringBuilder. This shows you how to create a String from a StringBuilder, and vice versa. (Whenever I write Java code, I have a browser window with the API documentation for quick reference next to my editor window. It's very useful.)
Edit (after the latest edit to the question):
There is a compilation problem and a runtime problem. First, the XOR operator produces a result of type int, even if its operands are char. So you should put your expression in parentheses and cast it to char. Once you've done that, you'll get a runtime error because you are trying to index an element of a StringBuilder which does not yet exist. When you created the StringBuilder like this:
StringBuilder input1=new StringBuilder(len);
len is the initial capacity. The value of the StringBuilder instance is initially "". You then call setCharAt() but the current size of the StringBuilder is 0, so you get an index-out-of-bounds exception. You need to initialise the StringBuilder with the string itself:
StringBuilder input1=new StringBuilder(input);
Now you won't get an exception, but you'll get the wrong answer. That's because of a problem with your XOR logic.

After
sc.nextInt();
write
sc.nextLine();
before starting first loop.
For the two lines of your code
String s1 = sc.next();
sc.nextLine();
write just
String s1 = sc.nextLine();
The next() function gives you characters before a space while next line gives you whole line.
It'll work Fine.

Related

Why am I not getting the correct output in ques of printing even and odd index character seperatly?

enter link description here
This is the link to the question. I have written this code in java but I am not getting the correct output.Why?
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for(int i=0; i<n; i++)
{
String name = sc.nextLine();
String even="";
String odd ="";
for(int j=0; j<name.length(); j++)
{
if(j%2==0)
even=even+String.valueOf(name.charAt(j));
else
odd=odd+String.valueOf(name.charAt(j));
}
System.out.println(even+" "+odd);
This is the error I am getting.
Input (stdin)
2
Hacker
Rank
Your Output (stdout)
// a blank space here.
Hce akr
Expected Output
Hce akr
Rn ak
Your int n = sc.nextInt(); consumes the integer that's input (2), but there is a still a newline.
When your loop goes through the first time, and you call String name = sc.nextLine();, it will consume that remaining newline (and nothing else). Hence, your blank line.
To get past that, make sure to read in the new line after you read in n
Also, the last entry isn't shown because you likely need a trailing newline (one after "Rank" in your input)
your code is correct but the problem is in your input taking.
if u take this as a input
2
Hacker
Rank
then your excepted output never come as u mentioned in your question.
Now i tell u in brief about where is the problem:---------
int n = sc.nextInt();
here u take integer input 2 but you delare only one string type variable.u must declare 2string typr variable if u choose 2.
otherwise only 1 tring willl be handled .
Hacker
Rank
thatswhy u take 2 string variable bt according to ur code only hacker will be compiled and give the output.
u declare 2 string variable .

scanner.nextLine() results in an error when user inputs 1 - 2. How do I allow my program to accept this input as 1?

I am attempting to allow a user to input a single number or an unsolved equation as their input. My program is supposed to take user input by assigning Integer.valueOf(scanner.nextLine()) to a variable. When the user inputs 2 - 1, I get an error java.lang.AssertionError:. Is this a limitation of scanner, or am I implementing my code incorrectly? I have attempted to assign the user input to a second variable after the fact in hopes that that would resolve the problem I am having, but am getting the same error. Can someone give me some help?
.nextLine(), as the name kinda gives away, reads one entire line. It returns "2 - 1" as a string. Integer.parseInt() parses integers; it is not a calculator. It can't parse 2 - 1.
This sounds like homework; the homework assignment would then presumably involve you writing a program that can read, in sequence, '2', '-', and '1', read these into multiple variables, and do the subtraction operation.
Scanner is not a great solution to this; if you must use it, you have to mess with the delimiter to ensure you get 2, -, and 1, in that order - out of the box, scanners split on spaces, so the input "2 - 1" would result in 3 tokens, but "2-1" (without the spaces) is one token, not what you want when writing a calculator.
You can loop over the characters of the line until you find a character that is not a digit and just parse the portion you have already processed.
private static int parseIntPart(final String str) {
final int len = str.length();
final StringBuilder sb = new StringBuilder(len);
for (int i = 0; i < len; i++) {
final char c = str.charAt(i);
if (c >= '0' && c <= '9') {
sb.append(c);
} else {
break;
}
}
return Integer.parseInt(sb.toString());
}
public static void main(final String[] args){
Scanner scan = new Scanner(System.in);
int i = parseIntPart(scan.nextLine());
}

what is equivalent to isEmpty() for integers?

Below is the script I have at the moment
import java.util.Arrays;
import java.util.Scanner;
public class SeeWhatTo
{
public static void main(String args[]) {
Scanner scan = new Scanner(System.in); //define scan
int a = scan.nextInt();
int sum =0;
while (a>0 )
{
sum = sum +a;
a = scan.nextInt();
}
System.out.println(sum); //print out the sum
}
}
Currently, it stores an input value in a and then adds it to sum and once a negative or zero is given as an input, it suspends itself and outputs the sum.
I was wondering if there's an integer equivalent of isEmpty so that i can do while (! a.isEmpty() ) so when there's no input but an enter, then it would stop and prints out the sum.
A natural followup from that would be, is there a way to assign an input integer to a and check if it is empty or not at the same time in the while condition as in while ( ! (a=scan.nextInt()).isEmpty() )
Scanner can do 2 things:
Read line-by-line (nextLine).
Read token-by-token (next or e.g. nextInt).
These are really two different functionalities of Scanner, and if you're reading tokens then your Scanner basically doesn't know about empty lines.
If you call nextInt, Scanner does two things:
Finds the next token (default: delimited by any whitespace).
Tries to turn it in to an int.
The tokenizing behavior is an important feature of Scanner. If you enter 1 2\n and call nextInt twice, you get 1 and 2. However, if you enter an empty line, the tokenizing Scanner just skips it as whitespace and keeps looking for another token.
So the straightforward answer is "no": you can never get an "empty" int from a call to nextInt in a simply way and still retain the token-by-token behavior. (That's beyond the fact that a primitive variable in Java can't be "empty".)
One easy way to do what you're asking is to use line-by-line reading instead and call parseInt yourself:
Scanner systemIn = new Scanner(System.in);
int sum = 0;
String line;
while (!(line = systemIn.nextLine()).isEmpty()) {
sum += Integer.parseInt(line);
}
But you lose the tokenizing behavior. Now, if you enter 1 2\n, an exception is thrown because nextLine finds 1 2.
You can still read token-by-token with nextInt, but it's more complicated, using a second Scanner:
Scanner systemIn = new Scanner(System.in);
int sum = 0;
String nextLine;
while (!(nextLine = systemIn.nextLine()).isEmpty()) {
Scanner theInts = new Scanner(nextLine);
while (theInts.hasNextInt()) {
sum += theInts.nextInt();
}
}
Here, we can enter 1 2\n, get 1 2 as our next line, then ask the second Scanner to tokenize it.
So yes, you can program the functionality you're looking for, but not in an easy way, because Scanner is more complicated.
edit
Possibly another way is to use a delimiter on the line separator:
// use System.getProperty("line.separator") in 1.6
Scanner systemIn = new Scanner(System.in).useDelimiter(System.lineSeparator());
int sum = 0;
while (systemIn.hasNextInt()) {
sum += systemIn.nextInt();
}
Now, nextInt tokenizes the same way as nextLine. This will break the loop for any input that's not an int, including empty tokens. (Empty tokens aren't possible with the default delimiter.) I'm never really sure if people actually expect Scanner's default delimiting to work the way it does or not. It's possible creating a Scanner in this way makes it behave closer to what people seem to expect for reading the console, just line-by-line.
There isn't an equivalent in the sense that you describe, since String is a variable-length collection of characters, and having zero characters is still a valid String. One integer cannot contain zero integers, since by definition, it is already an integer.
However, your problem revolves around how Scanner works, rather than how int works.
Take a look at scan.hasNextInt(), which returns true if there is an int to read, and false otherwise. This may give you what you want, using something like:
Scanner scan = new Scanner(System.in);
int sum = 0;
while(scan.hasNextInt())
{
int a = scan.nextInt();
sum = sum + a;
}
System.out.println(sum);

Array adds 0 as the first element instead of my input [java]

I've been writing this program to count the vowels in string/a line of strings. Now, I've got the whole program worked out and it does correctly output the number of vowels for all inputs, but the problem is that the first input of the array is always 0 / nonexistant for some reason.
I'll give you an example and the code here, it's kind of hard to explain:
Scanner sc = new Scanner(System.in);
int numberOfEntries = sc.nextInt() //this would be the number of lines of strings
String[] array = new String[numberOfEntries];
int k = 0;
while(sc.hasNext() && k < numberOfEntries){
array[k] = sc.nextLine();
k++;
}
So this is the part of the code that is relevant to the problem, the rest of it is fine. For some reason, when I input the following lines:
5
abcd
efgh
ijkl
mnop
qrst
The output I will get if I outprint the array is this:
[, abcd, efgh, ijkl, mnop]
I've tried using just the
for(int i = 0; i < array.length; i++){
array[i] = sc.nextLine();
}
thinking that it might solve the issue but nothing changed. I am out of ideas now, though I am sure I just made some silly little error somewhere and I just don't see it.
Kind regards, George
You get the empty line because of the '\n' that sits in the buffer after you call nextInt(). You press Enter after typing in your integer. Scanner consumes the integer in the call of nextInt(), but it does not touch '\n' that follows.
To fix this problem, call nextLine after reading your int, and discard the result:
int numberOfEntries = sc.nextInt();
sc.nextLine(); // Throw away the '\n' after the int
The statement int numberOfEntries = sc.nextInt(); reads the number, leaving the next character (a newline) as the next character to be read.
The first call to sc.nextLine() see this newline and recognizes it as the end on an (empty) line. For your sample input, this causes the call to return an empty string.
The solution is to add an extra call to sc.nextLine() after the sc.nextInt() to consume (and then discard) any characters after the last digit up to the end of the line.
(Actually ... this is a fairly common beginner's mistake with the Scanner API.)
Thats because the Scanner.nextInt() method does not read the last newline character of your input, and thus that newline is consumed in the next call to Scanner.nextLine().

Space Replacement for Float/Int/Double

I am working on a class assignment this morning and I want to try and solve a problem I have noticed in all of my team mates programs so far; the fact that spaces in an int/float/double cause Java to freak out.
To solve this issue I had a very crazy idea but it does work under certain circumstances. However the problem is that is does not always work and I cannot figure out why. Here is my "main" method:
import java.util.Scanner; //needed for scanner class
public class Test2
{
public static void main(String[] args)
{
BugChecking bc = new BugChecking();
String i;
double i2 = 0;
Scanner in = new Scanner(System.in);
System.out.println("Please enter a positive integer");
while (i2 <= 0.0)
{
i = in.nextLine();
i = bc.deleteSpaces(i);
//cast back to float
i2 = Double.parseDouble(i);
if (i2 <= 0.0)
{
System.out.println("Please enter a number greater than 0.");
}
}
in.close();
System.out.println(i2);
}
}
So here is the class, note that I am working with floats but I made it so that it can be used for any type so long as it can be cast to a string:
public class BugChecking
{
BugChecking()
{
}
public String deleteSpaces(String s)
{
//convert string into a char array
char[] cArray = s.toCharArray();
//now use for loop to find and remove spaces
for (i3 = 0; i3 < cArray.length; i3++)
{
if ((Character.isWhitespace(cArray[i3])) && (i3 != cArray.length)) //If current element contains a space remove it via overwrite
{
for (i4 = i3; i4 < cArray.length-1;i4++)
{
//move array elements over by one element
storage1 = cArray[i4+1];
cArray[i4] = storage1;
}
}
}
s = new String(cArray);
return s;
}
int i3; //for iteration
int i4; //for iteration
char storage1; //for storage
}
Now, the goal is to remove spaces from the array in order to fix the problem stated at the beginning of the post and from what I can tell this code should achieve that and it does, but only when the first character of an input is the space.
For example, if I input " 2.0332" the output is "2.0332".
However if I input "2.03 445 " the output is "2.03" and the rest gets lost somewhere.
This second example is what I am trying to figure out how to fix.
EDIT:
David's suggestion below was able to fix the problem. Bypassed sending an int. Send it directly as a string then convert (I always heard this described as casting) to desired variable type. Corrected code put in place above in the Main method.
A little side note, if you plan on using this even though replace is much easier, be sure to add an && check to the if statement in deleteSpaces to make sure that the if statement only executes if you are not on the final array element of cArray. If you pass the last element value via i3 to the next for loop which sets i4 to the value of i3 it will trigger an OutOfBounds error I think since it will only check up to the last element - 1.
If you'd like to get rid of all white spaces inbetween a String use replaceAll(String regex,String replacement) or replace(char oldChar, char newChar):
String sBefore = "2.03 445 ";
String sAfter = sBefore.replaceAll("\\s+", "");//replace white space and tabs
//String sAfter = sBefore.replace(' ', '');//replace white space only
double i = 0;
try {
i = Double.parseDouble(sAfter);//parse to integer
} catch (NumberFormatException nfe) {
nfe.printStackTrace();
}
System.out.println(i);//2.03445
UPDATE:
Looking at your code snippet the problem might be that you read it directly as a float/int/double (thus entering a whitespace stops the nextFloat()) rather read the input as a String using nextLine(), delete the white spaces then attempt to convert it to the appropriate format.
This seems to work fine for me:
public static void main(String[] args) {
//bugChecking bc = new bugChecking();
float i = 0.0f;
String tmp = "";
Scanner in = new Scanner(System.in);
System.out.println("Please enter a positive integer");
while (true) {
tmp = in.nextLine();//read line
tmp = tmp.replaceAll("\\s+", "");//get rid of spaces
if (tmp.isEmpty()) {//wrong input
System.err.println("Please enter a number greater than 0.");
} else {//correct input
try{//attempt to convert sring to float
i = new Float(tmp);
}catch(NumberFormatException nfe) {
System.err.println(nfe.getMessage());
}
System.out.println(i);
break;//got correct input halt loop
}
}
in.close();
}
EDIT:
as a side note please start all class names with a capital letter i.e bugChecking class should be BugChecking the same applies for test2 class it should be Test2
String objects have methods on them that allow you to do this kind of thing. The one you want in particular is String.replace. This pretty much does what you're trying to do for you.
String input = " 2.03 445 ";
input = input.replace(" ", ""); // "2.03445"
You could also use regular expressions to replace more than just spaces. For example, to get rid of everything that isn't a digit or a period:
String input = "123,232 . 03 445 ";
input = input.replaceAll("[^\\d.]", ""); // "123232.03445"
This will replace any non-digit, non-period character so that you're left with only those characters in the input. See the javadocs for Pattern to learn a bit about regular expressions, or search for one of the many tutorials available online.
Edit: One other remark, String.trim will remove all whitespace from the beginning and end of your string to turn " 2.0332" into "2.0332":
String input = " 2.0332 ";
input = input.trim(); // "2.0332"
Edit 2: With your update, I see the problem now. Scanner.nextFloat is what's breaking on the space. If you change your code to use Scanner.nextLine like so:
while (i <= 0) {
String input = in.nextLine();
input = input.replaceAll("[^\\d.]", "");
float i = Float.parseFloat(input);
if (i <= 0.0f) {
System.out.println("Please enter a number greater than 0.");
}
System.out.println(i);
}
That code will properly accept you entering things like "123,232 . 03 445". Use any of the solutions in place of my replaceAll and it will work.
Scanner.nextFloat will split your input automatically based on whitespace. Scanner can take a delimiter when you construct it (for example, new Scanner(System.in, ",./ ") will delimit on ,, ., /, and )" The default constructor, new Scanner(System.in), automatically delimits based on whitespace.
I guess you're using the first argument from you main method. If you main method looks somehow like this:
public static void main(String[] args){
System.out.println(deleteSpaces(args[0]);
}
Your problem is, that spaces separate the arguments that get handed to your main method. So running you class like this:
java MyNumberConverter 22.2 33
The first argument arg[0] is "22.2" and the second arg[1] "33"
But like other have suggested, String.replace is a better way of doing this anyway.

Categories

Resources