I just started learning this language and I have a problem trying to create a Matrix of type char from user input.
For example I want to read this as my input:
3 // this is an int n that will give me a square matrix[n][n]
.#.
###
.#.
For this example, this is what I have:
//...
Scanner stdin = new Scanner(System.in);
int n = stdin.nextInt();
char[][] matrix = new char[n][n]
for(int i = 0; i < n; i++){
matrix = stdin.nextLine();
}
Obviously this is wrong, and I know that. I'm just not seeing a way to correctly read this input.
If anyone could help me I would appreciate it.
ps: if possible, keep it simple, because like I said, I just started learning java :)
First, you need to add stdin.nextLine(); after reading n to skip the new line character.
Second, this is what you need inside your loop:
matrix[i] = stdin.nextLine().toCharArray();
This reads next line and converts it to an array of chars.
This is a runnable version of your question with output
import javafx.application.Application;
import javafx.stage.Stage;
import java.util.Arrays;
import java.util.Scanner;
public class MainNoFXML extends Application {
#Override
public void start(Stage stage) {
System.out.println("Enter Matrix Size:");
Scanner stdin = new Scanner(System.in);
int n = stdin.nextInt();
char[][] matrix = new char[n][n];
stdin.nextLine();
for(int i = 0; i < n; i++) {
System.out.println("Enter "+n+" Number of Chars");
System.arraycopy(stdin.nextLine().toCharArray(), 0, matrix[i], 0, n);
}
System.out.println("\nYour Matrix:");
for(int i = 0; i < n; i++)
System.out.println(Arrays.toString(matrix[i]));
}
public static void main(String[] args) { launch(args); }
}
Output:
Enter Matrix Size:
3
Enter 3 Number of Chars
.#.
Enter 3 Number of Chars
###
Enter 3 Number of Chars
.#.
Your Matrix:
[., #, .]
[#, #, #]
[., #, .]
First of all, thank you for all your answers.
I emailed my teacher and this was the solution he gave to me, if anyone is wondering:
Scanner stdin = new Scanner(System.in);
int n = stdin.nextInt();
stdin.nextLine();
char[][] matrix = new char[n][n]
for(int i = 0; i < n; i++){
String line = stdin.nextLine();
for(int j = 0; i < n; j++){
matrix[i][j] = line.charAt(j);
}
}
see code sample:
public class MatInput {
public static void main(String[] args) {
int matX = 3;
int matY = 3;
String matrix [][]=new String[matX ][matY];
Scanner input = new Scanner(System.in);
System.out.println("enter the strings for the Matrix");
for(int row=0;row<matX;row++){
for(int col=0;col<matY;col++){
matrix[row][col]=input.nextLine();
}
System.out.println("");
}
for(int r=0;r<matrix.length; r++) {
for (int c=0; c<matrix [r].length; c++) {
System.out.print(matrix [r][c] + " ");
}
System.out.println("");
}
input.close();
}
}
Related
This question already has answers here:
Printing with delimiter only between values
(3 answers)
Closed 2 years ago.
I was tasked to do a looping problem for Java, but I'm currently having a problem on how to display a factorial of a number. For example, 1x2x3x4x5 = 120.
I'm almost there, but I can't seem to figure out how to, or is there any possible way to display the factorial of a number because there is always an additional "x" at the end of the 5.
Here is my code:
import java.util.*;
public class trylangpo2 {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
int fctr;
System.out.println ("number");
fctr = input.nextInt();
for (int i = 1; i <=fctr; i++){
System.out.print(i);
int j;
for (j =1; j <=1 ; j++){
System.out.print("*");
}
}
}
}
Example output:
1x2x3x4x5x
Your loop for (j =1; j <=1 ; j++) can be removed. It only loops once so, just write System.out.print("*"). No loop required
Then if you think about it, you want to print the number and the * all the time, except when it is the last number (fctr)
So write it that way:
Scanner input = new Scanner (System.in);
int fctr;
System.out.println ("number");
fctr = input.nextInt();
for (int i = 1; i <=fctr; i++){
System.out.print(i);
if(i<fctr) {
System.out.print("*");
}
}
Try to add a condition if it’s not at the end of the loop. Then add start and if it’s the end, then just print the number:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int fctr;
System.out.println("number");
fctr = input.nextInt();
for (int i = 1; i <= fctr; i++) {
if (i < fctr) {
System.out.print(i + " * ");
} else {
System.out.print(i);
}
}
}
I always use a construct like
String sep="";
for (...) {
System.out.print(sep);
System.out.print(payload);
sep="x";
}
You need to make the printing of ***** condition. Don't print ***** if i == fctr. And you don't need that additional loop of j. As below :
public static void main(final String[] args) {
final Scanner input = new Scanner(System.in);
int fctr;
System.out.println("number");
fctr = input.nextInt();
// IntStream.range(1, fctr).
long factorial = 1;
for (int i = 1; i <= fctr; i++) {
factorial = factorial * i;
if (i == fctr) {
System.out.print(i);
} else {
System.out.print(i + "*");
}
}
System.out.print("=" + factorial);
}
I am trying to create a program that takes a user's answer for a test and puts it in a char array, and then compares it to an array with the answers.
I have a problem with input the user's Answers into the char array. I keep getting an EE saying that in.nextLine(); - there is no line found and it throws a no such element exception.
import java.util.Scanner;
public class driverExam {
public static void main(String[] args) {
System.out.println("Driver's Test. Input your answers for the following
10 Q's. ");
System.out.println();
char[] testAnswers = {'B','D','A','A','C','A','B','A','C','D'};
int uA =9;
String userInput;
for (int i =0; i<uA;i++) {
Scanner in = new Scanner(System.in);
System.out.print("Question #"+(i+1)+": ");
userInput = in.nextLine();
in.close();
int len = userInput.length();
char[] userAnswers = new char [len];
for(int x =0;x<len;x++) {
userAnswers[i] = userInput.toUpperCase().charAt(i);
}
System.out.println(userAnswers);
}
System.out.println("Your answers have been recorded.");
System.out.println();
}
}
Shouldn't userAnswers array be of size 10?
Your program has quite redundant and unnecessary steps, according to me. So I have modified it to meet your need.
There is no need to put the "Scanner in...." inside the loop.
This loop is full of mistakes. Not discouraging, just saying.
for (int i =0; i<uA;i++)
{
Scanner in = new Scanner(System.in);//scanner inside loop
System.out.print("Question #"+(i+1)+": ");
userInput = in.nextLine();
in.close();//already mentioned by someone in the comment
int len = userInput.length();
char[] userAnswers = new char [len];//no need to declare array inside loop
for(int x =0;x<len;x++)
{
userAnswers[i] = userInput.toUpperCase().charAt(i);
}
}
System.out.println(userAnswers);//this will not print the array,it will print
//something like [I#8428 ,[ denotes 1D array,I integer,and the rest of it has
//some meaning too
Now here is the code which will get the work done
char[] testAnswers = {'B','D','A','A','C','A','B','A','C','D'};
int uA =testAnswers.length;//to find the length of testAnswers array i.e. 10
char[] userAnswers = new char [uA];
char userInput;
int i;
Scanner in = new Scanner(System.in);
for (i =0; i<uA;i++)
{
System.out.print("Question #"+(i+1)+": ");
userInput = Character.toUpperCase(in.next().charAt(0));
}
for(i=0;i<ua;i++)
{
System.out.println(userAnswers[i]);
}
System.out.println("Data has been recorded");
I am not demeaning, just trying to help.
I'm doing a task in which I am told to check for the '-'s in sample data, when a - is found in the data and there are adjacent dashes within the hashes, this only counts for 1 occurrence, e.g. in this sample data the answer would be 4.
I started by creating a 2D array to populate it then I was going to check for the dashes in the array but I am a bit puzzled as to how I would go about actually counting the occurrences, Any help would be appreciated.
Here's what I have so far;
Scanner input = new Scanner(System.in);
int a = input.nextInt(); //no. of rows
int b = input.nextInt(); //no. of columns
String arr[][] = new String[a][b]; //array of strings of 10 x 20
for(int i = 0; i<a; i++){
for(int j = 0; j<b; j++){
arr[i][j] = input.next();
}
}
//for test purposes
for(String[] s : arr){
for(String e : s){
System.out.print(e);
}
}
Here's the sample input:
10 20
#################---
##-###############--
#---################
##-#################
########---#########
#######-----########
########---#########
##################--
#################---
##################-#
Simplest way to use regex. Consider each row as string, trim string and then allow only 20 characters in string(based on your column count).
Other approaches could be to use DSL algos.
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class test {
public static void main(String... args) throws Exception {
Scanner input = new Scanner(System.in);
int a = input.nextInt(); // no. of rows
int b = input.nextInt(); // no. of columns
Pattern pattern = Pattern.compile("#(--+)#");
int count = 0;
for (int i = 0; i < a; i++) {
String temp = input.next().trim();
if (temp.length() > b) {
temp.substring(0, b);
}
Matcher matcher = pattern.matcher(temp);
if (matcher.find()) {
count++;
}
}
System.out.println(count);
}
}
I have a problem with Scanner class. I have a few methods which read certain input from the user, however after invoking first method others crash (cannot read input). I searched for the solution and it looked like adding "scanner.nextLine()" will solve the problem but it didn't.
public class GameController {
private int numberOfPlayers = 2;
private Board board = new Board('.');
String players[] = new String[numberOfPlayers];
char playersMarkers[] = new char[numberOfPlayers];
public void getPlayersNames() {
Scanner input = new Scanner(System.in);
for (int i = 0; i < players.length; i++) {
System.out.print("Insert player " + (i + 1) + "'s name: ");
players[i] = input.nextLine();
}
input.nextLine(); // <- this one was suppose to solve the problem
input.close();
}
public static void main(String[] args) {
GameController gc = new GameController();
gc.getPlayersNames();
Scanner scanner = new Scanner(System.in);
int array[] = new int[5];
for (int i = 0; i < array.length; i++) {
if (scanner.hasNext()) {
array[i] = scanner.nextInt();
}
}
scanner.close();
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
Output:
Insert player 1's name: John
Insert player 2's name: George
1
0
0
0
0
0
You are not getting anything from scanner (in the main method) because you already closed System.in (when closing input, at the end of the getPlayersNames method).
You should not close System.in yourself, as it prevent any future attempt to read from this stream.
I was trying to take string input in java. My input should be like this
3
1,1,bugs#bunny.com,123 Sesame St.,New York,NY,10011,12345689010
1,2,bugs#bunny.com,123 Sesame St.,New York,NY,10011,12345689010
1,3,bugs#bunny.com,123 Sesame St.,New York,NY,10011,12345689010
So, I tried this
Scanner in = new Scanner(System.in);
int TotalNumber = in.nextInt();
String[] Data = new String[TotalNumber];
for (int Counter = 0; Counter < TotalNumber; Counter++) {
Data[Counter] = in.next();
}
in.close();
for (int counter = 0; counter < Data.length; counter++) {
System.out.println(Data[counter]);
}
My output is showing this
1,1,bugs#bunny.com,123
Sesame
St.,New
What is my problem ? How take input string line properly ?
Update
I found my solution at here Scanner issue when using nextLine after nextXXX
next() breaks at a whitespace. Instead, you should use nextLine() to input the entire line to your string:
int TotalNumber = in.nextInt();
String[] Data = new String[TotalNumber];
for (int Counter = 0; Counter < TotalNumber; Counter++) {
Data[Counter] = in.nextLine();
}
Try with Data[Counter] = in.nextLine();
What about:
import java.util.Scanner;
import java.lang.String;
public class Test
{
public static void main(String[] args)
{
char[] sArray;
Scanner scan = new Scanner(System.in);
System.out.print("Enter a Palindrome : ");
String s = scan.nextLine();
s = s.replaceAll("\\s+", "");
sArray = new char[s.length()];
for(int i = 0; i < s.length(); i++)
{
sArray[i] = s.charAt(i);
System.out.print(sArray[i]);
}
}
}
Try this (Mureinik modified code)..
int TotalNumber = in.nextInt();
in.nextLine();
String[] Data = new String[TotalNumber];
for (int Counter = 0; Counter < TotalNumber; Counter++) {
Data[Counter] = in.nextLine();
}
You need a nextLine() after taking the int because you will press enter after taking int and that enter is read by nextLine() in the Data[0].