Bingo Lyrics Code Java.lang.stringindexoutofbounds? - java

I am new to programming and I have written a bingo class that types out the lyrics to bingo. Here is the code:
public class BingoLyrics {
String lineOne = "There was a farmer had a dog and Bingo was his name, oh." ;
String lineTwo = "BINGO" ;
String lineThree = "And Bingo was his name, oh." ;
int starCount = 1 ;
public void bingoLyrics ( ) {
while (starCount != 7) {
System.out.println (lineOne) ;
System.out.println (lineTwo + ", " + lineTwo + ", " + lineTwo) ;
System.out.println (lineThree) ;
lineTwo = "*" + (lineTwo.substring(starCount)) ;
if (lineTwo.length() == 4) {
lineTwo = "*" + lineTwo ;
}
else if (lineTwo.length() == 3) {
lineTwo = "**" + lineTwo;
}
else if (lineTwo.length() == 2) {
lineTwo = "***" + lineTwo;
}
else if (lineTwo.length() == 1) {
lineTwo = "****" + lineTwo;
}
starCount = starCount + 1 ;
}
}
}
It works but i get a java.lang.stringindexoutofbounds for the line lineTwo = "*" + (lineTwo.substring(starCount)) ; . Why does it do this? Any way to fix?

You get an StringOutOfBoundsException because at the last iteration of the loop the starCount is 6, but the string is only five characters long. Instead of using a string for line two, you can use a StringBuilder. It's easier because you can replace a char at a specified index.
public class BingoLyrics {
String lineOne = "There was a farmer had a dog and Bingo was his name, oh.";
StringBuilder lineTwo = new StringBuilder("BINGO");
String lineThree = "And Bingo was his name, oh.";
int starCount = 0;
public void bingoLyrics() {
while (starCount < 6) {
System.out.println(lineOne);
System.out.println(lineTwo + ", " + lineTwo + ", " + lineTwo);
System.out.println(lineThree);
lineTwo.replace(starCount, starCount + 1, "*");
starCount = starCount + 1;
}
}
}

Related

If Else statement logic execution

The line with the problem is. This line should check if the 3rd index contains character and it should not contain the words north and america.
else if ( salida[3].matches("[a-zA-Z]+") && !salida[3].equals("North") ) { // not working correctly
if ( !salida[3].equals("America")) {
salida1 = salida1 + salida[0] + " " + salida[1] + " " + salida[2] + " " + salida[3] + ",";
The code above should run for the 4th line of the array data below
[United, States, 1,527,664, 90,978, North, America]
[Canada, 77,002, 5,782, North, America]
[Turks, and, Caicos, 12, 1, North, America]
[St., Vincent, &, Grenadines, 17, 0, North, America]
this is the string output I'm currently getting which doesn't add the 3rd index of the array to the string
United States,Canada ,Mexico ,Dominican Republic,Panama ,Honduras ,Guatemala ,Cuba ,El Salvador,Costa Rica,Jamaica ,Haiti ,Martinique ,Guadeloupe ,Bermuda ,Trinidad and,Aruba ,Bahamas ,Cayman Islands,Barbados ,Sint Maarten,Saint Martin,Nicaragua ,Antigua and,Grenada ,Belize ,Saint Lucia,St. Vincent,CuraƧao ,Dominica ,Saint Kitts,Turks and,Montserrat ,Greenland ,British Virgin,Saint Barthelemy,Caribbean Netherlands,Anguilla ,Saint Pierre,
Input country to display data:
This is my entire code
public String setCountriesList() {
String salida1 = "";
try {
Document doc = Jsoup.connect("https://www.worldometers.info/coronavirus/countries-where-coronavirus-has-spread/").get();
Elements tr = doc.select("tr");
String [] na = {"north", "america"};
for (int i = 0; i < tr.size(); i++) {
if (tr.get(i).text().contains("North America")) {
String[] salida = tr.get(i).text().split(" ");
System.out.println(salida[3].contains("North") + " and " + salida[3].contains("America") );
System.out.println(Arrays.deepToString(salida)); //split salida to country, number ,number in array
if ( salida[1].matches("[a-zA-Z]+")) {
salida1 = salida1 + salida[0] + " " + salida[1] + ",";
}
else if ( salida[2].matches("[a-zA-Z]+")) {
salida1 = salida1 + salida[0] + " " + salida[1] + " " + salida[2] + ",";
}
else if ( salida[3].matches("[a-zA-Z]+") && !salida[3].equals("North") ) { // not working correctly
if ( !salida[3].equals("America")) {
salida1 = salida1 + salida[0] + " " + salida[1] + " " + salida[2] + " " + salida[3] + ",";
}}
```
else {
salida1 = salida1 + salida[0] + " ,";
}
}
}
return salida1;
} catch (Exception ex) {
System.out.println("error");
return "error";
}
}
The issue is that the names of the countries contain a comma "," which is your separator character. You need to find a way to have the country name within the same index 0, or at least wrap the country name in quotes "", so that "North" is effectively index 3. In the examples above "North" was only index 3 for Canada.

How do I add "and" before the last author's last name?

public String Cite()
{
String authorsList = "";
Collections.sort(authors);
for(Author a: authors)
{
authorsList += a.firstName.toUpperCase().charAt(0) + ". " + a.lastName + ", ";
}
String cite = authorsList + "\"" + title + "\", " + venue + "(" + getAcronym() + ")" + " , " +
publisher;
return cite;
}
How would I go about adding the word "and" to separate the last two names of the list?
Use a for loop with index.
for (int i = 0; i < authors.size(); ++i) {
if (i == authors.size() - 2) {
authorsList += a.firstName.toUpperCase().charAt(0) + ". " + a.lastName + "and ";
} else {
authorsList += a.firstName.toUpperCase().charAt(0) + ". " + a.lastName + ", ";
}
}
public static String Cite(ArrayList<Author> authors){
String authorsList = "";
Collections.sort(authors, new CustomComperator());
int size = authors.size();
int count = 0;
for(Author a: authors) {
if (size ==1) {
authorsList = a.firstName.toUpperCase().charAt(0) + ". " + a.lastName;
}
else if (count == size-2) {
authorsList += a.firstName.toUpperCase().charAt(0) + ". " + a.lastName ;
}
else if (count == size - 1) {
authorsList += " and " + a.firstName.toUpperCase().charAt(0) + ". " + a.lastName ;
}
else{
authorsList += a.firstName.toUpperCase().charAt(0) + ". " + a.lastName + ", ";
}
count ++;
}
return authorsList;
}
You should use a normal for loop, so you can detect that you're on the first and/or last element.
Other changes:
Remove the , after the last author.
Use StringBuilder to build a String.
List<Author> authors = new ArrayList<>(List.of(
new Author("Stephen", "King"),
new Author("John", "Grisham"),
new Author("William", "Shakespeare"),
new Author("Charles", "Dickens") ));
Collections.sort(authors);
StringBuilder buf = new StringBuilder();
for (int i = 0; i < authors.size(); i++) {
Author a = authors.get(i);
if (i != 0)
buf.append(i < authors.size() - 1 ? ", " : " and ");
buf.append(a.firstName.toUpperCase().charAt(0) + ". " + a.lastName);
}
String authorsList = buf.toString();
System.out.println(authorsList);
Output
C. Dickens, J. Grisham, S. King and W. Shakespeare
Oxford comma
Whether or not you want , comma before and (Oxford comma) is of course entirely up to you.
buf.append(i < authors.size() - 1 ? ", " : ", and ");
Output
C. Dickens, J. Grisham, S. King, and W. Shakespeare
UPDATE
Since all 4 other answers at this time gave bad result for a single Author, here is test result for various number of authors.
Full Test
List<Author> allAuthors = List.of(
new Author("Stephen", "King"),
new Author("John", "Grisham"),
new Author("William", "Shakespeare"),
new Author("Charles", "Dickens") );
for (int aCount = 0; aCount <= allAuthors.size(); aCount++) {
List<Author> authors = new ArrayList<>(allAuthors.subList(0, aCount));
Collections.sort(authors);
StringBuilder buf = new StringBuilder();
for (int i = 0; i < authors.size(); i++) {
Author a = authors.get(i);
if (i != 0)
buf.append(i < authors.size() - 1 ? ", " : " and ");
buf.append(a.firstName.toUpperCase().charAt(0) + ". " + a.lastName);
}
String authorsList = buf.toString();
System.out.println(aCount + ": \"" + authorsList + "\"");
}
Output
0: ""
1: "S. King"
2: "J. Grisham and S. King"
3: "J. Grisham, S. King and W. Shakespeare"
4: "C. Dickens, J. Grisham, S. King and W. Shakespeare"
If you want to do the same without loops you could:
Define a toString or similar method inside your Author class:
class Author{
String firstName;
String lastName;
Author(String firstName,String lastName){
this.firstName=firstName;
this.lastName=lastName;
}
#Override
public String toString(){
return String.format("%s. %s",this.firstName.toUpperCase().charAt(0), this.lastName);
}
}
And use the Collectors.joining to create the initial list (comma separated).
List<Author> authors = Arrays.asList(new Author("Jules", "Verne"),
new Author("Pablo", "Neruda"), new Author("JK", "Rowling"));
authors.sort(Comparator.comparing(a -> a.lastName));
StringBuffer result = new StringBuffer(
authors.stream().limit(authors.size() - 1).map(a -> a.toString()).collect(
Collectors.joining(" ,")));
And after that, add the last "and":
if (authors.size() > 1) {
result.append(String.format(" and %s", authors.get(authors.size() - 1).toString()));
} else {
result.append(authors.get(authors.size() - 1).toString());
}
System.out.println(result);
Output: P. Neruda ,J. Rowling and J. Verne

Looping error in Method in Java

Hi guys this is my first post in this website and I'm still new to Java. This my code that i am working on.
public static void main(String[] args) throws Exception {
// debug
if ($DEBUG) System.out.println("starting\n");
//read data from text file into arrays w,p
String[] wArr = new String[50];
String[] pArr = new String[50];
String fileName = "homs.txt";
readFile(fileName, wArr, pArr);
//main control loop
while (true) {
//use input dialog to get 2 words from user
String input = JOptionPane.showInputDialog(null,"Enter two words: ");
String[] words = input.split("\\s+");
String w1 = words[0];
String w2 = words[1];
//check each word if in dictionary
int w1ix = chkFound(wArr, w1);
boolean isFound = (w1ix >= 0);
System.out.println(w1 + " is found: " + isFound);
int w2ix = chkFound(wArr, w2);
boolean isFound2 = (w2ix >= 0);
System.out.println(w2 + " is found: " + isFound2);
if (w1ix >=0 && w2ix >=0 ) msg = "both words " + w1 + " and " + w2 +
"\n\tare in dictionary";
else { msg = "one or more words not in dictionary: ";
if (w1ix <0) msg += w1 + " ";
if (w2ix <0) msg += w2 + " ";
System.out.println(msg);
//check if homonyms
boolean isHom = chkHom(pArr, w1, w2);
//output result
String line = msg +
"\nWord 1: " + w1 +
"\nWord 2: " + w2 +
"\nWord 1 in dictionary: " + isFound +
"\nWord 2 in dictionary: " + isFound2 +
"\nHomonyms: " + isHom;
JOptionPane.showMessageDialog(null, line);
//ask user to continue Y/N?
int cont = JOptionPane.showConfirmDialog(null, "Continue?");
if (cont > 0)
break;//exit loop or continue
}
//end main
}
}
public static int chkFound(String[] wArr, String w) {
for (String a : wArr) {
if(a.equals(w))
return 1;
}
return -1;
}//end chkFound
My problem for this code is that when i run it it keeps looping
String input = JOptionPane.showInputDialog(null,"Enter two words: ");
I think the reason for this problem is this part of the code. I have not come up with a solution for this though.
public static int chkFound(String[] wArr, String w) {
for (String a : wArr) {
if(a.equals(w))
return 1;
}
return -1;
}//end chkFound
https://docs.oracle.com/javase/7/docs/api/constant-values.html#javax.swing.JOptionPane.OK_OPTION
public static final int OK_OPTION 0
your break doesn't work
if (cont > 0)
break;//exit loop or continue
change it to:
final int cont = JOptionPane.showConfirmDialog(null, "Continue?","Continue?", JOptionPane.YES_NO_OPTION);
if(cont == JOptionPane.NO_OPTION){
break;
}

How to create a method that formats output of an array with a loop

I am creating a class that calls methods on an array of unknown size and unknown values. I have the entire thing made except the method that formats the output. The class is about locker rentals. If the first locker has been rented for two days, then this would be true:
daysLeftRental[0] == 2;
If the locker is available to rent, then this would be true:
daysLeftRental[0] == -1;
In other words, any lockers that are available hold a value of -1, since there is no way someone could rent a locker for -1 days. I need to format my output in the following manner:
Locker 0: 3
Locker 1: Available
Locker 2: 30
And so on and so forth. I have no idea how I would format my code so that when
i = position of locker;
daysLeftRental[i] == -1;
my output says "Available" and when
daysLeftRental[i] >= 0
my output says whatever value is stored in daysLeftRental[i]. For reference, this is what my code would look like if I could just return -1 instead of the string "available"
public String toString() {
String formatOutput = " ";
for (int i = 0; i < daysLeftRental.length; i++) {
formatOutput = formatOutput + "\nLocker"
+ i + ": " + daysLeftRental[i];
}
return formatOutput;
}
which would yield:
Locker 0: 3
Locker 1: -1
Locker 2: 30
Is this the one you are trying?
public String toString() {
String formatOutput = " ";
for (int i = 0; i < daysLeftRental.length; i++) {
formatOutput = formatOutput + "\nLocker "
+ i + ": " + (daysLeftRental[i] == -1 ? "Available" : daysLeftRental[i].toString());
}
return formatOutput;
}
you can do it like this:
public String toString() {
String formatOutput = " ";
for (int i = 0; i < daysLeftRental.length; i++) {
if(daysLeftRental[i] >= 0){
formatOutput = formatOutput + "\nLocker"
+ i + ": " + daysLeftRental[i];
}else{
formatOutput = formatOutput + "\nLocker"
+ i + ": Available";
}
}
return formatOutput;
}
or, you can prepare the line before the if-statement, then just append last segmant:
public String toString() {
String formatOutput = " ";
for (int i = 0; i < daysLeftRental.length; i++) {
formatOutput = formatOutput + "\nLocker" + i + ": ";
if(daysLeftRental[i] >= 0){
formatOutput += Integer.toString(daysLeftRental[i]);
}else{
formatOutput += "Available";
}
}
return formatOutput;
}
if you don't like to write same line in both if and else, you can use a variable to hold the number or the word "Available"
public String toString() {
String formatOutput = " ";
String status = "";
for (int i = 0; i < daysLeftRental.length; i++) {
if(daysLeftRental[i] >= 0){
status = Integer.toString(daysLeftRental[i]);
}else{
status = "Available";
}
//concatenate it:
formatOutput = formatOutput + "\nLocker" + i + status;
}
return formatOutput;
}
and you can use inline-if as in Aruna's answer above (if you understand it)
if not, i would recommend (option-2), no much code repeated (option-1), no much variables declared (option-3).
EDIT:
- -- -- -- --
i don't want to exaggerate, but you can always use a method, if you know how to use them
create a method that will return either the number or "Available"., the IF-statement goes to the method, and that's it
public String getStatus(int x){
if(x>=0){
return Integer.toString(x);
}else{
return "Available";
}
}
in the for loop, don't use IF-statement at all. just concatenate the result of getStatus() call to the line
formatOutput = formatOutput + "\nLocker" + i + ": " + getStatus(daysLeftRental[i]);

Android for loop is not working like java

This is my Android Java code . I don't understand why it is not working like java code . it is example of prime number . Suppose we want to find prime number between 1 to 5 . So I expect the result 2, 3, 5 . But I only got the result 5 . In my Java code I got the correct result . I mean 2, 3, 5 . Please help me figure out this problem.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_prime);
Button btn = (Button)this.findViewById(R.id.click_btn);
btn.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
TextView resp = (TextView) findViewById(R.id.response);
// Get number from EditText
EditText startnumber = (EditText) findViewById(R.id.first_number);
EditText endnumber = (EditText) findViewById(R.id.second_number);
// get the Strings from the EditTexts
String number1 = startnumber.getText().toString();
String number2 = endnumber.getText().toString();
// Convert Strings to int
int x1number = Integer.parseInt(number1);
int x2number = Integer.parseInt(number2);
String str = "List of prime numbers between " + x1number + " and " + x1number + ": ";
//resp.setText(str);
for(int i = x1number; i <= x2number; i++){
if(isPrime(i)){
resp.setText( str + String.valueOf(i));
}
}
}
});
}
public static boolean isPrime(int n){
if( n <= 1) {
return false;
}
for( int i = 2; i <= n/2; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
Here is my Java code .
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package primenumberstwo;
import java.util.Scanner;
/**
*
* #author vubon
*/
public class PrimeNumberstwo {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner s = new Scanner(System.in);
System.out.println("Enter your first number: ");
int start = s.nextInt();
System.out.println("Enter your second number: ");
int end = s.nextInt();
System.out.println("List of prime numbers bettween " + start + " and " + end);
for(int i = start; i <= end; i++){
if(isPrime(i)){
System.out.println(String.valueOf(i));
}
}
}
public static boolean isPrime(int n){
if( n <= 1) {
return false;
}
for( int i = 2; i <= n/2; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
}
You are overwriting the content of the TextView resp in each iteration that's why you see just le last one.
Try something like this:
String str = "List of prime numbers between " + x1number + " and " + x1number + ": ";
String result = "";
for(int i = x1number; i <= x2number; i++){
if(isPrime(i)){
result = result + " " + i;
}
}
if(!("".equalsIgnoreCase(result.trim()))){
resp.setText(str + result);
}
Problem is not in Android SDK. your logic is wrong.
String str = "List of prime numbers between " + x1number + " and " + x1number + ": ";
//resp.setText(str);
for(int i = x1number; i <= x2number; i++){
if(isPrime(i)){
resp.setText( str += String.valueOf(i));//see change here
}
}
Try with:
str = str + String.valueOf(i);
resp.setText(str);
you have found all prime numbers but override with last one on last loop iterate.
Try that;
String str = "List of prime numbers between " + x1number + " and " + x1number + ": ";
resp.setText(str);
for(int i = x1number; i <= x2number; i++){
if(isPrime(i)){
resp.setText( resp.getText() + String.valueOf(i));
}
}

Categories

Resources