So, I want to ask the user to input three values (all double) with only one prompt and have them stored in an array (I just started getting familiar with creating objects and arrays). This is what I've got so far:
import java.util.Scanner;
final int ARRAY_LIMIT=3;
Scanner input=new Scanner(System.in);
System.out.println("Enter the points and speed: ");
double entryVal=input.nextDouble();
double[] array=new double[ARRAY_LIMIT];
for(int entriesCounter=0; entriesCounter<array.length; entriesCounter++)
{
array[entriesCounter]=entryVal;
if(array[2]==0)
break;
}
So when I try to run it and I input something like 1.0, 1.0, 10.0, but I get all sorts of code spewed out. The point is to input all 3 values at the same time, eventually use these values in separate equations and terminate if the third number is 0. But I want to first be able to get these values to be stored correctly. I've tried to look at other previously answered questions but couldn't find something that helped me. I'm very new to Java so I'm still bumbling about. Any detailed help would be greatly appreciated.
The best way I think is just read the whole line to String :
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the points and speed: ");
String entryVal = input.nextLine();
String[] stringArray = entryVal.split(" ");
double[] array = new double[stringArray.length];
for (int i = 0; i < array.length; i++) {
array[i] = Double.valueOf(stringArray[i]);
}
}
Note that each value has to be seperated only by space.
Related
The user needs to enter a certain number of integers. Rather them enter an integer at a time, I want to make it so they can enter multiple integers on a single line, then I want those integers to be converted in an array. For example, if the user enters: 56 83 12 99 then I want an array to be created that is {56, 83, 12, 99}
In other languages like Python or Ruby I would use a .split(" ") method to achieve this. No such thing exist in Java to my knowledge. Any advice on how to accept user input and create an array based on that, all on a single line?
Using the Scanner.nextInt() method would do the trick:
Input:
56 83 12 99
Code:
import java.util.Scanner;
class Example
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int[] numbers = new int[4];
for(int i = 0; i < 4; ++i) {
numbers[i] = sc.nextInt();
}
}
}
At #user1803551's request on how Scanner.hasNext() can achieve this:
import java.util.*;
class Example2
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
ArrayList<Integer> numbers = new ArrayList<Integer>();
while (sc.hasNextInt()) { // this loop breaks there is no more int input.
numbers.add(sc.nextInt());
}
}
}
The answer by Makoto does what you want using Scanner#nextLine and String#split. The answer by mauris uses Scanner#nextInt and works if you are willing to change your input requirement such that the last entry is not an integer. I would like to show how to get Scanner#nextLine to work with the exact input condition you gave. Albeit not as practical, it does have educational value.
public static void main(String[] args) {
// Preparation
List<Integer> numbers = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
System.out.println("Enter numbers:");
// Get the input
while (scanner.hasNextInt())
numbers.add(scanner.nextInt());
// Convert the list to an array and print it
Integer[] input = numbers.toArray(new Integer[0]);
System.out.println(Arrays.toString(input));
}
When giving the input 10 11 12 upon first prompt, the program stores them (Scanner has a private buffer), but then keeps asking for more input. This might be confusing since we give 3 integers which loop through hasNext and expect that when the 4th call is made there will be no integer and the loop will break.
To understand it we need to look at the documentation:
Both hasNext and next methods [and their primitive-type companion methods] may block waiting for further input. Whether a hasNext method blocks has no connection to whether or not its associated next method will block.
(emphasis mine) and hasNextInt
Returns: true if and only if this scanner's next token is a valid int value
What happens is that we initialized scanner with an InputStream, which is a continuous stream of data. On the 4th call to hasNextInt, the scanner "does not know" if there is a next int or not because the stream is still open and data is expected to come. To conclude from the documentation, we can say that hasNextInt
Returns true if this scanner's next token is a valid int value, returns false if it is not a valid int, and blocks if it does not know what the next token is.
So what we need to do is close the stream after we got the input:
// Get the input
numbers.add(scanner.nextInt());
System.in.close();
while (scanner.hasNextInt())
numbers.add(scanner.nextInt());
This time we ask for the input, get all of it, close the stream to inform scanner that hasNextInt does not need to wait for more input, and store it through iteration. The only problem here is that we closed System.in, but if we don't need more input it's fine.
String#split exists, but you have to do more work, since you're only getting strings back.
Once you've got the split, convert each element into an int, and place it into the desired array.
final String intLine = input.nextLine();
final String[] splitIntLine = intLine.split(" ");
final int[] arr = new int[splitIntLine.length];
for(int i = 0; i < splitIntLine.length; i++) {
arr[i] = Integer.parseInt(splitIntLine[i]);
}
System.out.println(Arrays.toString(arr)); // prints contents of your array
Scanner scan2= new Scanner(System.in);
ArrayList l2=new ArrayList();
System.out.print("How many numbers do you want in your list: ");
int numbers=scan2.nextInt();
while(numbers!=0){
int age=scan2.nextInt();
l2.add(age);
numbers-=1;
}
System.println(l2);
I am trying to write a small program dealing the earthquakes and magnitudes.
When the program is run, it asks the user to input a number for how many earthquakes the user wants to submit magnitudes for. Depending on the response, the program then prompts the user to enter a magnitude for each earthquake. I have written the following code below but am having trouble with the for loop.
Obviously in the for loop, putting i <= numberOfEarthquakes disallows the program from compiling correctly. What is a simple way to give i a condition that correlates to the inputted number from the user. Much thanks.
(this is a smaller part of a larger program that I am hoping to write)
import java.util.*;
public class Earthquakes {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("How many magnitudes will you enter? ");
String numberOfEarthquakes = console.next();
for (int i = 1; i <= numberOfEarthquakes; i++) {
System.out.print("Enter magnitude for earthquake " + i);
String magnitudeOfEarthquake = console.next();
}
}
}
Make this String numberOfEarthquakes = console.next(); to int numberOfEarthquakes = console.nextInt();
You can not compare String with int.
Convert your numberOfEarthquakes from String to Integer. Use Integer.parseInt(numberOfEarthquakes) to convert String to Intger.
Any possible way to keep entering numbers, and when the same number is entered 2 or more times an error message arises or something like that? I need this to be answered in Java only. I'm new and I don't know where to go from here. I need help searching values in the array and then printing out all the numbers that have been entered.
public class Test
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.println("How big is the group?: ");
int[] group = new int[input.nextInt()];
for (int i = 0; i < group.length; i++)
{
System.out.println("Please enter number: ");
group[i] = input.nextInt();
}
I think this is what you're looking for. Inside of the for loop, there's a while loop spinning to keep collecting new ints until you enter one that's not already in the list.
for (int i = 0; i < group.length; i++)
{
System.out.println("Please enter number: ");
int next = input.nextInt();
while(Arrays.asList(group).contains(next)) { // Keep asking for new input while the input is already in list
System.out.println("That number is already in the group ... try again.");
next = input.nextInt();
}
group[i] = next;
}
Since this is clearly a "learning exercise", it is only appropriate to give you hints:
You can search an array by stepping through the array indexes and testing the elements at each index.
A method and a class both need a closing } ...
I need this to be answered in Java only.
That is incorrect. What you REALLY need is some hints. If we give you Java code, you miss out on the important learning experience of writing it yourself. And THAT is the WHOLE POINT of the homework. Go ask your teacher if you don't believe me.
Scanner input = new Scanner(System.in);
System.out.println("Enter matrix 1: ");
for(int row=0;row<3;row++){
for(int col=0;col<3;col++){
a[row][col]=input.nextDouble();
}
}
Hi there - Given the above solution to entry of data into a 2d 3*3 array called a, I'm currently unable to take user input. The intellij ide won't accept any input that I can see at the point of input.nextDouble().
I guess I'm missing something obvious but what ? :)
The below code works perfectly for me
double a[][]=new double[3][3];
Scanner input = new Scanner(System.in);
for(int row=0;row<3;row++){
for(int col=0;col<3;col++){
System.out.println("Enter value: ");
a[row][col]=input.nextDouble();
}
}
It's JUNIT4 not taking console input - that's why changing focus to the console produces no result.
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);
}
}