Is this code correct? I have mentioned my doubts in the form of comments in some places:
public class pract1
{
public static void main (String[] args)
{
int i;
String [] array = new String[20]; // Is this declaration correct?
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the Array: ");
array = br.readLine(); // Is this the correct way to accept input from keyboard?
i=0;
while(array[i]!='\0') // Can I use the null pointer concept in Java?
{
System.out.println("The "+(i+1)+"character is:" +array[i]+"\n"); //Want to print each and every characters in string along with its position
i++;
}
}
}
This is how you could also do it:
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Pract1
{
public static void main (String[] args)
{
String array = ""; //initialize an empty string that will hold the value from the keyboard
BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); // initialize the BufferedReader
// while "stop" is not typed on the console, keep running
while(!array.equals("stop")) {
System.out.println("Enter the Array: ");
try {
array = br.readLine(); // read from the console
System.out.println("Array:" + array);
for(int i=0; i<array.length(); i++) { //loop through the input and show the chars
System.out.println("Character "+(i+1)+" is: " +array.charAt(i));
}
} catch (Exception e) { // catch any exception and show only the message, not the entire stackTrace
System.out.println("Error: " + e.getMessage());
}
System.out.println("");
}
}
}
Java string is an object, not array. If you are more comfortable with array, use split() to get an array of String. You should note that each element in the derived array is String Object with only one letter, not primitive Char.
String[] array = "abc".split("");
for(int i; i< array.length; i++)
{
System.out.println("The "+(i+1)+"character is:" +array[i]+"\n");
}
You may want to read this Question to get the idea of String Object in Java Difference between "char" and "String" in Java
Array declaration
String [] array = new String[20]; // Is this declaration correct?
This declaration is correct for an array of 20 slots of type String (all of them initialized to null). But you might not need this right away, or not in this form.
You don't need to initialize the variable, especially if you overwrite that initialization by an instruction like: array = ....
Getting Input
array = br.readLine(); // Is this the correct way to accept input from keyboard?
Yes, readLine() is the way to go, but as the doc states, and as you will be told by the compiler, readLine(); does not return an array of Strings but a single String. You should use a String variable instead:
// initialize a String variable 'line' containing the whole line without the '\n' at the end
String line = br.readLine();
UPDATE: You could also use the Scanner class instead, that's usually what we do. Then, use sc.nextLine() for similar results as br.readLine(), as stated there.
Printing the chars
System.out.println("The "+(i+1)+"character is:" +array[i]+"\n");
//Want to print each and every characters in string along with its position
You can access the character at a given position in a String via the method charAt(int). Also, you don't have to deal with complicated C stuff such as looking for the end of the string via '\0'. You should instead use a proper for loop, like this:
String line = br.readLine();
for (int i = 0; i < line.length(); i++) {
System.out.println("The "+(i+1)+" character is: " + line.charAt(i) +"\n");
}
An alternate solution would be to use the toCharArray() method:
String line = br.readLine();
char[] chars = line.toCharArray();
for (int i = 0; i < chars.length; i++) {
System.out.println("The "+(i+1)+" character is: " + chars[i] +"\n");
}
Related
I have the below code that is not reading or infinitely looping when a user inputs text using System.in. If I hard code the text into the Scanner variable it works fine so I am not sure what is wrong with the System.in portion of this code. Any help is appreciated.
import java.util.Scanner; // needed to use the Scanner class
public class HW2 {
static Scanner in = new Scanner(System.in);
public static void main(String [] args) {
System.out.println("Enter your line here");
int the =0;
int and =0;
int is = 0;
int was =0;
int noword =0;
while (in.hasNext()){
String word = in.next();
if (word.equals("the")){
the++;
}
else if( word.equals("and")){
and ++;
}
else if (word.equals("is")){
is++;
}
else if (word.equals("was")){
was++;
}
else noword++;
}
System.out.println("The number of occurrences of the was"+ the);
System.out.println("The number of occurrences of and was"+ and);
System.out.println("The number of occurrences of is was"+ is);
System.out.println("The number of occurrences of was was"+ was);
}
}
As has been mentioned, a Scanner attached to System.in will block while looking for more input. One way to approach this would be to read a single line in from the scanner, tokenize it, and then loop through the words that way. That would look something like this:
//...
String line = in.nextLine(); // Scanner will block waiting for user to hit enter
for (String word : line.split(" ")){
if (word.equals("the")) {
the++;
}
//...
You can always substitute one loop structure (for, while, do-while) for another. They all do the same thing, just with different syntax to make one a bit simpler to use than others depending on the circumstances. So if you want to use a while loop, you can do something like this:
// ...
String line = in.nextLine();
String[] tokens = line.split(" ");
int i = 0;
while (i < tokens.length){
String word = tokens[i];
if (word.equals("the")) {
the++;
}
// ...
i++;
} // end of the while loop
However, I'm of the opinion that a for loop is cleaner in the case of looping over a known set of data. While loops are better when you have an unknown dataset, but a known exit condition.
As System.in is always available while the program is running unless you close it. It will never exit the while loop. So you could add else if (word.equals("exit")) { break; }. This way, whenever you type 'exit' it will close the while loop and execute the code AFTER the while loop.
Depends, do you want to just read 1 line of text and then count the words individually?
Because is you want only one line you could take the input string using the Scanner library and split the string into individual words and apply the if-statement then. Something like:
public static void main(String [] args) {
System.out.println("Enter your line here");
int the =0;
int and =0;
int is = 0;
int was =0;
int noword =0;
String input = in.nextLine();
String words[] = input.split(" ");
for (String s : words) {
if (s.equals("the")){
the++;
} else if( s.equals("and")){
and++;
} else if (s.equals("is")){
is++;
} else if (s.equals("was")){
was++;
} else {
noword++;
}
}
System.out.println("The number of occurrences of the was: "+ the);
System.out.println("The number of occurrences of and was: "+ and);
System.out.println("The number of occurrences of is was: "+ is);
System.out.println("The number of occurrences of was was: "+ was);
}
This way you won't need a while loop at all. So it's more processor and memory efficient.
I'm working my way through a java learning book and at the moment I'm learning about arrays and vectors. I've been doing ok up until now I've been stuck on this question for ages and have no idea how to tackle it, my head is about to explode!
The questions for this certain program I have to tackle are:
Elementary error checking is introduced, specifically check that the array Tokens has two elements, if there is a problem with the format of the data inform the user but carry on accepting input.
It will accept input of either
quit
put name mark
get name
The quit scenario works as before, the second scenario stores the student and their mark at the next
available array index; whilst get just returns the mark of any student who matched to the name ( there
may be more than one such student, there many be none).
The program reads in the mark as an integer not a String (you can find examples of the structure you
need by searching for Integer.parseInt on Google).
Upon typing quit, the mean mark, and the highest mark are also displayed.
The java code is as follows:
import java.util.Scanner;
public class ArrayInput {
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
String b;
String student[] = new String[50];
String mark[] = new String[50];
int i = 0;
while ((b = s.nextLine()) != null) {
if (b.equals("quit")) break;
String Tokens[] = b.split(' ');
// System.out.println(Tokens[0] + ' ' + Tokens[1]);
student[i] = Tokens[0];
mark[i] = Tokens[1];
i++;
}
for (int j = 0; j < i; j++) {
System.out.println(student[j] + ' ' + mark[j]);
}
}
}
It also throws out on error on this line:
String Tokens[] = b.split(' ');
use:
b.split("\\s+");
to split on whitespaces.
This will cause any number of consecutive spaces to split your string into tokens as the split() method in java is constructed to be used with regular expressions anyway
I would've written it like this (tried it on IDEONE):
import java.util.Scanner;
public class ArrayInput {
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
String b;
String[] student = new String[50]; // changed here
String[] mark = new String[50]; // Changed here
int i = 0;
b = s.nextLine(); // Get the next line here first
while (b != null) { // Evalaute b as for while loop here
if (b.equals("quit")) break;
String[] Tokens = b.split(" "); // Changed to use " ", not ' '
// System.out.println(Tokens[0] + ' ' + Tokens[1]);
student[i] = Tokens[0];
mark[i] = Tokens[1];
i++;
b = s.nextLine(); // get the next line here before looping again.
}
for (int j = 0; j < i; j++) {
System.out.println(student[j] + ' ' + mark[j]);
}
}
}
The Scannerclass has a method called hasNext() which you can use quite helpfully for the while() loops. If you use that the following snippet is improved:
// b = s.nextLine() not needed anymore
while(s.hasNext()){
...
...
...
}
What I am trying to do is read from a file (in this case the file contains over 100,000+ lines) and store the values in an array, then print out the first 10 lines. However when I run the program I get the first line, and then followed by 9 lines of "null" which is obviously not what I want! This is the code and any tips would be appreciated.
import java.io.*;
import java.util.Scanner;
public class DawsonZachA5Q2{
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a size for the number of letters for words: ");
int size = keyboard.nextInt();//prompts user for input
String[] array = new String[27000];
try {
File file = new File("big-word-list.txt");
Scanner scanner = new Scanner(file);
// Start a line count and declare a string to hold our current line.
int linecount=0;
// Tells user what we're doing
System.out.println("Searching for words with " + size + " letters in file...");
int wordCount=0;
while (scanner.hasNext()){
int i = 0;
String word = scanner.next();
if(size == word.length()){
wordCount++;
array[i]=word;
i++;
//add word to array
// increase the count and find the place of the word
}
}
linecount++;
System.out.println(wordCount);
System.out.println(wordCount+" words were found that have "+size+ " letters.");//final output
for(int o = 0; o<10; o++){
System.out.println(array[o]);
}
scanner.close();
}// our catch just in case of error
catch (IOException e) {
System.out.println("Sorry! File not found!");
}
} // main
} // class
Define int i = 0; outside of the while loop. It gets set to zero each time the loop runs. That is the problem here.
You have mistaken in the while loop. You must define 'int i = 0' before the while loop. In your case, what happen is that whenever the while loop execute, i is initialized to 0. i.e. every time, the word with required length found, that word will be stored in array[0] (Since i is initialized to 0 every iteration of while loop) replacing the previous stored value. As a result, you only get the first value and remaining displayed as null since nothing is stored after array[1].
Therefore, the actual flow should be like this.
// i is initialized outside of loop.
int i = 0;
while (scanner.hasNext()){
//int i = 0; this is your error
String word = scanner.next();
if(size == word.length()){
wordCount++;
array[i]=word;
i++;
//add word to array
// increase the count and find the place of the word
}
}
I need to write for loop to iterate through a String object (nested within a String[] array) to operate on each character within this string with the following criteria.
first, add a hyphen to the string
if the character is not a vowel, add this character to the end of the string, and then remove it from the beginning of the string.
if the character is a vowel, then add "v" to the end of the string.
Every time I have attempted this with various loops and various strategies/implementations, I have somehow ended up with the StringIndexOutOfBoundsException error.
Any ideas?
Update: Here is all of the code. I did not need help with the rest of the program, simply this part. However, I understand that you have to see the system at work.
import java.util.Scanner;
import java.io.IOException;
import java.io.File;
public class plT
{
public static void main(String[] args) throws IOException
{
String file = "";
String line = "";
String[] tempString;
String transWord = ""; // final String for output
int wordTranslatedCount = 0;
int sentenceTranslatedCount = 0;
Scanner stdin = new Scanner(System.in);
System.out.println("Welcome to the Pig-Latin translator!");
System.out.println("Please enter the file name with the sentences you wish to translate");
file = stdin.nextLine();
Scanner fileScanner = new Scanner(new File(file));
fileScanner.nextLine();
while (fileScanner.hasNextLine())
{
line = fileScanner.nextLine();
tempString = line.split(" ");
for (String words : tempString)
{
if(isVowel(words.charAt(0)) || Character.isDigit(words.charAt(0)))
{
transWord += words + "-way ";
transWord.trim();
wordTranslatedCount++;
}
else
{
transWord += "-";
// for(int i = 0; i < words.length(); i++)
transWord += words.substring(1, words.length()) + "-" + words.charAt(0) + "ay ";
transWord.trim();
wordTranslatedCount++;
}
}
System.out.println("\'" + line + "\' in Pig-Latin is");
System.out.println("\t" + transWord);
transWord = "";
System.out.println();
sentenceTranslatedCount++;
}
System.out.println("Total number of sentences translated: " + sentenceTranslatedCount);
System.out.println("Total number of words translated: " + wordTranslatedCount);
fileScanner.close();
stdin.close();
}
public static boolean isVowel (char c)
{
return "AEIOUYaeiouy".indexOf(c) != -1;
}
}
Also, here is the example file from which text is being pulled (we are skipping the first line):
2
How are you today
This example has numbers 1234
Assuming that the issue is StringIndexOutOfBoundsException, then the only way this is going to occur, is when one of the words is an empty String. Knowing this also provides the solution: do something different (if \ else) when words is of length zero to handle the special case differently. This is one way to do this:
if (!"".equals(words)) {
// your logic goes here
}
another way, is to simply do this inside the loop (when you have a loop):
if ("".equals(words)) continue;
// Then rest of your logic goes here
If that is not the case or the issue, then the clue is in the parts of the code you are not showing us (you didn't give us the relevant code after all in that case). Better provide a complete subset of the code that can be used to replicate the problem (testcase), and the complete exception (so we don't even have to try it out ourselves.
We are asked to do the following:
Receive the first names of your family members (between 3 to 6 members of your family), create an array of String.
Write a static method called generateNewName() as following:
It receives the array of String as a parameter.
It creates a new first name by using the 2nd character of each String from the array
Example: If you enter as first names Rocky, Ashley, Ocarina, Baron, Ernest, the resulting name should be oscar.
Display the names that were entered and newly generated name
This is what I have:
import java.util.Arrays;
import java.util.Scanner;
public class Foothill {
static Scanner input;
public static void main(String[] args) {
input = new Scanner (System.in);
String[] getNames = new String[5];
char Output;
Output = generateNewName(getNames);
System.out.println(Output);
for(int x = 0; x < 5; x++){
System.out.println("Enter 5 names: ");
getNames[x] = input.nextLine();
}
}
public static char generateNewName(String[] getNames)
{
String newS = Arrays.toString(getNames);
char result = '\0';
for(int j = 0; j < getNames.length; j++){
result = (char) (result + newS.charAt(1));
}
return result;
}
}
It is properly taking the input, however it seems to not be executing the generatNewName method. Am I doing something wrong with the types of methods i'm using? Should generateNewName return a string-type? If so, how do I get the second letter of all input strings and concatenate them? Thanks,
Your generateNewName() method should be returning a String, not a char.
Then you would have to change that
char result = '\0';
with
String result = "";
and then you start appending (using +) the letters to the String.
You can also read about StringBuilder, which would make the code more efficient.
Also, String newS = Arrays.toString(getNames); that line doesn't make much sense. You want to be looping through the names you have, not through all the letters of your name.
I would rewrite that loop to something like:
for (int i = 0 ; i < names.length ; i++) {
result += names[i].charAt(1);
}
or, using a for-each loop
for (String name : names) {
result += name.charAt(1);
}
"Enter 5 names:" is misleading. Consider "Enter name " + (x + 1) + " (of " + 5 + "):" or something similar.
But to answer your question: You are running generateNewName before you get any names! It's being executed for an array of only null elements!
Change this:
Output = generateNewName(getNames);
System.out.println(Output);
for(int x = 0; x < 5; x++){
System.out.println("Enter 5 names: ");
getNames[x] = input.nextLine();
}
to this
for(int x = 0; x < 5; x++){
System.out.println("Enter 5 names: ");
getNames[x] = input.nextLine();
}
Output = generateNewName(getNames);
System.out.println(Output);
:)
Also consider renaming your variables to (a) follow naming conventions such as variable names should be lowercase, and (b) to be more indicative of what they hold and what they are (string, char, array, etc.). Such as names or nameArray instead of getNames and newName or outputName instead of Output.
Finally, and as stated by others, you're using and returning a char in the generateNewName, and obviously a name is a string, not a char.
generateNewName should return a String, not a char. A char is a single character, like the letter A.
You can't generate the new name before asking for the old names, right? Within a method, unless you say otherwise (e.g. with a loop), code runs from top to bottom, like a list of instructions.