I'd like to create a method where it can print out an array created by user's input in Scanner.
The data type of the array is double.
So far, I have created an array of the size that the user has provided, but how do I enter all the double input elements into an array then print it out in a method?
Do I need to ask the user to give each number one by one? I would like to avoid this. Thanks
If I understand what you are asking, you don't want hundreds of alert messages asking the user for input, correct? Just ask once?
If that is the case, you can ask the user to separate the input with some symbol. For example a semi-colon. Then the user can input something like this:
1;2;3;4;5
Then what you do is split the input to get the array, and you print it out using a for loop and a printing method of your choice (e.g. system.out or show in an alert message)
Hope that solves your problem
You could grab user input from the console, and have them separate entries with spaces... ie:
Enter your series separated by spaces:
123.33 333.44 342.22 43.33
Storing this result to a String and then passing it to this method.
public double[] setDoubleArray(String input, int arraySize) {
double[] doubleArray = new double[arraySize];
Scanner s = new Scanner(input);
for (int i = 0; s.hasNextDouble(); i++) {
doubleArray[i] = s.nextDouble();
}
s.close();
return doubleArray;
}
Is this what your looking for?
Related
I'm trying to read a String and then Integers or Strings using Scanner:
public class Main {
public static void main (String[] args){
String[] StringList;
Integer[] IntegerList;
ArrayList<String> auxS = new ArrayList<>();
ArrayList<Integer> auxI = new ArrayList<>();
String order; int ord=-1;
Scanner scan = new Scanner(System.in);
order = scan.nextLine();
//do something with order
while(scan.hasNextLine()){
if(scan.hasNextInt()){
auxI.add(scan.nextInt());
}
else if(!scan.nextLine().isEmpty()){
auxS.add(scan.nextLine());
}else{ //I've tried using another scan. methods to get to this point
scan.next();
break;
}
}
}
}
As you can see, I first read a String and store it in "order", then I want to keep reading until EOF or user enters "Enter" or anything else non-specific such as "write 'exit' " or something like that.
I've tried using scan.hasNext, hasNextLine, and other combinations involving the last else but none of them worked.
If the input is:
>>THIS WILL BE STORED IN ORDER<<
123
321
213
231
312
<enter>
I want it to stop when nothing has been entered as in the last line. It is important to store the Integers or Strings in their own ArrayLists, as I use it later and I need to identify the type of each entered data (that's why I use hasNextInt inside the while loop).
Generally, just don't use .nextLine(), it is confusing and rarely does what you want. If you want to read entire lines as a single item, update the scanner's delimiter; change it from the default 'any sequence of whitespace' to 'a single newline': scanner.useDelimiter("\r?\n"); will do that (run that immediately after making a scanner). To read a line, use any of the .next() methods (but not .nextLine()): Want an int? call .nextInt(). Want any string? Call .next(), etcetera.
then split up your if/elseif block. An empty line is still a string, just, an empty one:
if (scanner.hasNextInt()) {
// deal with ints
} else {
String text = scanner.next();
if (!text.isEmpty()) {
// deal with strings
} else {
// deal with a blank line
}
}
NB: Once you stop using .nextLine(), you don't have to throw out semi-random .nextLine() calls to 'clear the buffer' or whatnot. That annoyance just goes away, which is one of the many reasons why you should just forget about nextLine. Generally, for scanners, either use only .nextLine(), or don't ever use .nextLine(), and things work out much better.
Im trying to write a program that takes a string of user inputs such as (5,6,7,8) and converts it to an arrayList of integers e.g. {5,6,7,8}. I'm having trouble figuring out my for loop. Any help would be awesome.
String userString = "";
ArrayList<Integer> userInts = new ArrayList<Integer>();
System.out.println("Enter integers seperated by commas.");
userString = in.nextLine();
for (int i = 0; i < userString.length(); i++) {
userInts.add(new Integer(in.nextInt()));
}
If your list consists of single-digit numbers, your approach could work, except you need to figure out how many digits there are in the string before allocating the result array.
If you are looking to process numbers with multiple digits, use String.split on the comma first. This would tell you how many numbers you need to allocate. After than go through the array of strings, and parse each number using Integer.parseInt method.
Note: I am intentionally not showing any code so that you wouldn't miss any fun coding this independently. It looks like you've got enough knowledge to complete this assignment by reading through the documentation.
Lets look at the lines:
String userString = ""
int[] userInt = new int[userString.length()];
At this point in time userString.length() = 0 since it doesnt contain anything so this is the same as writing int[] userInt = new int[0] your instantiating an array that cant hold anything.
Also this is an array not an arrayList. An arrayList would look like
ArrayList<Integer> myList = new ArrayList()<Integer>;
I'm assuming the in is for a Scanner.
I don't see a condition to stop. I'll assume you want to keep doing this as long as you are happy.
List<Integer> arr = new ArrayList<Integer>();
while(in.hasNext())
arr.add(in.nextInt());
And, say you know that you will get 10 numbers..
int count = 10;
while(count-- > 0)
arr.add(in.nextInt());
Might I suggest a different input format? The first line of input will consist of an integer N. The next line contains N space separated integers.
5
3 20 602 3 1
The code for accepting this input in trivial, and you can use java.util.Scanner#nextInt() method to ensure you only read valid integer values.
This approach has the added benefit of validate the input as it is entered, rather than accepting a String and having to validate and parse it. The String approach presents so many edge cases which need to be handled.
Trying to sort the doubles in descending order from my .txt file and print out the results, but why am I getting 4 lines of []?
My text file looks like this:
Mary Me,100.0
Hugh More,50.8
Jay Zee,85.0
Adam Cop,94.5
with my code that looks like this:
public static void sortGrade() throws IOException
{
Scanner input = new Scanner(new File("Grades.txt"));
while(input.hasNextLine())
{
String line = input.nextLine();
ArrayList<Double> grades = new ArrayList<Double>();
Scanner scan = new Scanner(line);
scan.useDelimiter(",");
while(scan.hasNextDouble())
{
grades.add(scan.nextDouble());
}
scan.close();
Collections.sort (grades,Collections.reverseOrder());
System.out.println(grades);
}
input.close();
}
I'd like for the output to look like this:
Hugh More,50.8
Jay Zee,85.0
Adam Cop,94.5
Mary Me,100.0
A push in the right direction would be great, thanks.
The problem is you're not reading in your values correctly!
You're reading in your line here:
String line = input.nextLine();
And then trying to parse it with a second one but this:
scan.hasNextDouble()
Will always return false as the first token in each string is the name! And it's not a double. You need to change the way you're parsing your input.
Furthermore if you want to sort both the name and the score at the same time you have to create an object that would encapsulate both name and grade and implement Comparable or write a custom Comparator for that type. Otherwise you'd have to make a Map mapping grade to each name, sort the grades and then print it in order while getting names for each grade (there can be multiple names for the same grade). This is not recommended because it does look clumsy.
Writing a comparable class really isn't that hard you just need to implement one method :-)
#Edit: you don't need a second scanner, if your format is set and that easy just use a split on that line like this:
String[] gradeName = line.split(",");
grades.add(Double.parseDouble(gradeName[1]));
If you can have more than 1 grade per person than instead of just getting gradeName[1] iterate over gradeName starting from the element at index 1 (since 0 is the name).
#Edit2:
You are creating a new grades list in the loop every time, so it will read one entry, add it to the list, sort it and print it. You should pull out everything except for those lines outside the while loop:
String line = input.nextLine();
String[] gradeName = line.split(",");
grades.add(Double.parseDouble(gradeName[1]));
#Edit3:
If you want an ascending order don't use Collections.reverseOrder(), just the default one:
Collections.sort (grades);
I need to know how to do computations on a user inputed list of numbers. Here's my code so far, I'm lost as to how to proceed. I need to write a code that asks whether or not the user wants to manually input numbers or upload from a file. If user chooses manual, I have to find the average, min, max, and stand. dev. of the numbers they input. Any help would be appreciated
import java.io.*;
public class computation {
//main method starts
public static void main (String[] args) throws Exception {
//create text input reader
InputStreamReader get = new InputStreamReader(System.in);
BufferedReader got = new BufferedReader(get);
//create a text printer
PrintWriter send = new PrintWriter(System.out,true);
//defining a string type variable for user input
String answer1;
//asks the user if they want to input data from keyboard
String question = "Do you want to input data manually? Enter y or n";
send.println(question);
//system reads user input
answer1 = got.readLine();
if (answer1.equals("y")) {
send.println("Enter numbers separated by spaces");
String datacurrent = got.readLine();
} //end of "y" if
if (answer1.equals("n")) {
send.println("Enter the path of your data file");
} //end of "n" if
} //end of main method
} //end of class computation
I just ran your program, it seems alright.
(A) What to do when values inputted through console ?
Split the string into an array, extract each number and then calculate Average, Min, Max, and Stand deviation.
For ex:
String[] numbers = datacurrent.split(",");
for(int i=0; i<number.length; i++)
{
....
}
(B) What to do when inputted as file path ?
You will have to read the file using File Stream/Buffer Reader.
BufferedReader reader = new BufferedReader(new FileReader(Your string variable pointing to path));
And then loop through file data.
Note: You need to know the text file format in order to loop through the file content.
You might want to look at the newer class System.console that we got that faciliates easier console i/o. Your program shows attempt and if you study one or two good Java books you will beable to write this program error-free. Two good new Java books are the Sierra / Bates OCJP study guide and the new A Press Java 7 book. I recommend you take a read or two from one or two of these books and you will learn how to use ? System.console for console i/o.
System.out.print("Enter something:");
String input = System.console().readLine();
Can anyone please help me with the code as how to read multiple lines from console and store it in array list?
Example, my input from the console is:
12 abc place1
13 xyz place2
and I need this data in ArrayList.
So far I tried this code:
Scanner scanner = new Scanner(System.in);
ArrayList informationList = new ArrayList<ArrayList>();
String information = "";
int blockSize = 0, count = 1;
System.out.println("Enter block size");
blockSize = scanner.nextInt();
System.out.println("Enter the Information ");
while (scanner.hasNext() && blockSize >= count) {
scanner.useDelimiter("\t");
information = scanner.nextLine();
informationList.add(information);
count++;
}
Any help is greatly appreciated.
Input line from console is mix of string and integer
You've got a few problems.
First of all, the initialization line for your ArrayList is wrong. If you want a list of Object so you can hold both Integers and Strings, you need to put Object inside the angle braces. Also, you're best off adding the generic type argument to the variable definition instead of just on the object instantiation.
Next, your count is getting messed up because you're initializing it to 1 instead of 0. I'm assuming "block size" really means the number of rows here. If that's wrong leave a comment.
Next, you don't want to reset the delimiter your Scanner is using, and you certainly don't want to do it inside your loop. By default a Scanner will break up tokens based on any whitespace which I think is what you want since your data is delimited both by tabs and newlines.
Also, you don't need to check hasNext() in your while condition. All of the next*() methods will block waiting for input so the call to hasNext() is unnecessary.
Finally, you're not really leveraging the Scanner to do what it does best which is parse tokens into whatever type you want. I'm assuming here that every data line is going to start with a single integer and the be followed by two strings. If that's the case, just make a call to nextInt() followed by two calls to next() inside your loop and you'll get all the data parsed out into the data types you need automatically.
To summarize, here is your code updated with all my suggestions as well as some other bits to get it to run:
import java.util.ArrayList;
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<Object> list = new ArrayList<>();
System.out.println("Enter block size");
int blockSize = scanner.nextInt();
System.out.println("Enter data rows:");
int count = 0;
while (count < blockSize) {
list.add(scanner.nextInt());
list.add(scanner.next());
list.add(scanner.next());
count++;
}
System.out.println("\nThe data you entered is:");
System.out.println(list);
}
}