What is "int" in this line? - java

I'm attempting to write an array inside a for loop that doesn't seem to make any sense with the error.
String[][] userName;
userName = new String[3][4];
for(int x=1; x<= 4; x++) {
for(int y=-1; y <= 3; y++) {
System.out.println("Enter student name for row "+x+"column "+y+" ==>");
userName[x-1][y-1] = (String) System.in.read();
}
}
For the line:
userName[x-1][y-1] = (String) System.in.read()
it gives an error:
Incompatible types: int cannot be converted to String
But what in that line is classified as int? The only ones I know are the [x-1][y-1], but they're numbers to find the place in the array, also, I even deleted them, and it still says the same error.
What is classified as int, and how do I fix this error?

because System.in.read() will read bytes will return the value within range of 0-255 so you don't need it , you want to read String then either use Scanner or Streams
Scanner scan =new Scanner(System.in);
for(int x=1; x<= 4; x++) {
for(int y=-1; y <= 3; y++) {
System.out.println("Enter student name for row "+x+"column "+y+" ==>");
userName[x-1][y-1] = scan.read();
}
}
Scanner (import java.util.Scanner)
Scanner scan =new Scanner(System.in);
scan.read(); // read the next word
scan.readLine(); // read the whole line
or
Streams
InputStreamReader r=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(r);
String str=br.readLine();
Scanner is easy , comes with lot of functionality link to doc , Streams can be used to read bulk data which sometimes can't be read by scanner

1 for(int x=1; x<= 4; x++)
2 {
3 for(int y=-1; y <= 3; y++)
4 {
5 System.out.println("Enter student name for row "+x+"column "+y+" ==>");
6 userName[x-1][y-1] = (String) System.in.read();
7 }
8 }
Lets split this loop bit by bit.
On line 6, You are taking an Integer input through System.in.read() line, but your array is basically String datatype! So, you cast it to String. however, you cannot really insert int to a string without Integer.toString(System.in.read()). It's the normal way! However, the easiest way would be
userName[x-1][y-1] = "" + System.in.read();
Java reads a line from right to left. So it will take an input and append it to an empty String and then put it inside userName array!.
(Thanks to Pavneet Singh for noticing me)
(Thanks to Erwin Bolwidt for correcting me out. I did not notice it was String!)
Or, you can use Scanner class.
To do that you will need add the following codes.
add the following before your class line (public class)
import java.util.Scanner;
Then when you class starts inside public static void main(..), on the first line or in any convenient line before function, you will write the following line
Scanner sc = new Scanner(System.in);
It initializes the scanner. Then you can use the scanner class!
userName[x-1][y-1] = sc.next();
See through scanner class, you will need to specify the data type you will be providing! So, if you/user provides String or float or boolean value, it will throw an error and program will end/crash! Pretty effective, if you are trying to avoid wrong datatype.
Finally, you probably have an error in your loop declaration on line 3.
You can run the loop from y = -1 but, in Java, array indexes starts from 0. So, there is no index on y - 1 = - 1 - 1 = -2, it will throw an error! To avoid this all you have to do is, declare your loop from y = 1.
for(int y = 1, y <= 3; y++)
Happy programming! Cheers!

Before using System.in.read() you should have done some research on it. The System.in.read() method reads bytes of data from input stream and return the data as integer. So you can only use an integer or a character variable to store the data. String variables cannot store the data returned by the method System.in.read(). And this is the reason why you get the exception
incompatible types: int cannot be converted to String
And also use a try catch block when you are using System.in.read() method.

Related

Getting an input mismatch error when trying to read an integer from a file and store it in a variable

public static Matrix read(String filename) {
Scanner scan = new Scanner(filename);
int row = scan.nextInt();
int column = scan.nextInt();
Matrix mat = new Matrix(row, column);
scan.nextLine();
for(int i=0; i<row; i++) {
for(int j=0; j<column; j++) {
mat.setElement(i, j, scan.nextInt());
}
scan.nextLine();
}
scan.close();
return mat;
}
This is currently my method to read a text file. Each text file has the matrix dimensions written at the top and then the rows of the matrix below. Ex:
2 3
1 1 1
2 2 2
When I try to store the first 2 numbers in the first row as the row and column indices, I get an input mismatch exception.
Probable cause of your issue
Whenever you take inputs from the user using a Scanner class. If the inputs passed doesn’t match the method or an InputMisMatchException is thrown. For example, if you reading an integer data using the nextInt() method and the value passed in a String then, an exception occurs.
Handling input mismatch exception
The only way to handle this exception is to make sure that you enter proper values while passing inputs. It is suggested to specify required values with complete details while reading data from user using scanner class.

Java Reading Strings to a 2D Boolean Array

I am trying to read a txt file which consists of # and spaces to a 2D boolean array, so that technically a # represents true and a space represents false.
With the help of similar posts i got together a code, although they were reading integers to an array.
My code is:
public static void main(String[] args) {
String x;
String y;
Scanner fileName = null;
try {
fileName = new Scanner(new File("C:/Users/USER/Desktop/hashtag.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
x = fileName.nextLine();
y = fileName.nextLine();
boolean[][] cells = new boolean[x][y];
String finalX = fileName.nextLine();
String finalY = fileName.nextLine();
cells[finalX][finalY] = true;
for (int i = 0; i < cells.length; i++) {
for (int j = 0; j < cells[i].length; j++) {
if (cells[i][j])
System.out.print("#");
else
System.out.print(" ");
}
System.out.println();
}
}
In my code where I have written boolean[][] cells = new boolean[x][y];
It says the [x] and [y] requires an int, but found a string. The same issue is for cells[finalX][finalY] = true;
I tried parsing i.e. Integer.parseInt(x) however this gets me an error:
Exception in thread "main" java.lang.NumberFormatException: For input string: "#####################"
At what point is my issue? If I parse to an Int, then it can't read the # correct?
I think this would solve it:
1- read each line of file until the end of it to get the number of cells rows which is n then take length of any String line to get number of columns which is m.
2- create boolean array cells[n][m].
3- read file line by line and put each line in String variable and iterate over the string variable characters if character is # put true in cells array otherwise put false.
String line="";
int n=0;
while(fileName.hasNextLine()){
line = fileName.nextLine();
n++;
}
int m = line.length();
boolean[][] cells = new boolean[n][m];
// initialize Scanner to read file again
Scanner in = new Scanner(new File("C:/Users/USER/Desktop/hashtag.txt"));
int i=0;
while(in.hasNextLine()){
line = in.nextLine();
for(int j=0; j < line.length(); j++){
char c = line.charAt(j);
if(c == '#'){
cells[i][j] = true;
}
else{
cells[i][j] = false;
}
}
i++;
}
You have many mistakes in code and this approach is definitely wrong, you don't even save values that you read from file inside array. Also this code is simply not how you do it, for reading files where you don't know length of file you want to use Lists where you don't need to specify number of elements that list will take(its possible to do get semi-working solution with arrays but there is no point of learning something that is simply wrong). Before even trying to work with files you should learn more basic things, you don't even initialize your arrays properly, you use string for size and index which is causing those issues you mentioned, another beginner mistake is trying to parse non-integer string to int(you are trying to convert ############ to int which is impossible, you can only use this if you know that string is an integer like 1 or 5 or 1000).
So my answer to your question is to just go slowly and learn basics then add new stuff step by step instead just rushing with it.
It says the [x] and [y] requires an int, but found a string. The same
issue is for cells[finalX][finalY] = true;
I tried parsing i.e. Integer.parseInt(x) however this gets me an
error: Exception in thread "main" java.lang.NumberFormatException: For
input string: "#####################"
One approach you could do is first read the entire file.
Example:
List<String> tempList = new ArrayList<>();
while (fileName.hasNextLine()) {
String line = fileName.nextLine();
tempList.add(line);
}
then you can do this:
boolean[][] cells = new boolean[tempList.size()][tempList.get(0).length()];
note - this solution assumes the length() of each line is the same and the columns of each line is the same.
Also, why do you need to perform this outside the loop?
cells[finalX][finalY] = true;
you should remove that line and let the loop do all the work to determine what's # or ' '. Also, your if condition doesn't seem to be doing the correct operation. Consider implementing this approach and then go on from there.

Convert input strings into int array

I want to read in five numbers from the console. To convert the input strings into int[x] for each number i tried to use a for loop. But it turns out that #1 incrementation is dead code and #2 my array is not initialized, even though i just did.
I'm on my first Java practices and would be happy to hear some advices.
My code:
public static void main(String[] args) throws IOException {
System.out.println("Type in five Numbers");
int [] array;
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
for(int x=0; x<5; x++){
String eingabe = br.readLine();
array[x] = Integer.parseInt(eingabe);
break;
}
reserve(array); }
First off, you didn't initialize your array, you only declared an array variable (named array). I highly suggest reading and practicing this fundamental concept of Java before proceeding further, because otherwise you will likely be confused later on. You can read more about the terms declaration, initialization, and assignment here.
Another issue, as Andrew pointed out, is that you used the keyword break in your first iteration of the loop. This keyword terminates a block of code, so your loop will only run once and then exit for good.
This code can be greatly simplified with a Scanner. A Scanner reads input from a specified location. The scanner's constructor accepts two inputs: System.in, for the default input device on your computer (keyboard), or a File object, such as a file on your computer.
Scanners, by default, have their delimeter set to the whitespace. A delimeter specifies the boundary between successive tokens, so if you input 2 3 5 5, for example, and then run a loop and invoke the scanVarName.nextInt() method, it will ignore the white spaces and treat each integer in that single line as its own token.
So if I understand correctly, you want to read input from the user (who will presumably enter integers) and you want to store these in an integer array, correct? You can do so using the following code if you know how many integers the user will enter. You can first prompt them to tell you how many integers they plan to enter:
// this declares the array
int[] array;
// declares and initializes a Scanner object
Scanner scan = new Scanner(System.in);
System.out.print("Number of integers: ");
int numIntegers = scan.nextInt();
// this initializes the array
array = new int[numIntegers];
System.out.print("Enter the " + numIntegers + " integers: ");
for( int i = 0; i < numIntegers; i ++)
{
// assigns values to array's elements
array[i] = scan.nextInt();
}
// closes the scanner
scan.close();
You can then use a for-each loop to run through the items in your array and print them out to confirm that the above code works as intended.

Extracting data from scanner string passed into method

I am required to pass a scanner as a parameter to a method and have the method print things based on what was passed with the scanner.
So, if the scanner passed contains "6 fox 3 bees 2 25 8 ducks"
The method would print out
foxfoxfoxfoxfoxfox
beesbeesbees
2525
ducksducksducksducksducksducksducksducks
I have no problem writing the method. I'm just confused as to how I would use a scanner to do that.
Well, a Scanner is used for reading stuff in from either a file or standard input (System.in). Passing it around wouldn't do you a whole lot of good unless you want to encapsulate functionality and responsibilities.
If we think about this from a problem-solving stance, what are we really trying to get?
We have a string that contains first a number and a string, and the second string could contain numerals.
All of these symbols are separated by space.
Everything is contained on one line; we don't have to worry about moving to the next line.
It's entirely up to you how you want to approach this, but a couple of suggestions are as follows:
Since you know the precise order of tokens, you can make multiple calls to Scanner.next() and Scanner.nextInt().
while(scanner.hasNext()) {
System.out.println(readFromScanner(scanner));
}
scanner.close(); // DO NOT DO THIS if you are using System.in!
public static String readFromScanner(Scanner scanner) {
StringBuilder result = new StringBuilder();
int times = scanner.nextInt();
String phrase = scanner.next();
for(int i = 0; i < times; i++) {
result.append(phrase);
}
return result.toString();
}
You could also read the entire line in at once using nextLine(), and parse it using String.split(), which gives you numerals at every even index (0, 2, 4, etc), and strings at every odd index (1, 3, 5, etc).
You can read from the Scanner using methods like next() and nextInt(). You can read the full Scanner javadoc here.
Try this. There are two ways of reading input.
1) InputStreamReader wrapped in a BufferedReader
2) Scanner classes in JDK1.5
Refer to this article. This will solve your problem.
http://www.mkyong.com/java/how-to-read-input-from-console-java/
You can pass a Parameter by :
Input Accept here
System.out.println("Input here: " );
String input = scan.next();
// This how you gonna pass the parameter
inputedByScanner(input);
Your Method Accept it and print the inputed value.
public void print inputedByScanner(String input){
System.out.println(input);
}
public class Homework {
public static void main(String[] args) {
System.out.println("Enter something:");
doStupidHomework(new Scanner(System.in));
}
private static void doStupidHomework(Scanner scanner) {
int i = 0, x = 0;
for (String next = scanner.next(); next != null; next = scanner.next(), i++) {
if (i % 2 == 0) {
x = Integer.parseInt(next);
continue;
}
for (int j = 0; j < x; j++) {
System.out.print(next);
}
System.out.println();
}
}
}
Output:
Enter something:
6 fox 3 bees 2 25 8 ducks
foxfoxfoxfoxfoxfox
beesbeesbees
2525
ducksducksducksducksducksducksducksducks

excess spaces in front of printed text java

I am trying to write a program to reverse the letters/words in an inputted string, I thought I finally had it but I can't figure out why there are so many excess spaces in front of my output text. Any help would be greatly appreciated.
Also on a side note I attempted to make the scope of the array an incremented variable but it would not run, however I can use an incremented variable for the index position without any issues; why is that?
This is what I have so far and it seems to do exactly what I want it to do minus all the excess white space in front of the output.
Scanner in = new Scanner(System.in);
System.out.println("please enter string");
String strName = in.nextLine();
int ap = 0;
char strArray[] = new char[99];
for(int i=0;i < strName.length();i++)
{
strArray[ap] = strName.charAt(i);
ap++;
}
for (int e=strArray.length-1;e >= 0;e--)
{
System.out.print(strArray[e]);
}
Try this
Scanner in = new Scanner(System.in);
System.out.println("please enter string");
String strName = in.nextLine();
int ap = 0;
char strArray[] = new char[strName.length()];
for(int i=0;i < strName.length();i++)
{
strArray[ap] = strName.charAt(i);
ap++;
}
for (int e=strArray.length-1;e >= 0;e--)
{
System.out.print(strArray[e]);
}
The issue is you are initializing that char array to size 99. For a string of size 4... we have to print 95 nulls THEN the 4 chars in reverse order. This will be fixed by initializing the array to the actual size of the input string. No nulls to print then (printing nulls results in a white space).
Also on a side note I attempted to make the scope of the array an incremented variable but it
would not run, however I can use an incremented variable for the index position without any
issues; why is that?
Hmmm. Not sure what you mean? The word "scope" has specific meaning in CS that I don't think is the meaning you are referring to!

Categories