In java when we take input from console we get a String, even if we want an integer as input we get a input in String format, then we covert it in integer format using several methods, like Integer.parseInt(). Where as C/C++ also take input from console but there we get integer values directly from console we does not require methods to convert them. Then why does java follows such long procedure. **What is the reason behind such an architecture of Java ?
//In java we follow the following process
public static void main(String args[])
{int i = Integer.parseInt( args[0]);// here we get input in String format and then convert it
}
//In C++ we follow the following :
void main()
{int i;
cin>>i;
}
Both C/C++ and Java takes input form Console then why java takes it in String Format and C++ does not ??
Check out java.util.Scanner, it might do what you need:
http://download.oracle.com/javase/6/docs/api/java/util/Scanner.html
Java - If you use the Scanner class you can get the input in the required data type. It's not only String java accepts.
If you take an integer from the console in C, it will require you to atoi() the input.
You always get a string when reading from stdin. In C++ however, the >> operator overload used when writing to an int performs the conversion - so it's just a different way of converting but in both languages it's necessary.
You are right that it's nicer in C++ though since you can use pretty much the same code no matter what data type you have.
Related
Given a string value, how can I display it on the screen in my console? What do I have to write to make that happen?
As an example, this is the code I have so far:
public class Main {
public static void main(String[] args) {
String message = "I am a school student and just started learning Java.";
// What to write next?
}
}
It works, but it obviously does not display the value on the console yet. What do I have to write to show it?
I want it to look something like this:
But all I get is this:
By default, a Java program doesn't print anything. You need to explicitly tell your program to print output. Here are some of the ways that you can do that:
To print a String to standard output:
System.out.print(message);
To print a String followed by a (platform appropriate) line separator:
System.out.println(message);
To print a String to the standard error stream:
System.err.print(message);
To print to the console (e.g. if standard output could have been redirected to a file):
Console console = System.console();
if (console != null) { // Note that in some contexts there
// is not a usable `Console`...
console.writer().print(message);
}
Note that the above print and println methods are defined by the PrintWriter class. There are convenience overloads for all of the primitive types, and also for Object. In the latter case, what is printed is the result of calling toString() on the argument.
There are also printf methods for formatting a number of arguments according to a format string.
For more information, read the following:
The javadocs for java.lang.System, java.io.PrintWriter and java.io.Console.
Oracle Java Tutorials: The Hello World Application.
System.out.print(message);
// or
System.out.println(message); // creates a new line after print is done.
There are many great courses on YouTube or the web for free which cover all basics and also intermediate topics.
Surf the internet about a problem before asking here. I'm not telling you that you can't ask here but you should put some effort into researching before asking.
In my code I am receiving numeric values as strings from different sources. One of the source is sending me this kind of value:
-6.535402781EX-05
After few tests I know that EX format is not handled by Double.valueOf() method. NumberFormatException is thrown.
I figured out easy workaround:
String val = "-6.535402781EX-05".replace("X", "");
Actually it is working, but I am not sure if that's best solution. I saw also EEX, EE and EXP. Question: How to protect my code for this kind of edge cases?
You may want to use replaceAll witha regex instead of replace if those are the only possible values:
String[] val = {"-6.535402781EX-05","-6.535402781EEX-05","-6.535402781EE-05","-6.535402781EXP-05"};
for(String v :val){
System.out.println(v.replaceAll("[EXP]{2,}", "E"));
}
Would a simple regular expression do the trick for you? You could first convert the different input formats to your known input format that can be handled by Double.valueOf().
String pattern = "(\\D?)(\\d+)(\\.?)(\\d+)(\\D+)(\\d+)";
List<String> inputs = Arrays.asList("-6.535402781EX-05",
"-6.535402781EXP-05",
"-6.535402781EE-05",
"-6.535402781E-05",
"6.535402781E-05",
"6.535402781",
"-6.535402781",
"6.5",
"6");
inputs.forEach((String in) -> System.out.println(in.replaceAll(pattern, "$1$2$3$4E-$6")));
The inputs in my example should be converted to the following and parsing them should be possible with Double.valueOf().
-6.535402781E-05
-6.535402781E-05
-6.535402781E-05
-6.535402781E-05
6.535402781E-05
6.535402781
-6.535402781
6.5
6
You should be careful to add enough unit test cases for all input formats you want to support.
I was wondering why do Java programs take parameters only in the form on Strings from the command line when they are run? I have read that if the parameters are declared as int, it still converts the int into String. Why does this happen? And is there any way to accept only int values from the command line when running a java program?
Strings are more versatile as they can hold any value and can even be an representative as an int. If you want to pass an int in the command line you can convert the string to and int yourself.
int val = Integer.parseInt(arg[0]);
The valid signature for the main method is
public static void main(String[] args)
no other argument structure will be seen as a main function.
I have read that if the parameters are declared as int, it still converts the int into String.
You have read that incorrectly. If the main() method takes anything other String[] args, it won't be recognized as a valid entry point by the JVM.
If you wish to take integer arguments, your main method still has to accept String[] args, and you have to perform the conversion yourself.
You passing chars from command line anyway (just because there is no "integers" on keyboard). So, you need to convert this char arrays (which are wrapped into String) into integers.
In my web application I have a version field that take float input values. But when using values like 1000000.1 (or larger) for the version it displays like 1.0E7. i tried several methods in Float wrapper class. but result still the same.
Thanks
Your problem is not in parsing but in formatting of your values. The value is correct and it is represented in java correctly. If you wish to change the format user either String.format() that provides C style formatting or java.text.NumberFormat.
System.out.printf("%f", Float.parseFloat("1.0E7")); outputs 10000000.000000
See http://ideone.com/3o6dO
Note that 1.0E7 is 1000000.0, not 1000000.1.
it probably has to do with your output format because 1.0E7 == 10000000
I think what you are looking for is the String.format(locale, msg, args) method.
Use String.valueOf(floatNumber)
Suggest use double instead of float
HI,
I have methods each of them requires integer ,string respectively. I read the inputs from my xml file. I will not be aware of what the type of inputs it will be. I am using reflection to invoke the method. I read the xml and store it as string. I invoke the method by passing in the parameter. One of the method expects an integer, but I pass in string. When I try to do the getType and cast, it is throwing class cast exception.
Anyhelp would be appreciated.
Thanks,
Priya.R
Java is strongly typed language. You can not pass a string to integer expecting method. You should convert string to integer, you can use Integer.parseInt() ..
If all inputs are Strings in the XML file, then there really is no difference between an XML file and a normal text file, is there?
The main problem is the representation of data types: you are not using XML as it's meant to be. XML files should represent the particular data type an input has. For example, a person's age should be represented as an int. You lose type semantics when you encode everything as a String.
As for actual code, use the XMLEncoder and XMLDecoder java classes located here and here, respectively.
Basically, you'll do something like:
XMLEncoder encoder = new XMLEncoder();
XMLDecoder decoder = new XMLDecoder();
Encoding (aka: Storing the data to the XML File)
- Write the first input as an integer type (encoder.writeInt(someIntValue))
- Write the second input as a String: encoder.writeString(someStrValue)
- etc
When decoding, you decode an integer first, then a String, etc.