I am trying to populate an NxN matrix. What I'd like to do is be able to enter all the elements of a given row as one input. So, for example if I have a 4x4 matrix, for each row, I'd like to enter the 4 columns in one input, then print the matrix after each input showing the new values. I try to run the following code but I get an error that reads: Exception in thread "main" java.util.InputMismatchException. Here is my code:
double twoDm[][]= new double[4][4];
int i,j = 0;
Scanner scan = new Scanner(System.in).useDelimiter(",*");
for(i =0;i<4;i++){
for(j=0;j<4;j++){
System.out.print("Enter 4 numbers seperated by comma: ");
twoDm[i][j] = scan.nextDouble();
}
}
When I get the prompt to enter the 4 numbers I enter the following:
1,2,3,4
Then I get the error.
You should just do this;
double twoDm[][] = new double[4][4];
Scanner scan = new Scanner(System.in);
int i, j;
for (i = 0; i < 4; i++) {
System.out.print("Enter 4 numbers seperated by comma: ");
String[] line = scan.nextLine().split(",");
for (j = 0; j < 4; j++) {
twoDm[i][j] = Double.parseDouble(line[j]);
}
}
scan.close();
You should not forget to close the scanner too!
1 2 3 4 are not visible by Scanner as double numbers, but as integers.
So you have the following possibilities:
If you don't need a double use nextInt()
Write 1.0,2.0,3.0,4.0 instead of 1,2,3,4
Read the values as strings and convert them to double with Double.parseDouble()
I believe it would be easier to use string.split() , rather than .useDelimiter() , because when using delimiter , you would have to input the last number with a comma as well (since comma is the one delimiting stuffs) unless you create some regex to take both comma and \n as delimiter.
Also, you should give the prompt - System.out.print("Enter 4 numbers separated by comma: "); inside the outer loop, not the inner loop, since you would be taking in each row inside the outer loop, and only elements in each row in the inner loop.
You can do -
double twoDm[][]= new double[4][4];
int i,j = 0;
Scanner scan = new Scanner(System.in);
for(i =0;i<4;i++){
System.out.print("Enter 4 numbers separated by comma: ");
String row = scan.nextLine().split(",");
for(j=0;j<4;j++){
twoDm[i][j] = Double.parseDouble(row[j]);
}
}
Related
I am trying to read elements of a 2-d 3x3 matrix using a scanner.
The input would look something like this:
3
11 2 4
4 5 6
10 8 -12
I am current geting the error:
Scanner scan = new Scanner(System.in);
int a = scan.nextInt();
scan.next();
List<List<Integer>> array = new ArrayList<>();
for (int i = 0; i < a; i++) {
String number = scan.nextLine();
String[] arrRowItems1 = number.split(" ");
List<Integer> list = new ArrayList<>();
for (int j = 0; j < a; j++) {
int arrItem = Integer.parseInt(arrRowItems1[j]);
list.add(arrItem);
}
array.add(list);
}
scan.close();
How do I go about doing this problem, so that a the end a 2d 3x3 matrix array is constructed according to user input? Thank You.
Do the following:
Scanner scan = new Scanner(System.in);
int a = scan.nextInt();
scan.nextLine(); // change to nextLine
Your program works just fine the way it was written as long as you make the above change. However, I recommend you split on "\\s+" to allow any number of spaces between the numbers.
You could read the input line-by-line as a string, check it for validity, parse it and fill it in an int[][]-Matrix.
This way, the program keeps asking for input until it got three valid lines of numbers:
Scanner scan = new Scanner(System.in);
int dim = 3; //dimensions of the matrix
int line = 1; //we start with line 1
int[][] matrix = new int[dim][dim]; //the target matrix
while(line <= dim) {
System.out.print("Enter values for line " + line + ": "); //ask for line
String in = scan.nextLine(); //prompt for line
String[] nums; //declare line numbers array variable
//check input for validity
if (!in.matches("[\\-\\d\\s]+")
| (nums = in.trim().split("\\s")).length != dim) {
System.out.println("Invalid input!");
continue;
}
//fill line data into target matrix
for (int i = 0; i < nums.length; i++) {
matrix[line - 1][i] = Integer.parseInt(nums[i]);
}
line++; //next line
}
scan.close(); //close scanner (!)
//test output
for (int i = 0; i < matrix.length; i++) {
System.out.println(Arrays.toString(matrix[i]));
}
The last for-loop is only for printing the result, just to check if it works:
Enter values for line 1: 11 2 4
Enter values for line 2: 4 5 6
Enter values for line 3: 10 8 -12
[11, 2, 4]
[4, 5, 6]
[10, 8, -12]
BTW by changing the value for dim (dimension) you could even get a 5x5 or whatever matrix!
I hope this helped!
I'm trying to create a program which allows the user to addition as many pairs of numbers as they would like, by first taking user input to ask them how many sums they would like to complete (additions of 2 numbers), thereafter creating 2 arrays of whatever size the user has input, and then asking the user to input each pair of numbers on a single line that they would like to addition and storing the first value in one array and the second value in a second array from each input. This is where I am stuck, I don't know how I can take the user input as two int values on each line and store them in the respective indexes of each array to be added later. Please take a look at my code below:
import java.util.Scanner;
public class SumsInLoop {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the amount of sums you would like to calculate: ");
int n = sc.nextInt();
int a[] = new int[n];
int b[] = new int[n];
String[] input = new String[2];
System.out.println("Please enter the values you would like to sum as pairs of two numbers: ");
for (int i = 0; i < a.length; i++) {
input = sc.nextLine().split(" ");
int[] intinput = Arrays.asList(input).stream().mapToInt(Integer::parseInt).toArray();
a = intinput[0];
b = intinput[1];
}
}
I think you need to change 2 lines this way:
a[i] = intinput[0];
b[i] = intinput[1];
You're using nextLine() method, which is useful for string input, but it's not the best solution for integer or other primitive data.
In addition, this line of code is wrong :
a = intinput[0];
because you're storing an integer value as integer array.
You must store that value inside a[i] in order to respect the variables type.
I'd do it this way:
public class SumsInLoop {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the amount of sums you would like to calculate: ");
int n = sc.nextInt();
int a[] = new int[n];
int b[] = new int[n];
for (int i = 0; i < a.length; i++) {
System.out.println("Please enter the values you would like to sum as pairs of two numbers: ");
// Read pair and store it inside i-th position of a and b arrays
System.out.println("Enter first number: ");
a[i] = sc.nextInt();
System.out.println("Enter second number: ");
b[i] = sc.nextInt();
}
// Close scanner
sc.close();
// Prints every sum
for(int i = 0; i < a.length; i++){
System.out.println(i + "-th sum is: " + (a[i] + b[i]));
}
}
}
Here you read every pair with nextInt() which is specific for integer data.
Every time you store items in i-th position of arrays, so finally you can sum a[i] and b[i].
Result example:
Enter the amount of sums you would like to calculate:
4
Please enter the values you would like to sum as pairs of two numbers:
Enter first number:
2
Enter second number:
1
Please enter the values you would like to sum as pairs of two numbers:
Enter first number:
3
Enter second number:
4
Please enter the values you would like to sum as pairs of two numbers:
Enter first number:
5
Enter second number:
6
Please enter the values you would like to sum as pairs of two numbers:
Enter first number:
7
Enter second number:
8
0-th sum is: 3
1-th sum is: 7
2-th sum is: 11
3-th sum is: 15
Just read pairs with nextInt() method of scanner, it's use all space symbols like separator (not only end of line):
public class SumsInLoop {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the amount of sums you would like to calculate: ");
int n = sc.nextInt();
int a[] = new int[n];
int b[] = new int[n];
System.out.println("Please enter the values you would like to sum as pairs of two numbers: ");
for (int i = 0; i < a.length; i++) {
a[i] = sc.nextInt();
b[i] = sc.nextInt();
}
}
}
If I wanted to enter 10 numbers, and after each number it displays the square root, how would I do this using a for loop?
int number;
System.out.print("Enter a number: ");
num = input.nextInt();
for (count = 0; count <= 10; count++)
{
System.out.println("The Square of Number is : "+(num*num));
System.out.println("The Cube of Number is : "+(num*num*num));
I have tried this code. However, it displays 1 input 10 times. How do I get it to display after each input?
Similar to what others have said, you are only getting input once, and then printing the output 10 times. input.nextInt() must be moved inside the for loop.
However, something that hasn't been said is that you aren't consuming the newline delimeter. (Assuming you're using the console, which it seems you are) When the user inputs text by hitting enter, there is a newline delimeter at the end of the input. You are only consuming the number, but not the newline.
An example of this can be found here.
If you want to output the square root after you entered a number, just put num = input.nextInt(); inside the for-loop, as already mentioned.
If you however want to input the 10 numbers first and then output the squares of every number, this would be a pretty good solution:
int[] numbers = new int[10];
for(int i = 0; i < numbers.length; i++) numbers[i] = input.nextInt();
for(int tempInt : numbers) System.out.println(Math.pow(tempInt, 2));
Move num = input.nextInt() inside the for loop, like #Pavneet Singh said. If you want it to display all 10 after they have been entered, use an int[] with a length of 10 like this:
int[] numbers = new int[10];
I'm attempting to capture integers from a user input using Scanner. These integers represent coordinates and a radius between 0 and 1000. It's a circle on a 2D plane.
What I have to do is to somehow capture these integers separately from one line. So, for example, the user inputs
5 100 20
Therefore, the x-coordinate is 5, the y-coordinate is 100, and the radius is 20.
The user must input all of these values on the same line, and I have to somehow capture the values from the program into three different variables.
So, I tried using this:
Scanner input = new Scanner(System.in);
String coordAndRadius = input.nextLine();
int x = coordAndRadius.charAt(0); // x-coordinate of ship
int y = coordAndRadius.charAt(2); // y-coordinate of ship
int r = coordAndRadius.charAt(4); // radius of ship
for one-digit characters, as a test. Didn't turn out so well.
Any suggestions?
Well the easiest way (not the nicest one) is just split them into array using String methods :
public static void filesInFolder(String filename) {
Scanner input = new Scanner(System.in);
String coordAndRadius = input.nextLine();
String[] array = coordAndRadius.split(" ");
int x = Integer.valueOf(array[0]);
int y = Integer.valueOf(array[1]);
int r = Integer.valueOf(array[2]);
}
You can also use nextInt method, which looks like this :
public static void filesInFolder(String filename) {
Scanner input = new Scanner(System.in);
int[] data = new int[3];
for (int i = 0; i < data.length; i++) {
data[i] = input.nextInt();
}
}
Your input will be stored in array data
Create a string array using coordAndRadius.split(" "); and extract the values from each array element.
You must split the input into 3 different string variables, each of which can be parsed separately. Use the split method to return an array, with each element containing a piece of input.
String[] fields = coordAndRadius.split(" "); // Split by space
Then you can parse each piece into an int using Integer.parseInt:
int x = Integer.parseInt(fields[0]);
// likewise for y and r
Just make sure you have 3 elements in your array before accessing it.
try this:
Scanner scanner = new Scanner(System.in);
System.out.println("Provide x, y and radius,");
int x = scanner.nextInt();
int y = scanner.nextInt();
int radius = scanner.nextInt();
System.out.println("Your x:"+x+" y: "+y+" radius:"+radius);
It will work either you will type in "10 20 24" or "10\n20\n24" where \n is of course a newline character.
And just in case you would like to know why your approach does not work here is explanation.
int x = coordAndRadius.charAt(0);
charAt(0) return first character of your string which then gets implicitly casted into int. Assume your coordAndRadius ="10 20 24". So in this case first char is '1'. So the statement above can be written as:
int x = (int)'1';
Split the values by space
String[] values = coordAndRadius.split(" ");
Then get each value as int using Integer.parseInt:
int x = Integer.parseInt(values[0]);
int y = Integer.parseInt(values[1]);
int radious = Integer.parseInt(values[2]);
I'm trying to shift the user number input from right to left. It seems to be working except for not registering the first number. I think because for the reverse portion I have count is 1. I've tried using 0 and vice verse, but it results in an error. Any ideas on how to shift the user numbers?
The desired output is the reverse of what the user inputs. Example: User inputs 3 numbers. 3.0 2.0 1.0. Reverse 1.0. 2.0. 3.0.
// import Scanner
import java.util.Scanner;
public class Arrays {
public static void main (String [] args){
int count=0;
//introduce Scanner
Scanner input = new Scanner(System.in);
//printout question asking for user input and use count as input variable
System.out.println("Please input the size of array");
count=input.nextInt();
//create array and connect count to it
double[] numbers = new double [count];
System.out.println("Please input "+ numbers.length+ " double numbers");
//create for loop for original number order
for ( count=0; count<numbers.length; count++){
numbers[count] = input.nextDouble();
System.out.print( +numbers[count] + " ");
}
//print out the reverse order
System.out.print("\n After Reverse Order " );
//create for loop for reversed number order
for (count = 1; count< numbers.length; count++){
numbers[count-1]=numbers[count];
System.out.println ( "\n"+ numbers[count] );
}
}
}
If you want to reverse the order of elements, that's REVERSE ORDER not SHIFT. "Shift" correctly would shift them all one to the right or left, either dropping the end element or or (possibly) rotating it round to the other end.
So first thing is, to know what you're actually talking about.
Reversing the order of integers in an array:
int i = 0;
int j = numbers.length - 1; // corresponding index at opposite end of array.
// stop when half the array has been swapped.. with the other half.
while (i < j) {
// swap between ends.
int swap = numbers[i];
numbers[i] = numbers[j];
numbers[j] = swap;
// advance indices.
i++; j--;
}
Try this:
Double[] numbers = new Double[count];
...
Collections.reverse(Arrays.asList(numbers));