This is my demo.jsp code ,here i'm writing code as follow,result showing as No line found exception where as i executed the code in java class working fine.How can i execute the revers e of string in jsp page?
Scanner sc = new Scanner(System.in);
System.out.println("Enter String :");
String n = sc.nextLine();
String rev = "";
int len = n.length();
for (int i = len - 1; i >= 0; i--) {
rev = rev + n.charAt(i);
}
out.println("Reverse of Given String is :");
out.println("" + rev);
Your current code works without errors . i guess the problem is you are passing the empty string as the input to nextLine method,
Try passing the values like this ,
Scanner sc = new Scanner(System.in);
System.out.println("Enter String :");
String n = sc.nextLine();
String rev = "value";
int len = n.length();
for (int i = len - 1; i >= 0; i--) {
rev = rev + n.charAt(i);
}
out.println("Reverse of Given String is :");
out.println("" + rev)
Hope this helps !!
The above code is pure Java code, not a valid JSP code. If we split what the above code does, it
Prompt for user input.
Perform the reverse on user entered string.
Print the result string.
System.in and Scanner cannot be used to read user input from a JSP page. Fundamentally the user interaction results in communication between the client (browser) and the server (like Tomcat).
In simple the below code is what makes your code a JSP.
Note : The jsp file name and the value of form action must be same.
<body>
<form action="rev.jsp">
<!-- 1. Prompt for user input -->
Enter Text : <input type="text" name="myText"/>
<input type="submit" value="Submit Text"/>
<br/>
<%
// 2. Perform the reverse on user entered string.
String rev = "";
String n = request.getParameter("myText"); // read user entered value in text box.
if(n != null) { // if myText is entered
int len = n.length();
for (int i = len - 1; i >= 0; i--) {
rev = rev + n.charAt(i);
}
// 3. Print the result string.
out.println("Reverse of Given String is :");
out.println("" + rev);
}
%>
</form>
</body>
If you want to open already existing function, You can use following,
String reverse = new StringBuffer(words).reverse().toString();
Refer THIS
Related
import java.util.Scanner;
class Palindrome_string
{
public static void main()
{
System.out.println("\f");
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string");
String a = sc.nextLine();
int b = a.length();
String rev = "";
for (int i = b - 1; i >= 0; i--)
{
char c = a.charAt(i);
rev = rev + c;
}
System.out.println("Original word "+a);
System.out.println("Reversed word "+rev);
a = a.toLowerCase();
rev = rev.toLowerCase();
if (a == rev)
{
System.out.println("It is a palindrome");
}
else
{
System.out.println("It is not a palindrome");
}
sc.close();
}
}
The program compiles properly. Still, when running the program, the message which tells if it is a palindrome prints incorrectly. What changes do I make? Here is a picture of the output. Even though the word 'level' (which is a palindrome) has been inputted, it shows that it isn't a palindrome. What changes should I make? output pic
You should not use == to compare two strings because it compares the reference of the string, i.e. whether they are the same object or not.
Use .equals() instead. It tests for value equality. So in your case:
if (a.equals(rev))
{
System.out.println("It is a palindrome");
}
Also try not to use single-letter variable names except for index variables when iterating over a list etc. It's bad practice.
I am trying to get a valid word from a set of scrabbled letters but all inputs (invalid ones,numbers included) are accepted by my code and checked against a list of words directly. How can i check the inputs against the displayed scrabbled letters so that only words containing letters from the scrabbled ones are accepted before checking the record?
import comp102x.IO; //a library from an edx course(COMP 102x)
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import javax.swing.JOptionPane;
import java.util.Random;
public class FormWords {
public void searchWord() throws IOException
{
Random random = new Random();
String [] randAlphs = {"o","b","e","k","a","i","c","d","f","g","h","k","u"};
int r = random.nextInt(randAlphs.length);
int a = random.nextInt(randAlphs.length);
int n = random.nextInt(randAlphs.length);
int d = random.nextInt(randAlphs.length);
int o = random.nextInt(randAlphs.length);
int m = random.nextInt(randAlphs.length);
int w = random.nextInt(randAlphs.length);
int i = random.nextInt(randAlphs.length);
int s = random.nextInt(randAlphs.length);
//prompt's user for input
String answer = JOptionPane.showInputDialog("form words with the following: " + randAlphs[r]+ randAlphs[a]+ randAlphs[n]+ randAlphs[d]+ randAlphs[o]+ randAlphs[m]+ randAlphs[w]+ randAlphs[s]);
/*searches the record to check if input exists
*/
boolean exist = searchFromRecord("record.txt", answer);
if (exist)
{
JOptionPane.showMessageDialog(null, "Congratulation!The word \"" + answer + "\" is a valid English word.");
}
else
{
// System.out.println("Sorry b ut the word \"" + answer + "\" is not a valid English word.");
JOptionPane.showMessageDialog(null, "Sorry but the word \"" + answer + "\" is not a valid English word.");
}
}
/**
* Searches the record and returns if a specified word is in the record.
*
* #param recordName The name of the record text file.
* #param word The word to be searched.
* #return true if the word presents in the record, false otherwise.
*/
private boolean searchFromRecord(String recordName, String word) throws IOException
{
// Please write your code after this line
File inputFile = new File("record.txt");
Scanner input = new Scanner(inputFile);
while(input.hasNextLine()){
if(word.equalsIgnoreCase(input.nextLine())){
return true;
}
}
return false;
}
}
Before your "prompt's user for input" code. You can use and HashSet in java and add all the letter into de HashSet. Code snippet like this:
Set<String> scrabbledLettersSet = new HashSet<String>();
scrabbledLettersSet.add(randAlphs[a]);
scrabbledLettersSet.add(randAlphs[n]);
scrabbledLettersSet.add(randAlphs[d]);
scrabbledLettersSet.add(randAlphs[o]);
scrabbledLettersSet.add(randAlphs[m]);
scrabbledLettersSet.add(randAlphs[w]);
scrabbledLettersSet.add(randAlphs[i]);
scrabbledLettersSet.add(randAlphs[s]);
Then before you do searchFromRecord method, you can use the set to check whether you input is valid or not. Code snippet is like this:
bool containsScrabbledLetters = false;
for(int i = 0 ; i < answer.length() ; ++ i) {
if (scrabbledLettersSet.contains(answer.substring(i, i + 1))) {
containsScrabbledLetters = true;
break;
}
}
boolean exist = false;
if (containsScrabbledLetters)
exist = searchFromRecord("record.txt", answer);
The above code means that if at least one letter in input string is the scrabbled letter, the input is OK, If you means all letters int the input string must exist in the scrabbled letters, you can use the following code:
bool containsScrabbledLetters = true;
for(int i = 0 ; i < answer.length() ; ++ i) {
if (!scrabbledLettersSet.contains(answer.substring(i, i + 1))) {
containsScrabbledLetters = false;
break;
}
}
boolean exist = false;
if (containsScrabbledLetters)
exist = searchFromRecord("record.txt", answer);
I have some code that I have no clue why it isn't working.
The code takes a serial input in the form of "xxx,yyy,zzz", where digits can range from 1 to 3 in each number. Because of an odd quirk in an app, it needs to be read as a char, then converted to a string to be handled. The intention is to split into 3 ints, red green and blue, from "RRR,GGG,BBB".
Now this works fine when I manually define String str (see commented code), but when I go and enter it from the serial console, it doesn't want to work. It seems to be coming from the indexOf(',') part, as while using Serial.print(c1);, I found that when I manually entered a string, it returned an index of the comma, but when I used the serial console, it returned -1 (not found).
And yes, the entered string into the console is in the correct format of "RRR,GGG,BBB", I've confirmed that by printing both phone and str independently.
while (Serial.available() > 0) {
char phone = Serial.read();
String str = String(phone);
//String str = "87,189,183";
int ln = str.length()-1;
int c1 = str.indexOf(','); //first place to cut string
int c2 = str.indexOf(',',c1+1); //second place
red = str.substring(0,c1).toInt();
green = str.substring(c1,c2).toInt();
blue = str.substring(c2,ln).toInt();
Serial.print(red);
Edit: With the Arduino String class, creating a string from a char is returning more than just one character, eleven in fact.
This:
char phone = Serial.read();
String str = String(phone);
will never create a string in str that has more than 1 character, since that's what you say you want.
This is the code for the Arduino's String(char) constructor:
String::String(char c)
{
init();
char buf[2];
buf[0] = c;
buf[1] = 0;
*this = buf;
}
So clearly your code will create a 1-character long string.
Also, beware of using indexes computed on the full string, on substrings later.
I'm try to guess that you are using these serial API http://playground.arduino.cc/Interfacing/CPPWindows.
while (Serial.available() > 0) {
char buf[12];
int len = Serial.ReadData(buf,11);
String str = String(buf);
//String str = "87,189,183";
int ln = str.length()-1;
int c1 = str.indexOf(','); //first place to cut string
int c2 = str.indexOf(',',c1+1); //second place
red = str.substring(0,c1).toInt();
green = str.substring(c1,c2).toInt();
blue = str.substring(c2,ln).toInt();
Serial.print(red);
If you are using other API like http://arduino.cc/en/Serial/Read you should follow these API where Serial is a Stream and read() return just the first available char.
Code was fixed by using a different function.
while (Serial.available() > 0) {
char phone = Serial.read();
str += phone;
//String str = "87,189,183";
int ln = str.length()-1;
int c1 = str.indexOf(','); //first place to cut string
int c2 = str.indexOf(',',c1+1); //second place
red = str.substring(0,c1).toInt();
green = str.substring(c1,c2).toInt();
blue = str.substring(c2,ln).toInt();
Serial.print(red);
I'm not sure why this works, and why before I was getting a string with more than one character. But it works!
I have set of code which returns me a value "2;#bbbb" where as i want to achieve bbbb.
Below is the code written by me.
SPListItemCollection col = StationaryList.Items;
for (int i = 0; i < col.Count; i++)
{
SPListItem item = col[i];
categoryName=item["QuizCategoryName"].ToString();
}
Please tell me what do i do to achieve this.
Actual Output: "2;#bbbb"
Expected Output: bbbb
string str = categoryName;
string[] result = str.Split('#');
if(result.Length > 1)
Response.Write(result[1]); // your expected output
This is format of lookup field which can be extracted using next sintaxys:
SPFieldLookupValue f = new SPFieldLookupValue("your text here");
string value = f.LookupValue;
This way can be extracted ID which in your case is 2
Andrew
I've got the following method:
public static string ReturnFormat(string input, int maxLength, int decimalPrecision, char formatChar)
{
string[] format = new string[2];
string[] inputs = new string[2];
inputs = input.Split(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator[0]);
if (input.Length > maxLength)
{
int offset = 0;
int counter = 0;
if (inputs[0].Length > maxLength - (1 + decimalPrecision))
{
offset = maxLength - (1 + decimalPrecision);
}
else
offset = inputs[0].Length;
for (int i = 0; i < offset; i++)
{
format[0] += formatChar;
if (counter < decimalPrecision)
{
format[1] += '0';
counter++;
}
}
System.Windows.Forms.MessageBox.Show("{0:" + format[0] + "." + format[1] + "}");
return String.Format(CultureInfo.CurrentCulture, "{0:" + format[0] + "." + format[1] + "}", input);
}
else
return input;
}
Which say I'm using as:
ReturnFormat("12.3456789011243", 10, 2, '#') // format is {0:##.00} // output 12.3456789011243
ReturnFormat("12345678901.1243", 10, 2, '#') // format is {0:#######.00} // output 12345678901.1243
Now my issue is that the input string is not formatted well, still the format strig appears to be ok.
Any ideas of what I'm doing wrong?
Your input is a String not a Double, so it gets formatted like a string: the formatting does not know about decimal places in that case.
You could use Double.Parse() to transform the string into a Double value, but take care of using the right culture.
Another thing, is there a specific reason for not using the more natural format {0:0.00} in both cases? If you really mean to use a placeholder for digits then # is ok, otherwise 0 is best.
Tested solution (beware it truncates and does not round) I needed some time to understand what was actually wanted:
public static string ReturnFormat(string input, int maxLength, int decimalPrecision)
{
if (input.Length <= maxLength)
return input;
Char separator = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator[0];
string[] inputs = input.Split(separator);
// NB: truncating rather than rounding
if (inputs[1].Length > decimalPrecision)
inputs[1] = inputs[1].Substring(0, decimalPrecision);
int digits = (maxLength - decimalPrecision - 1);
// NB: truncating rather than rounding, adding ~ to signalize the
// presence of missing significant digits
if (inputs[0].Length > digits)
inputs[0] = inputs[0].Substring(0, digits-1) + "~";
return inputs[0] + separator + inputs[1];
}