I'd like to pop from text file which looks like "70.869, 78.22, 368.12...". I wrote this code using delimiters but it doesn't work for double ( my console after compile project is empty ). If I change it to int it works perfectly fine. I'd like to put this numbers to the array.
Scanner src = new Scanner(new File("ala1.txt"));
src.useDelimiter(", *");
float [] taller = new float [15];
int k = 0;
// Read and sum numbers.
while(src.hasNextDouble()){
//tall[i++] = scanner.nextInt();
System.out.println(src.nextDouble());
}
src.close();
Your delimiter looks fine, which suggests that problem is somewhere else.
From your question it looks like hasNextDouble doesn't see 70.869 as proper double. Possible problem could be that your locales instead of . expects , in double value (and based on your code it looks like your locale is Polish which confirms this theory).
So if that is the case make your Scanner use other locale which expects . in double instead of , like Locale.ENGLISH:
Scanner src = new Scanner("70.869, 78.22, 368.12");
src.useLocale(Locale.ENGLISH);
src.useDelimiter(", *");
while(src.hasNextDouble()){
System.out.println(src.nextDouble());
}
Output:
70.869
78.22
368.12
Related
System.out.println("Number of pages + Number of lost pages + Number of Readers");
int n = s.nextInt();
int m = s.nextInt();
int q = s.nextInt();
I want to read input values all the values are going to be integer but I want to read it in a same line with changing it form Integer.
Assuming s is an instance of Scanner: Your code, as written, does exactly what you want.
scanners are created by default with a delimiter configured to be 'any whitespace'. nextInt() reads the next token (which are the things in between the delimiter, i.e. the whitespace), and returns it to you by parsing it into an integer.
Thus, your code as pasted works fine.
If it doesn't, stop setting up a delimiter, or reset it back to 'any whitespace' with e.g. scanner.reset(); or scanner.useDelimiter("\\s+");.
class Example {
public static void main(String[] args) {
var in = new Scanner(System.in);
System.out.println("Enter something:");
System.out.println(in.nextInt());
System.out.println(in.nextInt());
System.out.println(in.nextInt());
}
}
works fine here.
I'm doing a project for a Uni course where I need to read an input of an int followed by a '+' in the form of (for example) "2+".
However when using nextInt() it throws an InputMismatchException
What are the workarounds for this as I only want to store the int, but the "user", inputs an int followed by the char '+'?
I've already tried a lot of stuff including parseInt and valueOf but none seemed to work.
Should I just do it manually and analyze char by char?
Thanks in advance for your help.
Edit: just to clear it up. All the user will input is and Int followed by a + after. The theme of the project is to do something in the theme of a Netflix program. This parameter will be used as the age rating for a movie. However, I don't want to store the entire string in the movie as it would make things harder to check if a user is eligible or not to watch a certain movie.
UPDATE: Managed to make the substring into parseInt to work
String x = in.nextLine();
x = x.substring(0, x.length()-1);
int i = Integer.parseInt(x);
Thanks for your help :)
Try out Scanner#useDelimiter():
try(Scanner sc=new Scanner(System.in)){
sc.useDelimiter("\\D"); /* use non-digit as separator */
while(sc.hasNextInt()){
System.out.println(sc.nextInt());
}
}
Input: 2+33-599
Output:
2
33
599
OR with your current code x = x.substring(0, x.length()-1); to make it more precise try instead: x = x.replaceAll("\\D","");
Yes you should manually do it. The methods that are there will throw a parse exception. Also do you want to remove all non digit characters or just plus signs? For example if someone inputs "2 plus 5 equals 7" do you want to get 257 or throw an error? You should define strict rules.
You can do something like: Integer.parseInt(stringValue.replaceAll("[^\d]","")); to remove all characters that are no digits.
Hard way is the only way!
from my Git repo line 290.
Also useful Javadoc RegEx
It takes in an input String and extracts all numbers from it then you tokenize the string with .replaceAll() and read the tokens.
int inputLimit = 1;
Scanner scan = new Scanner(System.in);
try{
userInput = scan.nextLine();
tokens = userInput.replaceAll("[^0-9]", "");
//get integers from String input
if(!tokens.equals("")){
for(int i = 0; i < tokens.length() && i < inputLimit; ++i){
String token = "" + tokens.charAt(i);
int index = Integer.parseInt(token);
if(0 == index){
return;
}
cardIndexes.add(index);
}
}else{
System.out.println("Please enter integers 0 to 9.");
System.out.print(">");
}
Possible solutions already have been given, Here is one more.
Scanner sc = new Scanner(System.in);
String numberWithPlusSign = sc.next();
String onlyNumber = numberWithPlusSign.substring(0, numberWithPlusSign.indexOf('+'));
int number = Integer.parseInt(onlyNumber);
I need to read from a csv file. The file has some different types like int, float, String, char. How can I know what the type is?
I did write some code for it but my problem is with floating point numbers. In my computer java say that "7.9" is not a floating point number, but "7,9" is.
But on some computers "7.9" is a float. How can I solve this?
public static void Read(String filename) throws FileNotFoundException{
File file = new File(filename);
Scanner scanner1 = new Scanner(file);
String line ;
Scanner scanner;
int a;
float f;
String temp ;
while(scanner1.hasNextLine()){
line = scanner1.nextLine();
scanner = new Scanner(line);
scanner.useDelimiter(",|\\n");
while (scanner.hasNext()){
if (scanner.hasNextInt()){
a = scanner.nextInt();
System.err.printf("Int :%d",a);
}
else if(scanner.hasNextFloat()){
f = scanner.nextFloat();
System.err.printf("flt :%f",f);
}
else {
temp = scanner.next();
if(temp.length() == 1)
System.err.printf("char:%s",temp);
else
System.err.printf("string:%s",temp);
}
}
System.err.printf("\n");
scanner.close();
}
}
The more I read this more I realize I was wrong.
If your CSV data is like
1,2,3,4
Then it could be (1,2 and 3,4) eg (1.2, 3.4) or it could be the integers 1 through 4
If its properly quoted
"1,2","3,4"
Then your parser wont work because its not using quotes as the delimiters.
So its hard to say what is causeing your issue with out seeing the data.
You could add handeling of the quotes in your scanner but there are more cases inolved if your vlaues contain quotes themselves
Ideally use a proper CSV parse like http://opencsv.sourceforge.net/
Otherwise you need to walk through your data nad make sure your parse is covering all the cases you have today, and might have tomorrow.
A hack work around would be to modify your strings using replaceAll(".",","); but there are many pitfulls when doing that again, your scanner may confuse the elements as new entries in your CSV.
Specifically to change from representing decimals from 1,2 to 1.2 you can modify the Local for the number types you want with
scanner1.useLocale(Locale.US);
From what I can tell there is no way to have more than one locale for the scanner. One approach is to use two scanners, with two different Locales at the same time to parse the float differently.
You can change the scanner's locale using #useLocale(java.util.Locale)
Set the locale to one which uses . as the decimal point. I.e)
scanner.useDelimiter(",|\\n");
scanner.useLocale( Locale.US ); // Use '.' as decimal point
Currently reading Chapter 6 in my book. Where we introduce for loops and while loops.
Alright So basically The program example they have wants me to let the user to type in any amount of numbers until the user types in Q. Once the user types in Q, I need to get the max number and average.
I won't put the methods that actually do calculations since I named them pretty nicely, but the main is where my confusion lies.
By the way Heres a simple input output
Input
10
0
-1
Q
Output
Average = 3.0
Max = 10.0
My code
public class DataSet{
public static void main(String [] args)
{
DataAnalyze data = new DataAnalyze();
Scanner input = new Scanner(System.in);
Scanner inputTwo = new Scanner(System.in);
boolean done = false;
while(!done)
{
String result = input.next();
if (result.equalsIgnoreCase("Q"))
{
done = true;
}
else {
double x = inputTwo.nextDouble();
data.add(x);
}
}
System.out.println("Average = " + data.getAverage());
System.out.println("Max num = " + data.getMaximum());
}
}
I'm getting an error at double x = inputTwo.nextDouble();.
Heres my thought process.
Lets make a flag and keep looping asking the user for a number until we hit Q. Now my issue is that of course the number needs to be a double and the Q will be a string. So my attempt was to make two scanners
Heres how my understanding of scanner based on chapter two in my book.
Alright so import Scanner from java.util library so we can use this package. After that we have to create the scanner object. Say Scanner input = new Scanner(System.in);. Now the only thing left to do is actually ASK the user for input so we doing this by setting this to another variable (namely input here). The reason this is nice is that it allows us to set our Scanner to doubles and ints etc, when it comes as a default string ( via .nextDouble(), .nextInt());
So since I set result to a string, I was under the impression that I couldn't use the same Scanner object to get a double, so I made another Scanner Object named inputTwo, so that if the user doesn't put Q (i.e puts numbers) it will get those values.
How should I approach this? I feel like i'm not thinking of something very trivial and easy.
You are on the right path here, however you do not need two scanners to process the input. If the result is a number, cast it to a double using double x = Double.parseDouble(result) and remove the second scanner all together. Good Luck!
I'm have a little problem with the Java class Scanner:
I need to read a file (.dat) that contains Double values, but it seems like the method Scanner.nextDouble only recognize number written like this: 1234,5678 , with a "," but not with a ".". I wanted to know if there was a way to change that, because the file is generated by another software, so I can't make it change the "," for a ".".
Thanks
Robin
It seems like your default Locale uses a comma-based decimal separator for double values. Try using
scanner.useLocale(Locale.ENGLISH);
Replace , with .
Example:
Scanner sc = new Scanner(new File("myNumbers"));
while (sc.hasNext()) {
String s = sc.next();
Double d = (Double)s.replace(",",".");
}