I'm new to java and I have an assignment to count #s in tweets (the # has to be at the beginning of the word). Here's the code:
public static void main (String str[]) throws IOException {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a tweet.");
String tweet=scan.nextLine();
int quantity = tweet.length();
System.out.println(tweet);
if (quantity > 140)
{
System.out.println("Excess Characters: " + (quantity - 140));
}
else{
System.out.println("Length Correct");
int hashtags=0;
int v=0;
String teet=tweet;
while ((teet.indexOf('#')!=-1) || v==0){
v++;
int hashnum= teet.indexOf('#');
if ((teet.charAt(hashnum + 1)!=(' ')) && (teet.indexOf('#')!=-1)) {
hashtags++;}
teet=teet.substring(hashnum,(quantity-1));
}
System.out.println("Number of Hashtags: " + hashtags);
}
}
}
The compiler doesn't detect any errors, but when I run it, it does everything except print ("Number of Hashtags: " + hashtags). Can someone please help? Thank you.
Your while loop never exits.
Instead of
teet=teet.substring(hashnum,(quantity-1));
use
teet=teet.substring(hashnum+1,(quantity-1));
And might I humbly suggest various improvements.
public static void main (String args[]) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a tweet.");
String tweet = scan.nextLine();
System.out.println(tweet);
if (tweet.length() > 140) {
System.out.printf("Excess Characters: %d%n", tweet.length() - 140);
} else {
System.out.println("Length Correct");
int hashtags = tweet.length() - tweet.replaceAll("#(?=[^#\\s])", "").length();
System.out.printf("Number of Hashtags: %d%n", hashtags);
}
}
Related
I'm writing a program for an assignment that should give random problems for the user to solve. what I am attempting to make it do is after selecting a problem type and answering one question the program should load the menu up again.
Originally I wrote a method that would be called in the else statement on line 147. The method successfully looped however the assignment specifically asks for a loop to make it happen. I've tried several different ways to change the loops condition statement but I'm not sure where I went wrong? any help would be appreciated.
I want very badly to use a switch statement but I can't as we haven't learned that in class.
// Importing Scanner and Random class for later.
import java.util.Scanner;
import java.util.Random;
class AlgebraTutor {
// Solve for Y method.
public static void solve_for_y() {
// Creation of a random number generator.
Random number_gen = new Random();
// Generates random integers from -100 to 100.
int var_m = number_gen.nextInt(101) - 100;
int var_x = number_gen.nextInt(101) - 100;
int var_b = number_gen.nextInt(101) - 100;
// Print problem out for student to see
System.out.println("Problem: y = " + var_m + "(" + var_x +")" + "+" + var_b);
System.out.println(" m =" + var_m);
System.out.println(" x =" + var_x);
System.out.println(" b =" + var_b);
// This formula will calculate the value of y.
float var_y = (var_m * var_x) + var_b;
// Using the scanners class a scanner object called userInput was created to record students answer. Answer was taken as a string and converted to an integer.
Scanner user_input = new Scanner(System.in);
System.out.println("Please solve for y:");
String user_answer = user_input.nextLine();
int answer = Integer.parseInt(user_answer);
if (answer == var_y){
System.out.println("correct");
}else{
System.out.println("incorrect, The answer is:" + var_y);
}
}
// -------------------------------------------------------------------------
// Solve for M method.
public static void solve_for_m() {
// Creation of a random number generator.
Random number_gen = new Random();
// Generates random integers from -100 to 100.
int var_y = number_gen.nextInt(101) - 100;
int var_x = number_gen.nextInt(101) - 100;
int var_b = number_gen.nextInt(101) - 100;
// Print problem out for student to see.
System.out.println("Problem: " + var_y + " = m (" + var_x +") + " + var_b);
System.out.println(" y =" + var_y);
System.out.println(" x =" + var_x);
System.out.println(" b =" + var_b);
// This formula will calculate the value of m.
float var_m = (var_y - var_b) / var_x;
// Using the scanners class a scanner object called userInput was created to record students answer. Answer was taken as a string and converted to an integer.
Scanner user_input = new Scanner(System.in);
System.out.println("Please solve for m:");
String user_answer = user_input.nextLine();
int answer = Integer.parseInt(user_answer);
if (answer == var_m){
System.out.println("correct");
}else{
System.out.println("incorrect, The answer is:" + var_m);
}
}
// -------------------------------------------------------------------------
// Solve for B method
public static void solve_for_b() {
// Creation of a random number generator.
Random number_gen = new Random();
// Generates random integers from -100 to 100.
int var_y = number_gen.nextInt(101) - 100;
int var_x = number_gen.nextInt(101) - 100;
int var_m = number_gen.nextInt(101) - 100;
// Print problem out for student to see.
System.out.println("Problem: " + var_y + " = " + var_m + " (" + var_x +") " + "+ b");
System.out.println(" y =" + var_y);
System.out.println(" x =" + var_x);
System.out.println(" m =" + var_m);
// This formula will calculate the value of m.
float var_b = var_y / (var_m * var_x);
// Using the scanners class a scanner object called userInput was created to record students answer. Answer was taken as a string and converted to an integer.
Scanner user_input = new Scanner(System.in);
System.out.println("Please solve for b:");
String user_answer = user_input.nextLine();
int answer = Integer.parseInt(user_answer);
if (answer == var_b){
System.out.println("correct");
}else{
System.out.println("incorrect, The answer is:" + var_b);
}
}
// -------------------------------------------------------------------------
public static void main(String[] args) {
do{
System.out.println("Which type of problem would you like to practice?");
System.out.println("1) Solve for y");
System.out.println("2) Solve for m");
System.out.println("3) Solve for b");
System.out.println("4) To quit");
Scanner selection_input = new Scanner(System.in);
String user_selection = selection_input.nextLine();
if ( user_selection.equals("1")){
solve_for_y();
} else if (user_selection.equals("2")){
solve_for_m();
} else if (user_selection.equals("3")){
solve_for_b();
} else if (user_selection.equals("4")){
System.out.println("Quitting Program");
System. exit(0);
} else{
System.out.println("Please choose from the given options");
}
} while(user_selection.equals("1") &&
user_selection.equals("2") &&
user_selection.equals("3") &&
user_selection.equals("4"));
}
}
You must declare the user_inpout variable outside the do...while loop, then you can check its value in the while() expression. Also you should initialize the scanner only once at the beginning of your program.
public static void main(String[] args)
{
Scanner selection_input = new Scanner(System.in);
String user_selection=null;
do
{
System.out.println("Which type of problem would you like to practice?");
System.out.println("1) Solve for y");
System.out.println("2) Solve for m");
System.out.println("3) Solve for b");
System.out.println("4) To quit");
user_selection = selection_input.nextLine();
if (user_selection.equals("1"))
{
solve_for_y();
}
else if (user_selection.equals("2"))
{
solve_for_m();
}
else if (user_selection.equals("3"))
{
solve_for_b();
}
else if (user_selection.equals("4"))
{
System.out.println("Quitting Program");
System.exit(0);
}
else
{
System.out.println("Please choose from the given options");
}
}
while (!user_selection.equals("4"));
}
For the case "4" you have two exists now:
else if (user_selection.equals("4"))
{
System.out.println("Quitting Program");
System.exit(0);
}
and:
while (!user_selection.equals("4"));
Only one of both is needed. So you may either remove the first one or replace the while statement by while(true).
I'm Adrian and i'm kinda new to programming, would like to learn more and improve. I was asked to do a grade average exercise and i did this , but i'm stuck at making the code so if you type a number instead of a name the code will return from the last mistake the writer did , like it asks for a name and you put "5". In my code gives an error and have to re-run it. Any tips?
import java.util.*;
import java.math.*;
import java.io.*;
class Grades {
public static void main(String[] args) {
int j = 1;
double sum = 0;
double average;
Scanner keyboard = new Scanner(System.in);
System.out.println("Insert Student's Name");
String name = keyboard.next();
System.out.println("Insert Student's Surname");
String surname = keyboard.next();
System.out.println("Student's name: " + name + " " + surname);
System.out.println("How many Grades?");
int nVotes = keyboard.nextInt();
int[] arrayVotes = new int[nVotes];
System.out.println("Now insert all the grades");
for (int i=0; i<arrayVotes.length; i++) {
System.out.println("Insert the grade " + j);
arrayVotes[i] = keyboard.nextInt();
j++;
}
for (int i=0; i<arrayVotes.length; i++) {
sum += arrayVotes[i];
}
average = sum / arrayVotes.length;
System.out.println("Student's grade average is: " + average);
System.out.println("Does he have a good behaviour? Answer with true or false");
boolean behaviourStudent = keyboard.nextBoolean();
average = !behaviourStudent ? Math.floor(average) : Math.ceil(average);
System.out.println("The grade now is: " + average);
keyboard.close();
}
}
At the heart of any solution for this, it requires a loop, and a condition for resetting.
String result = null;
while (result == null) {
//OUT: Prompt for input
String input = keyboard.next();
if (/* input is valid */) {
result = input; //the loop can now end
} else {
//OUT: state the input was invalid somehow
}
//Since this is a loop, it repeats back at the start of the while
}
//When we reach here, result will be a non-null, valid value
I've left determining whether a given input is valid up to your discretions. That said, you may consider learning about methods next, as you can abstract this prompting/verification into a much simpler line of code in doing so (see: the DRY principle)
There are several ways to do it.
But the best way is to use regex to validate the user input.
Have a look at the below code, you can add other validations as well using regex.
import java.util.Scanner;
class Grades {
public static boolean isAlphabetOnly(String str)
{
return (str.matches("^[a-zA-Z]*$"));
}
public static void main(String[] args) {
int j = 1;
double sum = 0;
double average;
Scanner keyboard = new Scanner(System.in);
System.out.println("Insert Student's Name");
String name = keyboard.next();
if(!isAlphabetOnly(name)){
System.out.println("Please enter alfabets only");
return;
}
System.out.println("Insert Student's Surname");
String surname = keyboard.next();
System.out.println("Student's name: " + name + " " + surname);
System.out.println("How many Grades?");
int nVotes = keyboard.nextInt();
int[] arrayVotes = new int[nVotes];
System.out.println("Now insert all the grades");
for (int i=0; i<arrayVotes.length; i++) {
System.out.println("Insert the grade " + j);
arrayVotes[i] = keyboard.nextInt();
j++;
}
for (int i=0; i<arrayVotes.length; i++) {
sum += arrayVotes[i];
}
average = sum / arrayVotes.length;
System.out.println("Student's grade average is: " + average);
System.out.println("Does he have a good behaviour? Answer with true or false");
boolean behaviourStudent = keyboard.nextBoolean();
average = !behaviourStudent ? Math.floor(average) : Math.ceil(average);
System.out.println("The grade now is: " + average);
keyboard.close();
}
}
I was working on a project for class and everything works fine until the code the professor gave us that will prompt the user to "doOver" the code if they choose to, it's coming out with this error and I'm frankly confused.
I tried changing the sc.nextLine to a .hasNextLine as I've seen in other posts, but it comes up with an error stating it needs to be a boolean and then says I can not use the next doOver.trim() code on a boolean.
final static String TITLE = "ISBN-13 Generator!";
final static String CONTINUE_PROMPT = "\nDo this again? [y/n] ";
static Scanner input = new Scanner(System.in);
private static void process(Scanner sc, String args[]) {
boolean numberChecker;
String isbn;
do {
System.out.println("\nEnter the first 12 digits of an ISBN-13: ");
isbn = input.nextLine();
input.close();
isbn = isbn.trim();
numberChecker = true;
int s = 0;
do {
numberChecker = numberChecker && Character.isDigit(isbn.charAt(s));
s++;
} while (s < isbn.length() || numberChecker == false);
} while (isbn.length() != 12 & numberChecker == false);
int sum = 0;
int s = 0;
do {
if (s % 2 == 0) {
sum = sum + isbn.charAt(s) - 48;
} else {
sum = sum + 3 * (isbn.charAt(s) - 48);
}
s++;
} while (s < 12);
{
sum = 10 - (sum % 10);
if (sum == 10)
sum = 0;
}
System.out.println("Your ISBN is " + isbn + sum);
}
private static boolean doThisAgain(Scanner sc, String prompt) {
System.out.print(prompt);
String doOver = sc.nextLine();
return doOver.trim().equalsIgnoreCase("Y");
}
public static void main(String args[]) {
System.out.println("Welcome to " + TITLE);
Scanner sc = new Scanner(System.in);
do {
process(sc, args);
} while (doThisAgain(sc, CONTINUE_PROMPT));
sc.close();
System.out.println("Thank you for using the " + TITLE);
}
It should display "Do this again? [y/n]" with you inputting "y" to start the process over and entering "n" to stop and have the system print out ("Thank you for using the " + TITLE)
This is happening because you have closed the scanner instance already using line input.close();
Just comment out or delete input.close(); and your program will work as expected.
System.out.println("\nEnter the first 12 digits of an ISBN-13: ");
isbn = input.nextLine();
//input.close();
Let me know if it helps! :)
I'm currently working on a version of hangman through java. I've recently been stumped by a problem that I can't seem to solve.
I have an array easyDifficulty and a String hiddenWord. I want to make it so that every time the game starts, my method randomWord() will choose a random word from array easyDifficulty to start the program. Many of my methods use hiddenWord so I pasted all of my code below incase you need to check that. Otherwise, the main parts that I feel like that are causing problems are in the area where I declare my field variables, my randomWord method, and the main method.
import java.util.Arrays;
import java.util.*;
import java.util.Scanner;
public class HangmanGame {
static String[] easyDifficulty = new String[]{"orange", "jacket","shirt"
,"rocket","airplane","circle","balloon","swing","truck","caterpillar"};
static Random rand = new Random();
static String hiddenWord = new String("");
static char[] hiddenWordToChar = hiddenWord.toCharArray();
static int triesLeft = 6;
static boolean done = false;
static int length = hiddenWord.length();
static Scanner input = new Scanner(System.in);
final static int maxLength = 30;
static char[] repeatChecker = new char[30]; //this is to help prevent the user from putting the same char multiple times
static char[] fillWord = new char[length];
static int var;
static int var2;
static char underscore = '_';
static int chooseDifficultyInt;
public static String randomWord(int n) {
int randomNum = rand.nextInt(9);
int difficultyInt = n;
if (difficultyInt == 1){
//System.out.println(easyDifficulty[randomNum]);
return easyDifficulty[randomNum];
}
return null;
}
public static boolean contains(char[] arr, char i) {
for (char n : arr) {
if (i == n) {
return true;
}
}
return false;
}
public static boolean multiLetter(char[] arr, char i){
int multiple = 0;
for (char n : arr){
if (i == n){
multiple++;
//continue;
}
}
System.out.println(multiple);
if (multiple > 1){
return true;
}
else {
return false;
}
}
public static void createSpaces(int n){
for (int i = 0; i <= n-1; i++){
fillWord[i] = underscore;
}
System.out.println(fillWord);
}
public static void tryAgain(){
System.out.println("Would you like to try again? Enter Y/N to go again or quit!");
char goAgain = input.next().charAt(0);
goAgain = Character.toLowerCase(goAgain);
if (goAgain == 'y') {
triesLeft = 6;
repeatChecker = new char[20];
main(null);
}
else if (goAgain == 'n') {
System.out.println("Bye!");
System.exit(0);
}
else {
System.out.println("Invalid input");
tryAgain();
}
}
public static void arrayLetters(){
System.out.println("This is a " + length + " letter word. Please enter a letter to guess: ");
char charInput = input.next().charAt(0);
char[] letters = new char[20];
//This code only runs if the user inputs a letter that repeats
//throughout hiddenWord
if (multiLetter(hiddenWordToChar, charInput)){
for (int n = 0; n < length; n++){
char multiWordLetter = hiddenWord.charAt(n);
letters[n] = multiWordLetter;
if (letters[n] == charInput){
fillWord[n] = charInput;
}
if (contains(repeatChecker, charInput)){
System.out.println("You already did that word, try again!");
arrayLetters();
}
if (Arrays.equals(fillWord, hiddenWordToChar)){
System.out.println("Congratulations, you win! The word was '" + hiddenWord + "'!");
System.out.println("You completed the challenge in " + triesLeft + " tries! \n\n");
tryAgain();
}
}
System.out.println(fillWord);
System.out.println("Nice! There is a(n) " + charInput + " in this word!");
System.out.println("You have " + triesLeft + " tries left!\n");
arrayLetters();
}
//This block of code runs when the user input a letter that only occurs once
//in hiddenWord
for (int i = 0; i < length; i++){
char wordLetter = hiddenWord.charAt(i);
letters[i] = wordLetter;
if (contains(letters, charInput)){
/*
if (multiLetter(letters, charInput)){
System.out.println("aylmao");
}
*/
//System.out.println(multiLetter(hiddenWordArray, charInput));
if (contains(repeatChecker, charInput)){
System.out.println("You already did that word, try again!");
arrayLetters();
}
repeatChecker[var] = charInput;
var++;
fillWord[i] = charInput;
if (Arrays.equals(fillWord, hiddenWordToChar)){
System.out.println("Congratulations, you win! The word was '" + hiddenWord + "'!");
System.out.println("You completed the challenge in " + triesLeft + " tries! \n\n");
tryAgain();
}
System.out.println(fillWord);
System.out.println("Nice! There is a(n) " + charInput + " in this word!");
System.out.println("You have " + triesLeft + " tries left!\n");
arrayLetters();
}
if (i == length-1){
System.out.println("There is no " + charInput + " in this word!");
triesLeft--;
System.out.println("You have " + triesLeft + " tries left!\n");
if (triesLeft <= 0){
System.out.println("You failed!\n\n");
tryAgain();
}
arrayLetters();
}
}
}
public static void main(String[] args) {
System.out.println("Welcome to my hangman game!");
System.out.println("Please input your prefered difficulty level.");
System.out.println("1. Easy");
System.out.println("2. Medium");
System.out.println("3. Hard");
chooseDifficultyInt = input.nextInt();
randomWord(chooseDifficultyInt);
hiddenWord = randomWord(chooseDifficultyInt);
createSpaces(length);
arrayLetters();
}
}
I'm an intermediate in java programming so I've learned that Strings are immutable. Thus I've considered that the reason why hiddenWord won't be set equal to randomWord(chooseDifficultyInt); is because of that?
I'm an intermediate in java programming so I've learned that Strings are immutable
This often causes confusion among new programmers. This is correct, Strings are immutable. However the variable that points to that String can be re-assigned (assuming it isn't final).
You can modify your hidden word as many times as you like:
HangmanGame.hiddenWord = "MyNewWord";
HangmanGame.hiddenWord = "AnotherWord";
HangmanGame.hiddenWord = "ThisWorks";
You might be wondering how the hiddenWord is changing if Strings are immutable.
Your variable isn't actually changing. Every time you re-assign it, a new String is being created. This means that the Strings themselves are never modified.
So yes, you can call
HangmanGame.hiddenWord = HangmanGame.randomWord(n);
and it will work perfectly.
Your initialization of hiddenWord as new String(""); is useless. You could remove it safely.
When you do that:
hiddenWord = randomWord(chooseDifficultyInt);
you set hiddenWord to the reference of a random string of your predefined list, not allocating anything, just reusing an existing string reference.
I am writing some code to help teach me how code in java and I have been using arrays. I have an error that I can't work out why it is occurring.
The Code:
import java.util.Scanner;
public class pubQuizArray {
private static Scanner kb = new Scanner (System.in);
static String[] questions;
static String[][] answers;
static char[] realAnswers;
static char ans;
static char yn;
static int questionNum;
static int questionNumArray;
static int numQ;
static int score = 0;
public static void writeQuiz()
{
getQNum();
getQ();
}
public static void getQNum()
{
System.out.println("How many Questions?");
numQ = kb.nextInt();
questions = new String[numQ];
}
public static void getAns()
{
questionNumArray = questionNum - 1;
answers = new String[numQ][];
System.out.println("What are the answers?");
System.out.println("a: ");
answers[questionNumArray][0] = kb.nextLine();
System.out.println("b: ");
answers[questionNumArray][1] = kb.nextLine();
System.out.println("c: ");
answers[questionNumArray][2] = kb.nextLine();
System.out.println("d: ");
answers[questionNumArray][4] = kb.nextLine();
realAnswers = new char[numQ];
System.out.println("What is the correct Answer?");
realAnswers[questionNum] = kb.next().charAt(0);
}
public static void getQ()
{
questionNum = 0;
System.out.println("What is the First Question?");
questions[questionNum] = kb.nextLine();
getAns();
questionNum ++;
while(questionNum < numQ)
{
System.out.println("What is the next Question?");
questions[questionNum] = kb.nextLine();
getAns();
questionNum ++;
}
}
public static void askQ()
{
questionNum = 0;
while(questionNum < numQ)
{
System.out.println("Q1: " + questions[questionNum]);
System.out.println("a: " + answers[questionNum][0]);
System.out.println("b: " + answers[questionNum][1]);
System.out.println("c: " + answers[questionNum][2]);
System.out.println("d: " + answers[questionNum][3]);
ans = kb.next().charAt(0);
if(ans == realAnswers[questionNum])
{
System.out.println("That was correct");
score ++;
}
}
}
public static void menu()
{
System.out.println("Would you like to write a new Quiz? y/n");
yn = kb.next().charAt(0);
while(yn == 'y')
{
writeQuiz();
System.out.println("Would you like to play the Quiz? y/n");
yn = kb.next().charAt(0);
while(yn == 'y')
{
askQ();
System.out.println("Would you like to play again? y/n");
yn = kb.next().charAt(0);
}
}
}
public static void main(String[] args)
{
menu();
}
}
The error is this:
Would you like to write a new Quiz? y/n
y
How many Questions?
10
What is the First Question?
What are the answers?
a:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at pubQuizArray.getAns(pubQuizArray.java:34)
at pubQuizArray.getQ(pubQuizArray.java:56)
at pubQuizArray.writeQuiz(pubQuizArray.java:17)
Thanks in advance for any help that you can give. Please bear in mind that this is just a trial program and that I am still learning java.
OK I have another problem this time it says:
Would you like to write a new Quiz? y/n
y
How many Questions?
1
What is the First Question?
and
What are the answers?
a: a
Exception in thread "main" java.lang.NullPointerException
at pubQuizArray.getAns(pubQuizArray.java:34)
at pubQuizArray.getQ(pubQuizArray.java:57)
at pubQuizArray.writeQuiz(pubQuizArray.java:17)
at pubQuizArray.menu(pubQuizArray.java:96)
at pubQuizArray.main(pubQuizArray.java:110)
and i've updated the other previous code.
At this point, inside getAns()
questionNumArray = questionNum - 1;
answers = new String[numQ][];
System.out.println("What are the answers?");
System.out.println("a: ");
answers[questionNumArray][0] = kb.nextLine();
questionNumArray contains the value -1 which is an invalid index for an array.
It comes from
public static void getQ()
{
questionNum = 0; // set to 0
System.out.println("What is the First Question?");
questions[questionNum] = kb.nextLine();
getAns(); // still 0
questionNum ++; // too late
...
}
Edit
The NPE you are getting boils down to
System.out.println("a: ");
answers[questionNumArray][0] = kb.nextLine();
you haven't initialized answers[questionNumArray] so it is null. Do the following first
answers[questionNumArray] = new String[someSize]; // someSize should probably be 5 looking at your code