I know I can do it as follows:
String s = "Hello";
int maxLength = 10;
System.out.print(getSpaces((maxLength - s.length()) / 2) + s + getSpaces((maxLength - s.length()) / 2));
But I need to do it in a simple way. According to this page: Printf for Java Specification 3.0 (Section 9. flags):
I can center the text using ^ as a flag with printf() like this:
String s = "Hello";
int maxLength = 10;
System.out.printf("%^" + maxLength + "s", s);
But I got this error:
Exception in thread "main" java.util.UnknownFormatConversionException: Conversion = '^'
What is the correct way to use ^ flag with printf()?
The format String syntax, including information on specifiers and flags can be found here: java.util.Formatter.
I don't see use of ^ as a flag anywhere in this documentation.
I believe that your specification in the link above isn't for standard Java but rather for a 3rd party library called Lava3 Printf produced by SharkySoft. Please let us know if this is the library you are using, or if you're trying to do this coding with core Java.
Related
Groovy is the preferred scripting in JMeter
We advise using Apache Groovy or any language that supports the Compilable interface of JSR223.
The following code in JSR233 Sampler works in Java but not in Groovy
String a= "0"+"1" +
"2"
+"3";
log.info(a);
I found the reasons for + operator not to work as expected,
but what is the solution is I want to concatenate several variables to a script?
I failed to use answer of using three quotes """The row Id is: ${row.id}..."""
Currently I use Java as script language and use JMeter ${variable} although is also not recommended:
In this case, ensure the script does not use any variable using ${varName} as caching would take only first value of ${varName}
String text ="...<id>${id}</id><id2>${id2}</id2>...";
What's a better approach in groovy in such case?
EDIT:
Try using << but different error where it split to new line
String text ="<id>" <<vars["id1"] << "<id><id2>"
<< vars["id2"] << "<id2>";
Receives an error:
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
Script12.groovy: 2: unexpected token: << # line 2, column 1.
<< vars["id2"] << "<id2>";
Groovy uses the new line character to indicate end of statement except in cases where it knows the next line must extend the current one. Numerous binary operators on the start of the next line are supported. The '+' and '-' operators have binary and unary variants and currently (Groovy versions at least up to 2.5.x) don't support those operators at the start of the next line. You can place the operator on the end of the previous line (as in your first line) or use the line continuation character at the end of the previous line:
String a = "0" + "1" +
"2" \
+ "3"
log.info(a)
Why don't you use :
String text ="<id>" <<vars["id1"] << "<id><id2>" << vars["id2"] << "<id2>";
It works for me
If I had a hashmap to concat like yours, I would try:
def vars = ["id": "value", "id2": "value2", "id3": "value3"]
String text = ""
vars.each { k, v ->
text += "<${k}>${v}</${k}>"
}
println text
This is a Peter Norvig's repl function:
def repl(prompt='lis.py> '):
"A prompt-read-eval-print loop."
while True:
val = eval(parse(raw_input(prompt)))
if val is not None:
print(schemestr(val))
def schemestr(exp):
"Convert a Python object back into a Scheme-readable string."
if isinstance(exp, List):
return '(' + ' '.join(map(schemestr, exp)) + ')'
else:
return str(exp)
Which works:
>>> repl()
lis.py> (define r 10)
lis.py> (* pi (* r r))
314.159265359
lis.py> (if (> (* 11 11) 120) (* 7 6) oops)
42
lis.py>
I'm trying to write program with the same functionality in Java, tried classes from Java docs, but nothing works like that; any idea? Thanks.
A REPL is called REPL because it is a Loop that Reads and Evaluates code and Prints the results. In Lisp, the code is literally:
(LOOP (PRINT (EVAL (READ))))
In an unstructured language, it would be something like:
#loop:
$code ← READ;
$res ← EVAL($code);
PRINT($res);
GOTO #loop;
That's where the name comes from.
In Java, it would be something like:
while (true) {
Code code = read(System.in);
Object res = eval(code);
System.out.println(res);
}
But, there are no methods corresponding to READ or EVAL in Java or the JRE. You will have to write read, eval, and Code yourself. Note that read is essentially a parser for Java, and eval is an interpreter for Java. Both the syntax and the semantics for Java are described in the Java Language Specification, all you have to do is read the JLS and implement those two methods.
C++ beginner here. Wondering what the syntax is for this piece of Java code on restricting user input. Here is an example of a Java code I wrote
while (!in.hasNext("[A-Za-z]+")){}
Where "in" is my scanner variable. This piece of code runs when the input is not a real number, and returns an error message with the option to enter something in again. I haven't been able to find the equivalent of this "range" condition on C++. Any help would be appreciated.
EDIT:
I have tried using the regex function in Dev C++ but it gives me a warning like this:
#ifndef _CXX0X_WARNING_H
#define _CXX0X_WARNING_H 1
#if __cplusplus < 201103L
#error This file requires compiler and library support for the \
ISO C++ 2011 standard. This support is currently experimental, and must be \
enabled with the -std=c++11 or -std=gnu++11 compiler options.
#endif
#endif
Does this mean that I cant use the regex function in Dev C++?
Example:
cin >> inputStr;
if (std::regex_match (inputStr, std::regex("[A-Za-z]+") )) {
// do something, will you ?
}
Note: you will need to include <regex>.
More info: http://www.cplusplus.com/reference/regex/regex_match/
If you wan to loop until you get a real number then you can use:
do
{
cin >> input;
} while(std::regex_match (input, std::regex("[A-Za-z]+")));
You can also use std::stod() to convert a std::string to a double. Doing that will make sure you are getting a valid real number since a number and have e/E in it. You can do that with:
std::string input;
double value;
size_t pos;
do
{
cin >> input;
value = stod(input, &pos);
} while (pos < input.size());
The regular expression is
String regex = "^[\\p{IsHangul}\\p{IsDigit}]+";
And whenever i do
text.matches(regex);
It works fine in my system but not in some of the system.
I am not able to track the issue.
Thank you in advance.
Exception:
Exception in thread "main" java.util.regex.PatternSyntaxException: Unknown character property name {Hangul} near index 13
^[\p{IsHangul}\p{IsDigit}]+
^
at java.util.regex.Pattern.error(Pattern.java:1713)
at java.util.regex.Pattern.charPropertyNodeFor(Pattern.java:2437)
at java.util.regex.Pattern.family(Pattern.java:2412)
at java.util.regex.Pattern.range(Pattern.java:2335)
at java.util.regex.Pattern.clazz(Pattern.java:2268)
at java.util.regex.Pattern.sequence(Pattern.java:1818)
at java.util.regex.Pattern.expr(Pattern.java:1752)
at java.util.regex.Pattern.compile(Pattern.java:1460)
at java.util.regex.Pattern.<init>(Pattern.java:1133)
at java.util.regex.Pattern.compile(Pattern.java:823)
at java.util.regex.Pattern.matches(Pattern.java:928)
at java.lang.String.matches(String.java:2090)
at com.mycompany.helper.ApplicationHelper.main(ApplicationHelper.java:200)
According to Using Regular Expressions in Java:
Java 5 fixes some bugs and adds support for Unicode blocks. ...
Make sure you're using Java 5+ in the server.
It seems that Java version you are using is not able to recognise Hangul as correct script character so you can try to create your own character class which will cover same range as Hongul from newer versions of Java.
From what I see in code in source code of Character.UnicodeScript on Java 8 Hangul refers to Unicode ranges
1100..11FF
302E..302F
3131..318F
3200..321F
3260..327E
A960..A97F
AC00..D7FB
FFA0..FFDF
so maybe try with such pattern
Pattern.compile("^["
+ "\u1100-\u11FF"
+ "\u302E-\u302F"
+ "\u3131-\u318F"
+ "\u3200-\u321F"
+ "\u3260-\u327E"
+ "\uA960-\uA97F"
+ "\uAC00-\uD7FB"
+ "\uFFA0-\uFFDF"
+ "\\p{IsDigit}]+");
I am trying to match a Java version in HKLM\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall by iterating over the subkeys within Uninstall. I am trying to match a regular expression to Java 7 Update 40, but the regex is matching all DisplayName entries. Below is the code:
On Error Resume Next
Const HKEY_LOCAL_MACHINE = &H80000002
Dim oReg
Dim objShell
Set objShell = WScript.CreateObject("WScript.Shell")
Set oReg = GetObject("winmgmts:{impersonationLevel=impersonate}!\.\root\default:StdRegProv")
Dim sPath, aSub, sKey
Set objRegEx = New RegExp
objRegEx.Pattern = "\w{4}\s\d{1}\s\w{6}\s\d+"
objRedEx.IgnoreCase = True
objRegEx.Global = False
sPath = "SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall"
oReg.EnumKey HKEY_LOCAL_MACHINE, sPath, aSub
For Each sKey In aSub
disName = "HKLM" & "\" & sPath & "\" & sKey & "\DisplayName"
unString = "HKLM" & "\" & sPath & "\" & sKey & "\UninstallString"
reDisName = objShell.RegRead(disName)
reUnString = objShell.RegRead(unString)
'Wscript.echo(reDisName)
If objRexEx.Test( reDisName ) Then
Wscript.echo "Match"
End If
'Wscript.echo ObjShell.RegRead(disName)
'Wscript.echo ObjShell.RegRead(unString)
Next
Sorry if the formatting is off, I put a ctrl-k in front of each code line. This is my first time posting here so go easy...
You should start all your scripts with Option Explicit and Dim all your variables. Then you wouldn't need sln's eagle eyes to spot your typo:
Option Explicit
Dim objRegEx : Set objRegEx = New RegExp
objRegEx.Pattern = "\w{4}\s\d{1}\s\w{6}\s\d+"
objRedEx.IgnoreCase = True
output:
cscript 19188400.vbs
...\19188400.vbs(4, 1) Microsoft VBScript runtime error: Variable is undefined: 'objRedEx'
If you insist on using a global On Error Resume Next (a most dangerous mal-practice) then you should disable it until your script is thoroughly debugged. Keeping the OERN in a script known to have even the slightest problem is inviting desaster. Asking for help with code containing a global OERN is futile. So run you program without the OERN and see if the cause for its misbehaviour in't obvious.
Diagnostic output should be as specific as possible. Your WScript.Echo "Match" just shows that the statement is executed; a WScript.Echo "Match", disname would be a bit better. Using .Execute and looking at the Match's details could be more revealing.
The .Pattern should be more specific to. If you look for java updates, anchoring a literal "java" at the start of the string, and asking for "upgrade" instead of "\w{6}" may help to avoid false positives. OTOH, my display names don't look like
Java 7 Update 19
but like
Java(TM) 6 Update 19
and who knows what the next owner of Java will put into the display name.
You seem to have a few typo's
objRedEx.IgnoreCase = True
...
If objRexEx.Test( reDisName ) Then