So I can't get this little snipit of code to work and I'm not sure why it wont...
String rawInput = JOptionPane.showInputDialog("Please enter the three side lengths seperated by spaces.");
double[] hold = double.parseDouble(rawInput.split(" "));
I have an idea to use another string array to put the values in initially then put them into the double array using a for loop and the double.parseDouble() but that seems overly complicated for what I want to do.
Your code fails to compile because rawInput.split(" ") returns an array of String objects. You need just one String object to pass to Double.parseDouble(). It looks like you'll need a loop, to iterate through the array that you get.
If only it was that simple. You will have to create a loop.
What I ended up doing was this:
String rawInput = JOptionPane.showInputDialog("Please enter the three side lengths seperated by spaces.");
double[] doubleHold = new double[3];
String[] stringHold = rawInput.split(" ");
for(int i = 0; i < 3; i++)
{
doubleHold[i] = Double.parseDouble(stringHold[i]);
}
I don't like how it works and think there must be a better way, anyone have that better way?
String rawInput = JOptionPane.showInputDialog("Please enter the three side lengths seperated by spaces.");
String[] inputs = rawInput.split(" ");
double[] values = new double[inputs.length];
for (int i = 0; i < inputs.length; i++) {
values[i] = Double.parseDouble(inputs[i]);
}
Try this!
Related
I need to use scanner to get 2 inputs.
1st input is a sequence of integers that I need to store in ArrayList.
2nd input should go right after the first one and it's integer as well.
My question is - how do I stop accepting input for ArrayList and tell the machine to ask for a second number.
I ended with something like this but it does not of course work because it just keeps asking for integers for arraylist. And yes, I need to use ArrayList for the task, since I don't know how many integers there will be. I also haven't learned List interface yet so I need to use what I have in my disposal.
while (scanner.hasNextInt()) {
numbers.add(scanner.nextLine());
if (scanner.hasNextInt()) {
referenceNumber = scanner.nextInt();
}
}
I managed to solve it this way, though probably not optimal
String inputString = scanner.nextLine();
String[] inputArray = inputString.split(" ");
int[] numberArray = new int[inputArray.length];
for (int i = 0; i < inputArray.length; i++) {
numberArray[i] = Integer.parseInt(inputArray[i]);
}
if (scanner.hasNextInt()) {
referenceNumber = scanner.nextInt();
}
if your input sequence is something like 23 34 54 46 then you can use this
Scanner scanner = new Scanner(System.in);
String integers = scanner.nextLine();
StringTokenizer string = new StringTokenizer(integers);
ArrayList<Integer> list = new ArrayList<Integer>();
while(string.hasNextToken()){
list.add(Integer.parseInt(string.nextToken()));
}
Sorry for the uninformative title, but I'm new to Java and am quite confused about how I should separate a user input (a string) into two different strings.
Essentially, what I want to do is take a user input with two of the same numbers or letters separated by a space, and remove the corresponding numbers or letters from an ArrayList of strings.
Note: the user input can be a single number or letter, and the method for this part must identify that the user input is not a single letter or number.
For example, if I have the (java) code:
Scanner scan = new Scanner(System.in);
String str = scan.nextLine();
the user then input:5 5 (5 space 5)
and if I have an ArrayList:
Arraylist<String> arrList = new ArrayList<String>;
arrList.add("1");
arrList.add("5");
arrList.add("5");
arrList.add("3");
How do I remove the two 5's from arrList?
My first approach was to separate the user input string into two different strings so that I could remove the two strings from the ArrayList of strings. Since both numbers or letters should be identical to each other, I would only need to scan the first integer or letter. However, I'm not quite sure how to write a method that would scan the first integer or letter in a string that consist of two numbers/integers with a space between them.
I would be much appreciated for any help! Thanks!
Simply use Collection::removeIf method:
String number = "5"; // or an user input
arrList.removeIf(item -> number.equals(item)); // number::equals
You can use .split() to split the inputs by space
String str = scan.nextLine();
String[] list = str.split(" ");
Then you can remove inputs using .remove() from ArrayList
for (int i = 0; i < list.length; i++) {
arrList.remove(list[i]);
}
You have at least two options:
Use split():
String[] numbers = str.split(" ");
Use next() instead of nextLine():
String str1 = scan.next();
String str2 = scan.next();
If you take the latter approach, you might add a hasNext() call to handle the case where there's only one string.
According to your explained example, it looks like you only want to remove the first instance of a string item from the ArrayList otherwise you wouldn't want to supply 5 5, something like this:
String ls = System.lineSeparator();
ArrayList<String> arrList = new ArrayList<>();
arrList.add("1");
arrList.add("5");
arrList.add("5");
arrList.add("3");
Scanner scan = new Scanner(System.in);
String str = "";
while (str.equals("")) {
System.out.print("Enter the numerical strings to delete from ArrayList seperated by a whitespace: " + ls
+ "Your Entry: --> ");
str = scan.nextLine();
if (!str.replaceAll("\\s+", "").matches("\\d+")) {
System.out.println("Invalid Entry! Entries must be numerical integer type! (" + str + ")" + ls);
str = "";
}
}
String[] numbers = str.split("\\s+");
// Iterate through all the User Supplied numbers...
for (int i = 0; i < numbers.length; i++) {
// Remove the first instance (only) of the
// current User the supplied number.
for (int j = 0; j < arrList.size(); j++) {
if (arrList.get(j).equals(numbers[i])) {
arrList.remove(j);
break;
}
}
}
// Display the ArrayList when all is done...
System.out.print(String.join(ls, arrList));
If you supply only one 5 then only the first 5 encountered within the ArrayList is removed.
At the start of the code the user determines a number of keywords and the keyword strings themselves, they place this into an array. Lets say the user says 3 keywords and they are "music", "sports" and "memes". After all this, say the user inputs in the program "I like sports". I simply want the program to respond with "Let's talk about sports" after recognising that the user said sports which is in the array that the user has essentially created.
I want to reference a string the user has predetermined then print it along with a message
I can see the potential of this working using for loops and going through every article until you find a match, I haven't done much work with booleans yet so I just need some assistance punching out the code then learning from it
this all has to happen inside a while loop so when that's done they can use a different keyword and get the same boring response
thanks
note: I don't actually have any of this code I want in my program yet, this code is just to show you kind of how it fits into the greater scheme of things.
import java.util.Scanner;
public class Assignment1 {
public static void main(String[] args) {
String kwArray[];
String UserMessage;
String Target = "";
int numKw = 0;
Scanner input = new Scanner(System.in);
System.out.println("How many keywords do you want?");
numKw = input.nextInt();
kwArray = new String[numKw];
System.out.print(System.lineSeparator());
input.nextLine();
for (int i = 0; i < numKw; i++) {
System.out.println("Enter keyword " + (i + 1) + ": ");
kwArray[i] = input.nextLine();// Read another string
}
for (int i = 0; i < numKw; i++) {
kwArray[i] = kwArray[i].toLowerCase();
}
int x = 0;
while (x == 0) {
System.out.println("Hey I'm a chatbot! Why don't you say something to me!");
System.out.println("These are the keywords you gave me");
for (String i : kwArray) {
System.out.print(i);
System.out.print(", ");
}
System.out.print(System.lineSeparator());
System.out.println("Or you can terminate the program by typing goodbye");
UserMessage = input.nextLine();
// Gives the user opportunity to type in their desired message
UserMessage = UserMessage.toLowerCase();
if (UserMessage.contains("?")) {
System.out.println("I will be asking the questions!");
}
if (UserMessage.contains("goodbye")) {
x = 1;
}
}
input.close();
}
}
If I am getting the question right, you want to check whether an element exists in the submitted keywords and want to reference it back if you further processing.
For this, instead of an array you could use a HashSet which can check the existence any element in O(1).
Updated the code, but I still feel your query is the same what I understood, putting the exact example of your use case below:
Scanner input = new Scanner(System.in);
Set<String> set = new HashSet<String>();
int keywords = input.nextInt();
for (int i=0; i<keywords; i++) {
//add to set set like:
set.add(input.readLine());
}
String userComment = input.readLine();
String[] userCommentWords = userComment.split(" ");
//you can iterate over the words in comment and check it in the set
for (int i=0; i<userCommentWords.length; i++) {
String word = userCommentWords[i];
if (set.contains(word)) {
System.out.println("Let's talk about "+word);
}
}
I have a bit of a unique problem to solve and I'm stuck.
I need to design a program that does the following:
Inputs two series of numbers (integers) from the user.
Creates two lists based on each series.
The length of each list must be determined by the value of the first digit of each series.
The rest of the digits of each series of numbers becomes the contents of the list.
Where I'm getting stuck is in trying to isolate the first number of the series to use it to determine the length of the list.
I tried something here so let me know if this is what you're looking for. It would be better for you to provide your attempt first.
I also want to point out that Lists are for the most part dynamic. You don't have to worry about the size of them like a normal array.
Scanner sc = new Scanner(System.in);
ArrayList<Integer[]> addIt = new ArrayList<>();
boolean choice = false;
while(choice == false){
String line = sc.nextLine();
if(line.equalsIgnoreCase("n")){
break;
}
else{
String[] splitArr = line.split("\\s+");
Integer[] convertedArr = new Integer[splitArr.length];
for(int i = 0; i < convertedArr.length; i++){
convertedArr[i] = Integer.parseInt(splitArr[i]);
}
addIt.add(convertedArr);
}
}
This is assuming that you are separating each integer with a whitespace. If you are separating the numbers with something else just modify the split statement.
The user enters "n" to exit. With this little snippet of code, you store each array of Integer objects in a master ArrayList. Then you can do whatever you need to with the data. You can access the first element of each Integer object array to get the length. As you were confused how to isolate this value, the above snippet does that for you.
I would also advise you to add your parse statement in a try-catch block to provide error handling for invalid input that cannot be parsed to an integer.
This is one way of doing it with default arrays.
import java.util.Scanner;
public class ScanList {
public static void main(String[] args){
System.out.println("Array:");
Scanner s = new Scanner(System.in);
String line = s.nextLine();
String[] nums = line.split(",");
int[] result = new int[Integer.parseInt(nums[0])];
for(int i = 0; i<result.length;i++){
result[i]=Integer.parseInt(nums[i+1]);
}
for(int r:result){
System.out.println(r);
}
}
}
This is what I came up with:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Insert the first series of numbers: ");
String number1 = input.nextLine();
System.out.println("Insert the second series of numbers: ");
String number2 = input.nextLine();
String[] items = number1.split(" ");
String[] items2 = number2.split (" ");
List<String> itemList = new ArrayList<String>(Arrays.asList(items));
itemList.remove(0);
Collections.sort(itemList);
System.out.println(itemList);
} // End of main method
while (scan.hasNextLine()) {
String thisline = scan.nextLine();
totalnumber.countthelines++; //linecount works
for(int i = 0; i < thisline.length();i++){
totalnumber.charactercounter++; //chararacter count works
String [] thewords = thisline.split (" ");
totalnumber.wordcounter = thewords.length; //does not work
}
}
I am having trouble getting my wordcounter to work(I am already able to count the characters and lines). I have tried many different ways to make it work, but it always ends up only counting the words from the last line of the read in file. Any suggestions on how to make it read every single line instead of just the last?
Thanks
Well :
totalnumber.wordcounter += thewords.length
should be enough !
You just forgot to add the number of words...
So the entiere code is :
while (scan.hasNextLine()) {
String thisline = scan.nextLine();
totalnumber.countthelines++; //linecount works
totalnumber.charactercounter+=thisline.length(); //chararacter count works
String [] thewords = thisline.split (" ");
totalnumber.wordcounter += thewords.length;
}
(Sorry about the multiple edits. Sometime, it's so obvious... ;)
You need:
String [] thewords = thisline.split (" ");
totalnumber.wordcounter += thewords.length;
outside of the loop iterating the characters. Note the += instead of =.
for(int i = 0; i < thisline.length(); i++) {
totalnumber.charactercounter++; //chararacter count works
}
String [] thewords = thisline.split (" ");
totalnumber.wordcounter = thewords.length; //does not work