can javascript accept a string with length 27601? - javascript

I have a webmethod which will return an object with strings(i.e)str is object and str(0) would be string. str(0)'s length would be 27601. likewise all other array members having the same length.(i.e) str(1)'s length is 27601 also str(2),str(3)......
my webmethod return the exact object. but on the client side javascript doesn't accept the value it immediately fire the error method.
sample code is,
PageMethods.paging("","",pospara,"position_select","stored Procedure",function sucMulti(result){
alert(result);
});
web method is
<WebMethod()> _
<ScriptMethod()> _
Public Shared Function paging(ByVal query As String, ByVal tbl As String, ByVal para() As Object, ByVal spname As String, ByVal cmdtype As String) As Object()
Dim dsrt As New DataSet, dbacc As New dataaccess
If cmdtype = "stored Procedure" Then
dsrt = dbacc.retds1(spname, conn, para)
Else
dsrt = dbacc.retds(query, tbl, conn)
End If
'here dsrt will have 19 rows. so i split them by 8.
Dim no As Integer
Dim rows As Integer = 8
Dim r As Integer
no = Floor(dsrt.Tables(0).Rows.Count / rows)
If dsrt.Tables(0).Rows.Count < rows Then
r = 0
Else
r = dsrt.Tables(0).Rows.Count Mod rows
End If
Dim start As Integer = 0
Dim last As Integer = 7
Dim str(0) As Object
Dim dv As New DataView
dv = dsrt.Tables(0).DefaultView
If r <> 0 Then
no += 1
End If
If no >= 1 Then
ReDim str(no - 1)
For i As Integer = 1 To no
Dim ds As New DataSet
Dim dt As New DataTable
dt = dsrt.Tables(0).Clone
dt.Rows.Clear()
For j As Integer = start To last
dt.ImportRow(dsrt.Tables(0).Rows(j))
Next
start = (rows * i)
If r <> 0 And i = no - 1 Then
last = last + r
Else
last = start + 7
End If
ds.Tables.Add(dt)
str(i - 1) = ds.GetXml
Next
Else
str(0) = dsrt.GetXml
End If
Dim len As Integer = str(0).ToString.Length
Return str
End Function
everything goes fine . str will contain 4 rows, each row would have a string with 27601 length. but javascript doesn't alert the result. why?

I found a solution that to increase the jason max length by the following.
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="5000"/>
</webServices>
</scripting>
I put the above code inside the tag of web Config file.It works but it gives tooltip error message on the first tag. any suggestions to correct it?
the error message is,
"the element 'configuration' in namespace 'http://schemas.microsoft.com/.NetConfiguration/v2.0' has invalid child element 'system.we.extensions' in namespace 'http://schemas.microsoft.com/.NetConfiguration/v2.0'. List of possible elements expected: 'system.net' in namespace 'http://schemas.microsoft.com/.NetConfiguration/v2.0'"

Related

Classic ASP error on function Base64_HMACSHA1

I have a function Base64_HMACSHA1 and am getting the error Expected ')'. The full code is:
Public Function Base64_HMACSHA1(ByVal sTextToHash As String, ByVal sSharedSecretKey As String)
Dim asc As Object, enc As Object
Dim TextToHash() As Byte
Dim SharedSecretKey() As Byte
Set asc = CreateObject("System.Text.UTF8Encoding")
Set enc = CreateObject("System.Security.Cryptography.HMACSHA1")
TextToHash = asc.Getbytes_4(sTextToHash)
SharedSecretKey = asc.Getbytes_4(sSharedSecretKey)
enc.Key = SharedSecretKey
Dim bytes() As Byte
bytes = enc.ComputeHash_2((TextToHash))
Base64_HMACSHA1 = EncodeBase64(bytes)
Set asc = Nothing
Set enc = Nothing
End Function
Private Function EncodeBase64(ByRef arrData() As Byte) As String
Dim objXML As MSXML2.DOMDocument
Dim objNode As MSXML2.IXMLDOMElement
Set objXML = New MSXML2.DOMDocument
' byte array to base64
Set objNode = objXML.createElement("b64")
objNode.DataType = "bin.base64"
objNode.nodeTypedValue = arrData
EncodeBase64 = objNode.Text
Set objNode = Nothing
Set objXML = Nothing
End Function
I've tried adding an ) in multiple places but I still get an error. The error message is for Line: 84, Column:51, which is this line: Public Function Base64_HMACSHA1(ByVal sTextToHash As String, ByVal sSharedSecretKey As String)
The code for the url is:
Dim objOAuth : Set objOAuth = New cLibOAuth
objOAuth.ConsumerKey = "0b57d617-7a92-4504-a5e1-25273e3b0384"
objOAuth.ConsumerSecret = "joSPols5B8uyKQqYzkk8uiwHrJ7nq3VwravLnTdJTFXMqSAq0KSBvPVoLETAmUiS"
objOAuth.EndPoint = "https://login.windstream.com/as/token.oauth2"
objOAuth.RequestMethod = OAUTH_REQUEST_METHOD_POST
objOAuth.TimeoutURL = "authenticate.asp"
'objOAuth.Parameters.Add "username", Request.Cookies("username")
'objOAuth.Parameters.Add "password", Request.Cookies("password")
objOAuth.Parameters.Add "oauth_callback", "callback.asp"
objOAuth.Send()
Dim strResponse : strResponse = _
objOAuth.Get_ResponseValue(access_token)

Unable to catch web page content with an HTML object from VBA

Im using this URL https://www.morningstar.com/stocks/xtks/1407/dividends
and the table with the upcoming dividends are displayed on my browser
I inspect the page and try to catch the content of the table
I tried this code :
Dim html As New htmlDocument
Dim HTTP As Object, Elem As Object, Quote As Object
Dim iTicker As Integer, nTicker As Integer, BBG_Ticker As String, DES As String, TYP As String, MKT_STATUS As String
Dim vHeader As Variant, vData As Variant, i As Integer, j As Integer, t As Integer, k As Integer, nFields As Integer, x As Integer
Dim n As Integer
Set HTTP = CreateObject("MSXML2.XMLHTTP")
ReDim vWebPxLast(0)
With HTTP
.Open "GET", URL, True
.Send
End With
While HTTP.ReadyState <> 4
DoEvents
Wend
html.Body.innerHTML = HTTP.responseText
Crash HTTP.responseText
If HTTP.Status = 200 Then
Set Elem = html.getElementsByClassName("dividends-recent")
but the Elem object is empty
I used selenium with chrome and it worked

The use of pageNum property in Acrobat Type Library 10.0 JSObject returns RunTime error 438

I need to get the page number in order to extract text from that specific page in a .PDF document. I am using Excel VBA function that makes use of the JSObject from the Acrobat Type Library 10.0
Here is the code snippet and the code hicks up on when I am trying to reference the pageNum property from Doc object. I am trying to avoid the AV Layer and use the PD Layer only, so my macro runs in the background only and doesn't invoke Acrobat Application.
Function getTextFromPDF_JS(ByVal strFilename As String) As String
Dim pdDoc As New AcroPDDoc
Dim pdfPage As Acrobat.AcroPDPage
Dim pdfBookmark As Acrobat.AcroPDBookmark
Dim jso As Object
Dim BookMarkRoot As Object
Dim vBookmark As Variant
Dim objSelection As AcroPDTextSelect
Dim objHighlight As AcroHiliteList
Dim currPage As Integer
Dim strText As String
Dim BM_flag As Boolean
Dim count As Integer
Dim word As Variant
strText = ""
If (pdDoc.Open(strFilename)) Then
Set jso = pdDoc.GetJSObject
Set BookMarkRoot = jso.BookMarkRoot
vBookmark = jso.BookMarkRoot.Children
'Add a function call to see if a particular bookmark exists within the .PDF
Set pdfBookmark = CreateObject("AcroExch.PDBookmark")
BM_flag = pdfBookmark.GetByTitle(pdDoc, "Title Page")
If (BM_flag) Then
For i = 0 To UBound(vBookmark)
If vBookmark(i).Name = "Title Page" Then
vBookmark(i).Execute
jso.pageNum
Set pdfPage = pdDoc.AcquirePage(pageNum)
Set objHighlight = New AcroHiliteList
objHighlight.Add 0, 10000 ' Adjust this up if it's not getting all the text on the page
Set objSelection = pdfPage.CreatePageHilite(objHighlight)
If Not objSelection Is Nothing Then
For tCount = 0 To objSelection.GetNumText - 1
strText = strText & objSelection.GetText(tCount)
Next tCount
End If
Exit For
End If
pdDoc.Close
End If
End If
getTextFromPDF_JS = strText
End Function
jso.pageNum = 0; set a page number
pageNo = jso.pageNum; get a page number
edit: 3.3.19
Mmmh, it seems you have to work with AVDoc in order to get the current actual page via jso.pageNum . Also if you work with AVdoc the Acobat window stay hidden in the background. Example:
strFilename = "d:\Test2.pdf"
set avDoc = CreateObject("AcroExch.AVDoc")
If (avDoc.Open(strFilename,"")) Then
Set pdDoc = avDoc.getPDDoc()
Set jso = pdDoc.GetJSObject
pageNo = jso.pageNum
msgbox(pageNo)
end if

PhoneBookEntry Driver Program error [duplicate]

I am using the Scanner methods nextInt() and nextLine() for reading input.
It looks like this:
System.out.println("Enter numerical value");
int option;
option = input.nextInt(); // Read numerical value from input
System.out.println("Enter 1st string");
String string1 = input.nextLine(); // Read 1st string (this is skipped)
System.out.println("Enter 2nd string");
String string2 = input.nextLine(); // Read 2nd string (this appears right after reading numerical value)
The problem is that after entering the numerical value, the first input.nextLine() is skipped and the second input.nextLine() is executed, so that my output looks like this:
Enter numerical value
3 // This is my input
Enter 1st string // The program is supposed to stop here and wait for my input, but is skipped
Enter 2nd string // ...and this line is executed and waits for my input
I tested my application and it looks like the problem lies in using input.nextInt(). If I delete it, then both string1 = input.nextLine() and string2 = input.nextLine() are executed as I want them to be.
That's because the Scanner.nextInt method does not read the newline character in your input created by hitting "Enter," and so the call to Scanner.nextLine returns after reading that newline.
You will encounter the similar behaviour when you use Scanner.nextLine after Scanner.next() or any Scanner.nextFoo method (except nextLine itself).
Workaround:
Either put a Scanner.nextLine call after each Scanner.nextInt or Scanner.nextFoo to consume rest of that line including newline
int option = input.nextInt();
input.nextLine(); // Consume newline left-over
String str1 = input.nextLine();
Or, even better, read the input through Scanner.nextLine and convert your input to the proper format you need. For example, you may convert to an integer using Integer.parseInt(String) method.
int option = 0;
try {
option = Integer.parseInt(input.nextLine());
} catch (NumberFormatException e) {
e.printStackTrace();
}
String str1 = input.nextLine();
The problem is with the input.nextInt() method; it only reads the int value. So when you continue reading with input.nextLine() you receive the "\n" Enter key. So to skip this you have to add the input.nextLine().
Try it like this, instead:
System.out.print("Insert a number: ");
int number = input.nextInt();
input.nextLine(); // This line you have to add (It consumes the \n character)
System.out.print("Text1: ");
String text1 = input.nextLine();
System.out.print("Text2: ");
String text2 = input.nextLine();
It's because when you enter a number then press Enter, input.nextInt() consumes only the number, not the "end of line". When input.nextLine() executes, it consumes the "end of line" still in the buffer from the first input.
Instead, use input.nextLine() immediately after input.nextInt()
There seem to be many questions about this issue with java.util.Scanner. I think a more readable/idiomatic solution would be to call scanner.skip("[\r\n]+") to drop any newline characters after calling nextInt().
EDIT: as #PatrickParker noted below, this will cause an infinite loop if user inputs any whitespace after the number. See their answer for a better pattern to use with skip: https://stackoverflow.com/a/42471816/143585
TL;DR
nextLine() is safe to call when (a) it is first reading instruction, (b) previous reading instruction was also nextLine().
If you are not sure that either of above is true you can use scanner.skip("\\R?") before calling scanner.nextLine() since calls like next() nextInt() will leave potential line separator - created by return key which will affect result of nextLine(). The .skip("\\R?") will let us consume this unnecessary line separator.
skip uses regex where
\R represents line separators
? will make \R optional - which will prevent skip method from:
waiting for matching sequence
in case of reaching end of still opened source of data like System.in, input stream from socket, etc.
throwing java.util.NoSuchElementException in case of
terminated/closed source of data,
or when existing data doesn't match what we want to skip
Things you need to know:
text which represents few lines also contains non-printable characters between lines (we call them line separators) like
carriage return (CR - in String literals represented as "\r")
line feed (LF - in String literals represented as "\n")
when you are reading data from the console, it allows the user to type his response and when he is done he needs to somehow confirm that fact. To do so, the user is required to press "enter"/"return" key on the keyboard.
What is important is that this key beside ensuring placing user data to standard input (represented by System.in which is read by Scanner) also sends OS dependant line separators (like for Windows \r\n) after it.
So when you are asking the user for value like age, and user types 42 and presses enter, standard input will contain "42\r\n".
Problem
Scanner#nextInt (and other Scanner#nextType methods) doesn't allow Scanner to consume these line separators. It will read them from System.in (how else Scanner would know that there are no more digits from the user which represent age value than facing whitespace?) which will remove them from standard input, but it will also cache those line separators internally. What we need to remember, is that all of the Scanner methods are always scanning starting from the cached text.
Now Scanner#nextLine() simply collects and returns all characters until it finds line separators (or end of stream). But since line separators after reading the number from the console are found immediately in Scanner's cache, it returns empty String, meaning that Scanner was not able to find any character before those line separators (or end of stream).
BTW nextLine also consumes those line separators.
Solution
So when you want to ask for number and then for entire line while avoiding that empty string as result of nextLine, either
consume line separator left by nextInt from Scanners cache by
calling nextLine,
or IMO more readable way would be by calling skip("\\R") or skip("\r\n|\r|\n") to let Scanner skip part matched by line separator (more info about \R: https://stackoverflow.com/a/31060125)
don't use nextInt (nor next, or any nextTYPE methods) at all. Instead read entire data line-by-line using nextLine and parse numbers from each line (assuming one line contains only one number) to proper type like int via Integer.parseInt.
BTW: Scanner#nextType methods can skip delimiters (by default all whitespaces like tabs, line separators) including those cached by scanner, until they will find next non-delimiter value (token). Thanks to that for input like "42\r\n\r\n321\r\n\r\n\r\nfoobar" code
int num1 = sc.nextInt();
int num2 = sc.nextInt();
String name = sc.next();
will be able to properly assign num1=42 num2=321 name=foobar.
It does that because input.nextInt(); doesn't capture the newline. you could do like the others proposed by adding an input.nextLine(); underneath.
Alternatively you can do it C# style and parse a nextLine to an integer like so:
int number = Integer.parseInt(input.nextLine());
Doing this works just as well, and it saves you a line of code.
Instead of input.nextLine() use input.next(), that should solve the problem.
Modified code:
public static Scanner input = new Scanner(System.in);
public static void main(String[] args)
{
System.out.print("Insert a number: ");
int number = input.nextInt();
System.out.print("Text1: ");
String text1 = input.next();
System.out.print("Text2: ");
String text2 = input.next();
}
If you want to read both strings and ints, a solution is to use two Scanners:
Scanner stringScanner = new Scanner(System.in);
Scanner intScanner = new Scanner(System.in);
intScanner.nextInt();
String s = stringScanner.nextLine(); // unaffected by previous nextInt()
System.out.println(s);
intScanner.close();
stringScanner.close();
In order to avoid the issue, use nextLine(); immediately after nextInt(); as it helps in clearing out the buffer. When you press ENTER the nextInt(); does not capture the new line and hence, skips the Scanner code later.
Scanner scanner = new Scanner(System.in);
int option = scanner.nextInt();
scanner.nextLine(); //clearing the buffer
If you want to scan input fast without getting confused into Scanner class nextLine() method , Use Custom Input Scanner for it .
Code :
class ScanReader {
/**
* #author Nikunj Khokhar
*/
private byte[] buf = new byte[4 * 1024];
private int index;
private BufferedInputStream in;
private int total;
public ScanReader(InputStream inputStream) {
in = new BufferedInputStream(inputStream);
}
private int scan() throws IOException {
if (index >= total) {
index = 0;
total = in.read(buf);
if (total <= 0) return -1;
}
return buf[index++];
}
public char scanChar(){
int c=scan();
while (isWhiteSpace(c))c=scan();
return (char)c;
}
public int scanInt() throws IOException {
int integer = 0;
int n = scan();
while (isWhiteSpace(n)) n = scan();
int neg = 1;
if (n == '-') {
neg = -1;
n = scan();
}
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
integer *= 10;
integer += n - '0';
n = scan();
}
}
return neg * integer;
}
public String scanString() throws IOException {
int c = scan();
while (isWhiteSpace(c)) c = scan();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = scan();
} while (!isWhiteSpace(c));
return res.toString();
}
private boolean isWhiteSpace(int n) {
if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true;
else return false;
}
public long scanLong() throws IOException {
long integer = 0;
int n = scan();
while (isWhiteSpace(n)) n = scan();
int neg = 1;
if (n == '-') {
neg = -1;
n = scan();
}
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
integer *= 10;
integer += n - '0';
n = scan();
}
}
return neg * integer;
}
public void scanLong(long[] A) throws IOException {
for (int i = 0; i < A.length; i++) A[i] = scanLong();
}
public void scanInt(int[] A) throws IOException {
for (int i = 0; i < A.length; i++) A[i] = scanInt();
}
public double scanDouble() throws IOException {
int c = scan();
while (isWhiteSpace(c)) c = scan();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = scan();
}
double res = 0;
while (!isWhiteSpace(c) && c != '.') {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, scanInt());
}
res *= 10;
res += c - '0';
c = scan();
}
if (c == '.') {
c = scan();
double m = 1;
while (!isWhiteSpace(c)) {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, scanInt());
}
m /= 10;
res += (c - '0') * m;
c = scan();
}
}
return res * sgn;
}
}
Advantages :
Scans Input faster than BufferReader
Reduces Time Complexity
Flushes Buffer for every next input
Methods :
scanChar() - scan single character
scanInt() - scan Integer value
scanLong() - scan Long value
scanString() - scan String value
scanDouble() - scan Double value
scanInt(int[] array) - scans complete Array(Integer)
scanLong(long[] array) - scans complete Array(Long)
Usage :
Copy the Given Code below your java code.
Initialise Object for Given Class
ScanReader sc = new ScanReader(System.in);
3. Import necessary Classes :
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
4. Throw IOException from your main method to handle Exception
5. Use Provided Methods.
6. Enjoy
Example :
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
class Main{
public static void main(String... as) throws IOException{
ScanReader sc = new ScanReader(System.in);
int a=sc.scanInt();
System.out.println(a);
}
}
class ScanReader....
sc.nextLine() is better as compared to parsing the input.
Because performance wise it will be good.
I guess I'm pretty late to the party..
As previously stated, calling input.nextLine() after getting your int value will solve your problem. The reason why your code didn't work was because there was nothing else to store from your input (where you inputted the int) into string1. I'll just shed a little more light to the entire topic.
Consider nextLine() as the odd one out among the nextFoo() methods in the Scanner class. Let's take a quick example.. Let's say we have two lines of code like the ones below:
int firstNumber = input.nextInt();
int secondNumber = input.nextInt();
If we input the value below (as a single line of input)
54 234
The value of our firstNumber and secondNumber variable become 54 and 234 respectively. The reason why this works this way is because a new line feed (i.e \n) IS NOT automatically generated when the nextInt() method takes in the values. It simply takes the "next int" and moves on. This is the same for the rest of the nextFoo() methods except nextLine().
nextLine() generates a new line feed immediately after taking a value; this is what #RohitJain means by saying the new line feed is "consumed".
Lastly, the next() method simply takes the nearest String without generating a new line; this makes this the preferential method for taking separate Strings within the same single line.
I hope this helps.. Merry coding!
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int i = scan.nextInt();
scan.nextLine();
double d = scan.nextDouble();
scan.nextLine();
String s = scan.nextLine();
System.out.println("String: " + s);
System.out.println("Double: " + d);
System.out.println("Int: " + i);
}
if I expect a non-empty input
avoids:
–  loss of data if the following input is eaten by an unchecked scan.nextLine() as workaround
–  loss of data due to only partially read lines because scan.nextLine() was replaced by scan.next() (enter: "yippie ya yeah")
–  Exceptions that are thrown when parsing input with Scanner methods (read first, parse afterwards)
public static Function<Scanner,String> scanLine = (scan -> {
String s = scan.nextLine();
return( s.length() == 0 ? scan.nextLine() : s );
});
used in above example:
System.out.println("Enter numerical value");
int option = input.nextInt(); // read numerical value from input
System.out.println("Enter 1st string");
String string1 = scanLine.apply( input ); // read 1st string
System.out.println("Enter 2nd string");
String string2 = scanLine.apply( input ); // read 2nd string
Use 2 scanner objects instead of one
Scanner input = new Scanner(System.in);
System.out.println("Enter numerical value");
int option;
Scanner input2 = new Scanner(System.in);
option = input2.nextInt();
In one of my usecase, I had the scenario of reading a string value preceded by a couple of integer values. I had to use a "for / while loop" to read the values. And none of the above suggestions worked in this case.
Using input.next() instead of input.nextLine() fixed the issue. Hope this might be helpful for those dealing with similar scenario.
As nextXXX() methods don't read newline, except nextLine(). We can skip the newline after reading any non-string value (int in this case) by using scanner.skip() as below:
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
sc.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
System.out.println(x);
double y = sc.nextDouble();
sc.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
System.out.println(y);
char z = sc.next().charAt(0);
sc.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
System.out.println(z);
String hello = sc.nextLine();
System.out.println(hello);
float tt = sc.nextFloat();
sc.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
System.out.println(tt);
Use this code it will fix your problem.
System.out.println("Enter numerical value");
int option;
option = input.nextInt(); // Read numerical value from input
input.nextLine();
System.out.println("Enter 1st string");
String string1 = input.nextLine(); // Read 1st string (this is skipped)
System.out.println("Enter 2nd string");
String string2 = input.nextLine(); // Read 2nd string (this appears right after reading numerical value)
To resolve this problem just make a scan.nextLine(), where scan is an instance of the Scanner object. For example, I am using a simple HackerRank Problem for the explanation.
package com.company;
import java.util.Scanner;
public class hackerrank {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int i = scan.nextInt();
double d = scan.nextDouble();
scan.nextLine(); // This line shall stop the skipping the nextLine()
String s = scan.nextLine();
scan.close();
// Write your code here.
System.out.println("String: " + s);
System.out.println("Double: " + d);
System.out.println("Int: " + i);
}
}
The nextLine() will read enter directly as an empty line without waiting for the text.
Simple solution by adding an extra scanner to consume the empty line:
System.out.println("Enter numerical value");
int option;
option = input.nextInt(); // Read numerical value from input
input.nextLine();
System.out.println("Enter 1st string");
String string1 = input.nextLine(); // Read 1st string (this is skipped)
System.out.println("Enter 2nd string");
String string2 = input.nextLine(); // Read 2nd string (this appears right after reading numerical value)
This is a very basic problem for beginner coders in java. The same problem I also have faced when I started java (Self Taught).
Actually, when we take an input of integer dataType, it reads only integer value and leaves the newLine(\n) character and this line(i.e. leaved new line by integer dynamic input )creates the problem when we try to take a new input.
eg. Like if we take the integer input and then after try to take an String input.
value1=sc.nextInt();
value2=sc.nextLine();
the value2 will auto read the newLine character and will not take the user input.
Solution:
just we need to add one line of code before taking the next user input i.e.
sc.nextLine();
or
value1=sc.nextInt();
sc.nextLine();
value2=sc.nextLine();
Note: don't forget to close the Scanner to prevent memory leak;
Scanner scan = new Scanner(System.in);
int i = scan.nextInt();
scan.nextLine();//to Ignore the rest of the line after (integer input)nextInt()
double d=scan.nextDouble();
scan.nextLine();
String s=scan.nextLine();
scan.close();
System.out.println("String: " + s);
System.out.println("Double: " + d);
System.out.println("Int: " + i);
Why not use a new Scanner for every reading? Like below. With this approach you will not confront your problem.
int i = new Scanner(System.in).nextInt();
The problem is with the input.nextInt() method - it only reads the int value. So when you continue reading with input.nextLine() you receive the "\n" Enter key. So to skip this you have to add the input.nextLine(). Hope this should be clear now.
Try it like that:
System.out.print("Insert a number: ");
int number = input.nextInt();
input.nextLine(); // This line you have to add (It consumes the \n character)
System.out.print("Text1: ");
String text1 = input.nextLine();
System.out.print("Text2: ");
String text2 = input.nextLine();

Getting value from SQL query to textbox

Protected Sub Button3_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button3.Click
Dim cons, query As String
Dim con As OdbcConnection
Dim adpt As OdbcDataAdapter
'Dim num As Integer
cons = "dsn=Courier; UID=Courier; PWD=123;"
con = New OdbcConnection(cons)
con.Open()
query = "select Name from EMPLOYEE where EMPLOYEE_ID=" + DropDownList1.SelectedValue
Dim ds As DataSet
adpt = New OdbcDataAdapter(query, con)
ds = New DataSet
adpt.Fill(ds, "Courier")
' TextBox1.Text = ds
con.Close()
End Sub
I want to display the name of the employee in Textbox whoos ID is specified in query, what can I do for that?
You should use DataRow but to answer your question, try this.
TextBox1.Text = ds.Tables(0).Rows(0)("Name").ToString()
Since you only want one value back you should skip the dataset and adapter altogether.
query = "select Name from EMPLOYEE where EMPLOYEE_ID=" + DropDownList1.SelectedValue
Dim TempName As String = query.ExecuteScalar
TextBox1.Text = TempName
ExecuteScalar returns the first cell of the first row, that's all you need.
You should read about parameters as well.

Categories