I'm trying to take user input and put it into a character array and then print it out.... It's part of a bigger program and since i'm a new coder, I was hoping if you could keep the program simple without....
I get the error "Array index out of bounds". I tried changing the length of the array but that still didn't work.
public static void main(String[] args) {
// TODO Auto-generated method stub
char[] ToEdit = new char [];
Scanner sc = new Scanner(System.in);
for (int i=0; i<5; i++)
{
System.out.println(i + ":");
ToEdit[i] = sc.next().charAt(i);
}
System.out.println(ToEdit);
}
Thank you
The problem lies here: char[] ToEdit = new char [];.
On that line, you are creating an empty array without a size. You would need to change it to : char[] ToEdit = new char [5];.
Further more, you will need to change this: ToEdit[i] = sc.next().charAt(i); to this: ToEdit[i] = sc.next().charAt(0);. The problem with your current line is that even if you enter 1 character, your code will look for more.
As a side note, it would be recommended that you extract the number 5 as a variable. This will allow you to increase or decrease the amount of characters your program can process by changing just one location.
As a further excercise, you can take a look at lists and see how you can make your program more flexible, without having to define a size for the array.
This wont compile as you need to add char array length first:
char[] ToEdit = new char[5];
Then this code ToEdit[i] = sc.next().charAt(i); produces String array out of bound exception. Because charAt(i) each time find char at 0,1,2,3,4 and so on position in string as shown below (the output of your program). So you need to change this to ToEdit[i] = sc.next().charAt(0);
0:
abcde
1:
acx
2:
acv
3:
acvff
4:
acdcdvc
acvfd
Related
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.
Trying to populate an array with input through the scanner .nextLine() function. The problem specifications give a sample input as follows:
3 5 4
abc
bca
dac
dbc
cba
(ab)(bc)(ca)
abc
(abc)(abc)(abc)
(zyx)bc
Just as I copied and pasted that whole chunk into this box, I'd like to do the same with my code, but when I try, the code only reads in the last line. I want each line to be read in and stored in it's own index in the array, NOT a multi-line string in one index or only the last line being read in and stored (which is what is happening now).
This is my method for initializing the array, which I've tested and it works when I feed in the input line by line, but that's just really annoying to be honest.
public static void initialize_array(String [] arr)
{
Scanner kbreader = new Scanner(System.in);
for (int i = 0 ; i < arr.length ; i++)
{
arr[i] = kbreader.nextLine();
System.out.println("this is just loading in: " + arr[i]);
}
}
When I run the program, (it also takes in 3 integers at the top and I print them just to test them, but that's not important) it only registers the last line.
A screenshot:
enter image description here
I think I've done something like this in C, but that might be because I used scanf() and C is relatively low level so it literally had to walk through the entire chunk.
It might not be possible, but I figured I'd ask to see.
Also, just so you know this is for practice, not an actual graded assignment or anything important, so don't hold anything back. :)
If you know the exact length of the array, then this would work:
Scanner scn = new Scanner(System.in);
scn.useDeliminator("\n");
for (int i = 0 ; i < arr.length ; i++)
{
arr[i] = scn.next();
System.out.println("this is just loading in: " + arr[i]);
}
The key here is the useDeliminator method call. The next methods reads from the stream until it reaches the deliminator pattern. In this case, it is \n, a new line. Please use the new line character of your OS.
This may be off point, but have you tried just using array.add(scanner.next()) and looping until scanner.hasNext() returns false?
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.
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!
I have the task of writing a program using the fibonacci sequence and putting them into arrays. It works by getting user input ( how many numbers in the sequence the user wants to print out) and then it implements that into an array and prints out the sequence with the number of 'numbers' the user inputed.
As I missed out on 2 weeks of class I looked online on how to write this program and found a video which the following code was written. So I do not take credit for the following code, I'm merely using it as an example.
Anyway here's the code:
public class Fibonacci
{
public static void main(String[] args)
{
int numToPrint;
//how many numbers to print out
Scanner scan = new Scanner(System.in);
System.out.println("Hvað viltu prenta út margar tölur úr Fibonacci röðinni?");
numToPrint = scan.nextInt();
scan.close();
//prints out the first 2 numbers
int nuverandiT = 1;
int lokaT = 0;
System.out.println(lokaT);
System.out.println(nuverandiT);
//prints out the rest of the sequence
int lokaLokaT;
for(int i = 2; i < numToPrint; i++)
{
lokaLokaT = lokaT;
lokaT = nuverandiT;
nuverandiT = lokaLokaT + lokaT;
System.out.println(nuverandiT);
}
}
}
Now this prints out the fibonacci sequence with input from the user, but I'm not quite sure how to make it print out into an array. Do any of you guys know how to do this?
You have to create an array, for example:
int[] simpleArray;
simpleArray = new int[numToPrint];
At the place of
System.out.println(lokaT);
System.out.println(nuverandiT);
Put:
simpleArray[0] = lokaT;
simpleArray[1] = nuverandiT;
And inside your loop, you put instead this:
System.out.println(nuverandiT);
This:
simpleArray[i] = nuverandiT;
I'm guessing when you say 'print out into an array' you really mean you just want to store the values in an array. In that case,
Before your for loop:
int[] array = new int[numToPrint];
And inside your for loop:
array[i-2] = nuverandiT;
If you wanted to print the numbers once they've been stored in an array, you would probably want to loop through it and print in the same fashion, accessing the elements by index. For more information, the java documentation is very good. I recommend reading up on arrays and counted loops.