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!
Related
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
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.
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.
Forgive me if this has already been asked, but I am trying to fill an array of user defined size, but I want to make sure any extra input is either dumped or triggers an error to reprompt for input. My assignment requires that all input for an array is done on one line, with spaces separating individual values. The program works fine, and seeing how we are still in the beginning of the class I don't think that we are expected to know how to filter the quantity of inputs on a single line, but it is something that still bugs me.
I have searched for some time now for a solution, but everything thing I find is not quite what I am looking for. I thought doing a while(scannerVariable != "\n") would work, but once I thought about it more I realized that wouldn't do anything for my problem since the new line character is only being encountered once per array regardless of the number of inputs. The snippet with the problem is below:
public static double[] getOperand(String prompt, int size)
{
System.out.print(prompt);
double array[];
array = new double[size];
for(int count = 0; count < size; count++)
{
array[count] = input.nextDouble();
}
return array;
}
All I need is some way of validating the number of inputs or dumping/ignoring extra input, so that there is no trash in the buffer to skip input that follows. The only way I can think of is counting the number of spaces and comparing that against the size of the array -1. I don't think that would be reliable though, and I'm not sure how to extract a whitespace character for the count unless I were to have all the input go into a string and parse it. I can post more code or provide more details if needed. As always, thanks for any help!
This can help you. Function that allows the entry of numbers on a line separated by spaces. Valid numbers are stored in a list of type Double.
public static void entersDouble () {
Scanner input = new Scanner(System.in);
String s;
ArrayList<Double> numbers= new ArrayList<>();
System.out.print("Please enter numbers: ");
s=input.nextLine();
String [] strnum = s.split("\\s+");
int j=0;
while(j<strnum.length){
try {
numbers.add(Double.parseDouble(strnum[j++]));
}
catch(Exception exception) {
}
}
for (Double n : numbers)
System.out.println(n);
}
It seems to me that rather than trying to work out the number of inputs up front you would be better off trying to read them one by one and then taking appropriate action if it's too long or too short.
For example
public static double[] getOperands(String prompt, int size) {
double[] operands = new operands[size];
while (true) {
System.out.println(prompt);
Scanner scanner = new Scanner(System.in);+
int operandCount = 0;
while (scanner.hasNextDouble()) {
double val = scanner.nextDouble();
if (operandCount < size)
operands[operandCount++] = val;
}
if (operandCount == size)
return operands;
else
System.out.println("Enter " + size + " decimals separated by spaces.");
}
}
Hello I am working on an assignment and I'm running into issues I was hoping for a little direction...
The purpose is to have user input a phrase and create an acronym out of that phrase. Anything over three words will be ignored.
I'm having issues with the acronym part, I am able to get the first character and figured that I would loop through the user input and grab the character after a space, but that is not working. All I am getting is the first character, which is obvious because I grab that first, but I can't figure out how to "save" the other two characters. Any help is greatly appreciated.
*********UPDATE************************
So thanks to an answer below I have made progress with using the StringBuilder. But, now if I enter "Your Three Words" the Output is: YYYYYTYYYYYWYYYY
Which is progress but I can't understand why it's repeating those first characters so many times??
I edited the code too.
*********UPDATE*****************************
public class ThreeLetterAcronym {
public static void main(String[] args) {
String threeWords;
StringBuilder acronym = new StringBuilder();
Scanner scan = new Scanner(System.in);
System.out.println("Enter your three words: ");
threeWords = scan.nextLine();
for(int count = 0; count < threeWords.length(); count++) {
acronym.append(threeWords.charAt(0));
if(threeWords.charAt(count) == ' ') {
++count;
acronym.append(threeWords.charAt(count));
}
}
System.out.println("The acronym of the three words you entered is: " + acronym);
}
}
You can't save the other characters because char is supposed to store only one character.
You can use a StringBuilder in this case
StringBuilder acronym = new StringBuilder();
Then in your loop simply replace it with
String[] threeWordsArray = threeWords.split(" ");
for(String word : threeWordsArray) {
acronym.append( word.substring(0, 1) );
}
**updated
You store the character at the current index in space:
char space = threeWords.charAt(count);
Then you compare the value of space with the integer value 3:
if(space < 3)
This will almost certainly never be true. You are asking for the numeric value of a character. Assuming it is a letter it will be at least 65. I suspect that your intention is to store something different in the variable space.