In my code, I'm asking the user to input three different values divided by a blank space.
Then, those three different values I would like to assign them to three different Double variables.
I have tried by assigning the first character of such string to my double variables but I haven't been able to succeed.
Any suggestions?
Thank you!
Here is what I'm trying to do:
int decision = message();
String newDimensions;
double newHeight, newWidth, newLength;
if(decision == 1){
newDimensions = JOptionPane.showInputDialog("Please enter the desired amount to be added" +
"\nto each dimension." +
"\nNOTE: First value is for Height, second for Width, third for Length" +
"\nAlso, input information has to have a blank space between each value." +
"\nEXAMPLE: 4 8 9");
newHeight = Double.parseDouble(newDimensions.charAt(0));
Take input from user.
split that line using delimeter space i.e " ".
inside for loop change each index element to double.By using Double.parseDouble(splitted[i]);
Get the input, split it by a whitespace and parse each Double. This code does not sanitize the input.
String input = "12.4 19.8776 23.3445";
String[] split = input.split(" ");
for(String s : split)
{
System.out.println(Double.parseDouble(s));
}
You could first split the input using String.split and then parse each variable using Double.parseDouble Double.parseDouble to read them into a Double variable.
String[] params = newDimensions.split(" ");
newHeight = Double.parseDouble(params[0]);
newWidth = Double.parseDouble(params[1]);
Double#parseDouble(str) expects a string,and you are trying to pass a character.
try this:
newHeight = Double.parseDouble(newDimensions.subString(1));
Try something like this:
newDimensions = JOptionPane.showInputDialog(...
newDimensions = newDimensions.trim();
String arr[] = newDimensions.split(" ");
double darr[] = new double[arr.length];
for(int i=0;i<arr.length;i++) darr[i] = Double.parseDouble(arr[i].trim());
There are still some defensive issues that can be taken. Doing a trim on your parse double is kind of critical.
Related
I am writing a program and I need to input a value for index, but the index should be composite, e.g 44GH.
My question is, how to make the program to do not crash when I ask the user to input it and then I want to display it?
I have been looking for answer in the site, but they are only for integer or string type.
If anyone can help, would be really appreciated.
Scanner s input = new Scanner(System.in);
private ArrayList<Product> productList;
System.out.println("Enter the product");
String product = s.nextLine();
System.out.println("Input code for your product e.g F7PP");
String code = s.nextLine();
}
public void deleteProduct(){
System.out.println("Enter the code of your product that you want to delete ");
String removed = input.nextLine();
if (productList.isEmpty()) {
System.out.println("There are no products for removing");
} else {
String aString = input.next();
productList.remove(aString);
}
}
Remove all non digits char before casting to integer:
String numbersOnly= aString.replaceAll("[^0-9]", "");
Integer result = Integer.parseInt(numbersOnly);
The best way to do it is to create some RegEx that could solve this problem, and you test if your input matches your RegExp. Here's a good website to test RegExp : Debuggex
Then, when you know how to extract the Integer part, you parse it.
I think the OP wants to print out a string just but correct me if I am wrong. So,
Scanner input = new Scanner(System.in);
String aString = input.nextLine(); // FFR55 or something is expected
System.out.println(aString);
Then obviously you can use:
aString.replaceAll();
Integer.parseInt();
To modify the output but from what I gather, the output is expected to be something like FFR55.
Try making the code split the two parts:
int numbers = Integer.parseInt(string.replaceAll("[^0-9]", ""));
String chars = string.replaceAll("[0-9]", "").toUpperCase();
int char0Index = ((int) chars.charAt(0)) - 65;
int char1Index = ((int) chars.charAt(1)) - 65;
This code makes a variable numbers, holding the index of the number part of the input string, as well as char0Index and char1Index, holding the value of the two characters from 0-25.
You can add the two characters, or use the characters for rows and numbers for columns, or whatever you need.
I was working on a bit of code where you would take an input of 2 numbers, separated by a comma, and then would proceed to do other actions with the numbers.
I was wondering how I would parse the string to take the first number up to the comma, cast it to and int and then proceed to cast the second number to an int.
Here is the code I was working on:
Scanner Scan = new Scanner(System.in);
System.out.print("Enter 2 numbers (num1,num2): ");
//get input
String input = Scan.nextLine();
//parse string up to comma, then cast to an integer
int firstNum = Integer.parseInt(input.substring(0, input.indexOf(',')));
int secondNum = Integer.parseInt(Scan.nextLine());
Scan.close();
System.out.println(firstNum + "\n" + secondNum);
The first number is cast to an integer just fine, I run into issues with the second one.
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
How would I be able to then take the second integer out of the input string and cast it to an Int.
The error mode you're encountering seems reasonable indeed, as you're reading the next line from the scanner and therefore explicitly no longer operating on the first input anymore.
What you're looking for is probably this:
int secondNum = Integer.parseInt(input.substring(input.indexOf(',') + 1));
When defining secondNum, you're setting it equal to the parsed integer of the next line the scanner object reads, but all of the data has already been read. So rather than read from the scanner again, you'll want to call Integer.parseInt on everything after the comma.
It fails because all digit are given by the user on the same line. and you have two Scanner.nextLine(); the second is probably empty.
here is a solution :
Scanner Scan = new Scanner(System.in);
System.out.print("Enter 2 numbers (num1,num2): ");
//get input
String input = Scan.nextLine();
StringTokenizer st = new StringTokenizer(input, ",");
List<Integer> numbers = new ArrayList<>();
while (st.hasMoreElements()) {
numbers.add(Integer.parseInt(st.nextElement()));
}
System.out.println(numbers);
If input on one line, both the numbers will be stored in the String variable input. You don't need to scan another line. It will be empty, and you cannot cast the empty string to an int. Why not just parse the second number out of input, as you did the first.
Hello i tried many ways to complete this but i failed.
Could you help me ?
I need double split one is "\n" and second is "|".
In textArea is string
350|450\n
444|452\n
and so one.
There are mouse coordinates.
X|Y
in int array i need
array[0]= x coord;
array[1]= y coord;
array[2]= x coord;
array[2]= y coord;
So i have string in textarea.I split that by "\n"
String s[]= txtArea.getText().split("\\n");
This is one split and in textarea i have something like 150|255
this is my mouse coordinates x|y.
So i need next split "|".
String s2[] = s[i].split("|");
After that
int [] array = new [s.length*2];
And some method for
while(!(s[j].equals("|")))
array[i] = Integer.parseInt(s[j]);
I tried something like that-
for(String line : txtArea.getText().split("\\n")){
arrayXY = line.split("\\|");
array = new int[arrayXY.length];
}
Thank you a lot for answers :)
Have a nice day.
This can be solved easily using regex:
String[] split = input.split("\\||\n");
split will then contain the single numbers from the input.
Use Scanner. It is always preferred over String.split().
Your code would then reduce to:
Scanner scanner = new Scanner(txtArea.getText());
scanner.useDelimiter("\\||\\n"); // i.e. | and the new line
for (int i = 0; i < array.length; i++) { // or use the structure you need
array[i] = scanner.nextInt();
}
Also, don't forget to import java.util.Scanner;
Input:
1 10
How can I provide a space between two inputs so that compiler can take both the inputs differently.
I tried to use
st1=in.nextInt();
in.next();
st2=in.nextInt();
Simply remove the in.next(); call. nextInt() already "ignores" whitespaces. And there is no need to create an array by using split() and to convert the number "manually". Just let the Scanner handle this by using nextInt() like you do already:
Scanner s = new Scanner("1 10 9 5");
while(s.hasNextInt()) {
int number = s.nextInt();
System.out.println(number);
}
The good thing about that is, that you won't get a NumberFormatException like in the other answers if the user does not provide numbers (e.g. a b c).
The following line will give you a String array containing the two numbers as strings:
String[] numbersFromUser = in.nextLine().split(" ");
Assuming that the user properly formats the input.
This would of course also work for a number of arguments greater than 2.
You can then go on to convert numbersFromUser[0] and numbersFromUser[1] into the int values you need:
int st1 = Integer.valueOf(numbersFromUser[0]).intValue();
int st2 = Integer.valueOf(numbersFromUser[1]).intValue();
Use:
data = line.split("\s");
first = data[0];
second = data[1];
third = data[2];
System.out.println(first)
System.out.println(second);
System.out.println(third);
Input:
1 5 6
Output:
1
5
6
I realise it's pretty basic.
I need to ask user for an string input. Then I divide string to single char array and print it in a console. I have to ignore spaces
Tried this but when I input "this is test string" as output I get only {t h i s}
String tekst;
Scanner odczyt = new Scanner(System.in);
System.out.println("Wpisz tekst");
tekst = odczyt.next();
int iloscZnakow = tekst.length();
char tablica[] = new char[iloscZnakow];
tablica = tekst.toCharArray();
System.out.println(Arrays.toString(tablica));
You can use toCharArray() method of String class.
Please replace odczyt.next(); with odczyt.nextLine();