How to use java.util.Scanner class to read input? - java

I have a question about using java.util.Scanner class to read input.
Below is my coding without using java.util.Scanner class to read input:
public class NewTry {
public static float[][] clone(float[][] a) throws Exception {
float b[][] = new float[a.length][a[0].length];
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++) {
b[i][j] = a[i][j];
}
}
return b;
}
public static void main(String args[]) {
float[][] a = new float[][] { { 1.513f, 2.321f, 3.421f }, { 4.213f, 5.432f, 6.123f },
{ 7.214f, 8.213f, 9.213f } };
try {
float b[][] = clone(a);
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++) {
System.out.print(b[i][j] + " ");
}
System.out.println();
}
} catch (Exception e) {
System.out.println("Error!!!");
}
}
}
Show output without using java.util.Scanner:
run:
1.513 2.321 3.421
4.213 5.432 6.123
7.214 8.213 9.213
BUILD SUCCESSFUL (total time: 3 seconds)
My problem is how to add java.util.Scanner class to read input without default float number in the coding? Is using array run scanner?
Actually I want the sample output same like the below (the float number must key in myself):
run:
Type nine float numbers two-dimensional array of similar type and size with line breaks, end
by"-1":
1.513
2.321
3.421
4.213
5.432
6.123
7.214
8.213
9.213
-1
The result is:
1.513 2.321 3.421
4.213 5.432 6.123
7.214 8.213 9.213
BUILD SUCCESSFUL (total time: 11 second)
Hope someone can guide me or modified my coding to add java.util.Scanner class to read input .Thanks.

Check this out
public static void main(String args[]) {
Scanner sc = new Scanner (System.in);
System.out.println ("Type nine float numbers two-dimensional array of similar type and size with line breaks, end by -1:");
float[][] a = new float[3][3];
for (int i=0; i<3; i++){
for (int j=0; j<3; j++){
String line = sc.nextLine();
if ("-1".equals(line)){
break;
}
a[i][j]=Float.parseFloat(line);
}
}
System.out.println("\n The result is:");
try {
float b[][] = clone(a);
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++) {
System.out.print(b[i][j] + " ");
}
System.out.println();
}
} catch (Exception e) {
System.out.println("Error!!!");
}
}
You should define a new Scanner (sc) and then loop 3 x 3 times until you read all input.
If the user enters -1 the loop ends. Note that you do not need to exit when 9 numbers are entered.
Also each user input is read as a line and not as a token, and then is parsed into a Float. If the user enters a String that is not a float number then it throws an Exception.
Sample:
Type nine float numbers two-dimensional array of similar type and size with line breaks, end by -1:
1.1
1.2
1.3
2.1
2.2
2.3
3.1
3.2
3.3
The result is:
1.1 1.2 1.3
2.1 2.2 2.3
3.1 3.2 3.3

Scanner scan =new Scanner(System.in);
float[][] a = new float[3][3];
for(int i =0 ;i<3;i++) {
for(int j=0; j<3; i++) {
a[i][j] =scan.Float();
}
}

Related

create two dimensional array that can store integer values inside, and square them in different method and print them in another method

Complete question is: Create a program that uses a two dimensional array that can store integer values inside. (Just create an array with your own defined rows and columns). Make a method called Square, which gets each of the value inside the array and squares it. Make another method called ShowNumbers which shows the squared numbers.
What I attempted thou it has errors:
public class SquareMatrix {
public static void main(String[] args) {
int sqr[][]= {{1,3,5},{2,4,6}};
System.out.println("Your Original Matrix: ");
for(int i = 0; i < 2; i++){
for(int j = 0; j < 3; j++){
System.out.print(sqr[i][j] + " ");
}
System.out.println();
}
Square();
ShowNumbers();
}
static void Square(){
for(int i = 0; i <= 1; i++) {
for(int j = 0; j <= 2; j++) {
sqr[i][j] = sqr[i][j] * sqr[i][j];
}
}
}
static void ShowNumbers(){
System.out.println("Matrix after changes: ");
for(int i = 0; i < 2; i++){
for(int j = 0; j < 3; j++){
System.out.print(sqr[i][j] + " ");
}
System.out.println();
}
}
}
Also how would I write it if I wanted an input from the user for the col and row for a specific range of 0 to 10, I made an alternative version with many errors below. Below code is not as important as the one above
import java.util.Scanner;
public class MyClass {
public static void main(String args[]) {
int row, col, i, j;
int arr[][] = new int[10][10];
Scanner scan = new Scanner(System.in);
try{
System.out.print("Enter Number of Row for Array (max 10) : ");
row = scan.nextInt();
System.out.print("Enter Number of Column for Array (max 10) : ");
col = scan.nextInt();
if(0>=row && row<=10 || 0>=col && col<=10 ){
}
}
catch (Exception e){
System.out.println("(!) Wrong input...\n");
}
System.out.print("Enter " +(row*col)+ " Array Elements : ");
for(i=0; i<row; i++){
for(j=0; j<col; j++){
arr[i][j] = scan.nextInt();
}
}
}
static void square(){
arr[row][col] = arr[row][col] * arr[row][col];
}
static void ShowNumbers(){
System.out.print("The Array is :\n");
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
{
System.out.print(arr[i][j]+ " ");
}
System.out.println();
}}}
PS I am new to java and would appreciate a response with the whole code pasted not just a section of the code so I don't get lost or with the number of the line the error is from.
thanks for any help
Since you are starting from scratch, it would be good to go over the basics of the language again. Take a look at oracle classvars For your upper problem you need to understand the difference between local and instance variables and the difference between static and non static variables respectively. To solve your issue just move the declaration of your array out of the main method and add a static modifier:
public class SquareMatrix {
static int sqr[][] = {{1, 3, 5}, {2, 4, 6}};
public static void main(String[] args) {
//rest of your code
}

How to read int numbers (matrix) from file.txt and add to array?

I want to multiply two matrices. I have 2 files with 2 different integers (matrices).
file1.txt
4 3 4 6
-1 10 4 -1
4 7 2 -8
file2.txt
3 0 0
0 3 0
0 0 3
0 2 4
How can I read these files separately into a two-dimensional array, so that it is convenient to multiply. I've a code where the size of the matrix is indicated at the beginning, but what if there could be different size of matrices? Here is my code with given size:
public static void main(String[] args) throws IOException {
try {
Scanner input = new Scanner(new File(file1.txt));
int m = 3; // I need the size for random matrix
int n = 5; // I need the size for random matrix
int[][] a = new int[m][n];
while (input.hasNextLine()) {
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
try{
a[i][j] = input.nextInt();
System.out.println("number is "+ a[i][j]);
}
catch (java.util.NoSuchElementException e) {
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
It would be better to implement a separate method reading a file into matrix if the dimensions of the matrix are known:
public static int[][] readFileWithMatrix(String filename, int rows, int cols) throws Exception {
int[][] arr = new int[rows][cols];
try (Scanner input = new Scanner(new File(filename))) { // use try-with-resources to close Scanner
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
arr[i][j] = input.nextInt();
}
}
}
return arr;
}
Then it would be simpler to use this method:
int[][] arr3x4 = readFileWithMatrix("file1.txt", 3, 4);
int[][] arr4x3 = readFileWithMatrix("file2.txt", 4, 3);
//... do matrix multiplication
Here try the following code which takes all the input from file assuming that it contains only the matrix elements and store it into a dynamic 2D array a e.g., list of list. First I read the first line of the file and take out all the numbers from it which gives me the total number of columns of the matrix. Next I keep on reading the input lines until the end of file which expands the row of the matrix a
public static void main(String[] args) throws IOException {
try {
Scanner input = new Scanner(new File(file1.txt));
List<ArrayList<Integer>> a = new ArrayList<ArrayList<Integer>>();
int row=0;
String cols[] = input.nextLine().split(" ");
a.add(row, new ArrayList<Integer>());
for (int j = 0; j < cols.length; j++) {
try {
a.get(row).add(Integer.parseInt(cols[j]));
} catch (Exception e) {
}
}
row++;
while (input.hasNextLine()) {
a.add(row, new ArrayList<Integer>());
for (int j = 0; j < cols.length; j++) {
try {
a.get(row).add(input.nextInt());
} catch (java.util.NoSuchElementException e) {
}
}
row++;
}
System.out.println("Rows: "+row+" Columns: "+cols.length);
for (int i = 0; i < a.size(); i++) {
for (int j = 0; j < a.get(i).size(); j++) {
System.out.println("Number is "+ a.get(i).get(j));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
Demo code in here: https://ideone.com/ZEcgPR#stdin

How stop array input limit then the result to show the output?

I have a question about stop array input limit then the result to show the output.
Below is my coding have already set new float[3][3]:
import java.util.Scanner;
public class Clone2Darray {
public static float[][] clone(float[][] a) throws Exception {
float b[][] = new float[a.length][a[0].length];
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++) {
b[i][j] = a[i][j];
}
}
return b;
}
public static void main(String args[]) {
Scanner sc = new Scanner (System.in);
System.out.println ("Type nine float numbers two-dimensional array of similar type and size with line breaks, end by -1:");
float[][] a = new float[3][3];
for (int i=0; i<3; i++){
for (int j=0; j<3; j++){
String line = sc.nextLine();
if ("-1".equals(line)){
break;
}
a[i][j]=Float.parseFloat(line);
}
}
System.out.println("\n The result is:");
try {
float b[][] = clone(a);
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++) {
System.out.print(b[i][j] + " ");
}
System.out.println();
}
} catch (Exception e) {
System.out.println("Error!!!");
}
}
}
The limit output is show me like below:
run:
Type float numbers in the two-dimensional array of similar type and size
with line breaks, end by -1:
5.33
9.33
63.33
6.36
3.55
7.25
2.33
3.66
The result is:
6.33 5.33 9.33
63.33 6.36 3.55
7.25 2.33 3.66
BUILD SUCCESSFUL (total time: 31 seconds)
My problem is want to stop limit float[3][3] and can unlimited key in the input until type -1 to stop the input. May I know how to remove the limit float[3][3] in the array? Hope anyone can guide me to solve my problem. Thanks.
At the point when you allocate memory for the two-dimensional array you have to tell the sizes of its elements, because memory will be allocated for that array and the amount of memory to be allocated must be known.
You can bypass this, by using some more dynamic types, like List and its popuplar implementation, ArrayList, even in a nested form. That's a nice thing to do, but then you will not have a "real" array.
The below code allows you to create the dynamic arrays.
import java.util.Scanner;
public class Clone2DArray {
public static float[][] clone(float[][] a) throws Exception {
float b[][] = new float[a.length][a[0].length];
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++) {
b[i][j] = a[i][j];
}
}
return b;
}
public static void main(String args[]) {
Scanner sc = new Scanner (System.in);
System.out.println("enter row size");
int row = Integer.parseInt(sc.nextLine());
System.out.println("enter column size");
int column = Integer.parseInt( sc.nextLine());
System.out.println ("Type float numbers two-dimensional array of similar type and size with line breaks:");
float[][] a = new float[row][column];
for (int i=0; i<row; i++){
for (int j=0; j<column; j++){
String line = sc.nextLine();
if ("-1".equals(line)){
break;
}
a[i][j]=Float.parseFloat(line);
}
}
System.out.println("\n The result is:");
try {
float b[][] = clone(a);
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++) {
System.out.print(b[i][j] + " ");
}
System.out.println();
}
} catch (Exception e) {
System.out.println("Error!!!");
}
}
}

Printing pattern a pattern in java [duplicate]

This question already has answers here:
Java algorithm to make a straight pyramid [closed]
(4 answers)
How to print this pyramid pattern?
(5 answers)
Logic behind printing pyramid shape using nested for loops in Java
(1 answer)
What is a debugger and how can it help me diagnose problems?
(2 answers)
Closed 4 years ago.
I tried to print the below pattern in java
***1***
**2*2**
*3*3*3*
4*4*4*4
like this way
public class Sample {
public static void main(String[] args) {
int m, n;
Scanner s = new Scanner(System.in);
System.out.println("Enter the no of rows");
m = s.nextInt();
System.out.println("Enter the no of columns");
n = s.nextInt();
s.close();
//Printing the number of rows
for (int i = 1; i <= m; i++) {
//printing number of columns
for (int j = n; j > 0; j--) {
//Printing values in the pattern
for (int k = 0; k < j; k++) {
if (k == j / 2)
System.out.print(i);
}
System.out.print("*");
}
System.out.print("\n");
}
}
}
I am facing problem at the logic of finding the positions to print the values in each row. Its asked at my previous interview.
Try to figure out a formula when the asterisk(*) is replaced with number.
Hint1: the formula depends on the distance of the given symbol from the middle of the row
Hint2: the formula depends on the remainder modulo 2 of the position in the current row(and the number of the row too)
The formula is simple enough if you note the two dependencies I mention above.
we can write logic based on the output. Right now you are passing the value row = 4 and column =7. For that you have provided output. Based on that I have written this program, which output matching with that, we can modify/tune this program also:
import java.util.Scanner;
public class Sample {
public static void main(String[] args) {
int m, n;
Scanner s = new Scanner(System.in);
System.out.println("Enter the no of rows");
m = s.nextInt();
System.out.println("Enter the no of columns");
n = s.nextInt();
s.close();
String[][] str = new String[m][n];
int frontPos = 0;
int backPos = n-1;
for (int i=0; i<m; i++){
int l = Math.round((n)/(i+2));
if(i==(m-1)){
frontPos = 0;
backPos = n-1;
} else {
frontPos = l;
backPos = n-1-l;
}
//System.out.println("Difference =="+frontPos);
boolean contFlag = false;
do{
//System.out.println("frontPos=="+frontPos+"|backPos=="+backPos);
if(frontPos == backPos){
str[i][frontPos] = new Integer(i+1).toString();
} else if(frontPos < backPos){
str[i][frontPos] = new Integer(i+1).toString();
str[i][backPos] = new Integer(i+1).toString();
}
if((backPos-frontPos) > l){
contFlag = true;
frontPos = frontPos + (l+1);
backPos = backPos -(l+1);
} else {
contFlag = false;
}
} while(contFlag);
//System.out.print("\n");
}
for(int a=0; a<m; a++){
for(int b=0; b<n; b++){
if(str[a][b]==null){
System.out.print("*");
} else {
System.out.print(str[a][b]);
}
}
System.out.print("\n");
}
}
}

Adjacency Matrix java

User enters a text file at command-line and my prog. will take the text, create an array with the number of rows (vertices) of the first number showed, then fill the 2d array with the remaining numbers. Finally it will display if # connects to # display T, else display F. I haven't completed it, and am stuck on it just filling the array and displaying the numbers in the array.
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class AdjMatrix {
public static void main(String[] args) {
//ArrayList<Integer> list = new ArrayList<Integer>(); //Arraylist to store all integers in the array
//int n = 0; //Vertices
final int COLS = 2; //Number of columns
int[][] array = null;
int lineNumber = 0;
String line = "";
if(args.length > 0)
{
try
{
java.io.File file = new java.io.File(args[0]);
Scanner in = new Scanner(file);
//Reading the file
while(in.hasNext())
{
line = in.next();
lineNumber++;
if(lineNumber == 1)
{
//n = Integer.parseInt(line);
array = new int[Integer.parseInt(line)][COLS];
System.out.println(Integer.parseInt(line));
}
else
{
String[] tokens = line.split(",");
for(int x = 0; x < tokens.length; ++x)
for(int j = 0; j < tokens.length; ++j)
{
array[x][j] = Integer.parseInt(tokens[x]);
}
}
}
in.close();
}//End try
catch(FileNotFoundException e)
{
System.err.println("File was either not found or it does not exist.");
System.out.printf("\n");
}//End catch
}//End Commandline param entry
for(int i = 0; i < array.length; i++)
for(int j = 0; j < array.length; j++)
System.out.println(" " + array[i][j]);
}
}
I put in System.out.println(Integer.parseInt(line)); to see if it grabs the number and puts it in the rows # for the array, that's successful. Any help is appreciated. Been on it for a good while and any assistance is appreciated.
EDIT
Sorry, forgot to add the input file.
integer.txt
9
1,2
2,6
6,2
5,1
6,5
3,2
6,3
3,7
8,7
9,9
9 being the number that establishes the # of rows. Then the program grabs all numbers after 9
It looks like you're initializing a firstLine by 2 dimension array,
array = new int[Integer.parseInt(line)][COLS];
but you're trying to fill it with line.length by line.length elements.
for(int x = 0; x < tokens.length; ++x)
for(int j = 0; j < tokens.length; ++j)
{
array[x][j] = Integer.parseInt(tokens[x]);
}
This seems like a bug, but without seeing a sample file, I can't say for sure.

Categories

Resources