Java Creating a array and strings from user input - java

Im writing a program that first takes input from the user as an int then constructs an array that the user then types in individual characters that builds a string from that. i've written some code but I've come up with a form of writer's block and i don't know where to go from here. any help is greatly appreciated.
EDIT: im stuck on getting the string from the input into the array im getting an error where a method is not applicable. ill make in the code where the error is happening.
Example:
How many strings? 2
Enter string #1:
Enter an alphabetic string followed by enter: t
Enter an alphabetic string followed by enter: e
Enter an alphabetic string followed by enter: s
Enter an alphabetic string followed by enter: t
Enter an alphabetic string followed by enter: %
Enter string #2:
Enter an alphabetic string followed by enter: one
Enter an alphabetic string followed by enter: two
The strings you entered are:
test onetwo
code is below:
package workfiles;
//George Flamburis
import java.util.*;
public class Hw3 {
private static Scanner numScan;
public static void main(String[] args) {
int numstring=0;
numScan = new Scanner(System.in);
while (numstring <= 0 ){
System.out.print("How many strings? ");
numstring = numScan.nextInt();
if (numstring<1){
System.out.print("Please enter a positive (> 0) number.");
}
}
String[] stringarray = new String[numstring];
for (int i = 0; i < numstring; i++) {
//ERROR HAPPENING IN THIS CODE BELOW!!!
stringarray[i] = inputAlphaString();
}
numScan.close();
}
public static String inputAlphaString(Scanner aScan) {
Scanner strScan = new Scanner(System.in);
String t = "a";
String hold = "";
while(t.matches("[a-zA-Z]+")){
System.out.println("Enter an alphabetic string followed by enter: ");
t = strScan.nextLine();
hold = hold + t;
}
strScan.close();
return hold;
}
//added [] into the method name and int to i
public static void printSArray(String[] sArray) {
for (int i = 0; i <= sArray.length; i++)
System.out.print(sArray[i] + " ");
System.out.println();
}
}

Related

Java string inside string

Write a program that asks the user to enter two Strings, and prints the number of times that the second String appears within the first String. For example, if the first String is "banana" and the second is "an", the program prints 2.
Below is my code so far
public class Assignment4 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner answer = new Scanner(System.in);
//Prompt the user to enter a string
System.out.println("Enter a word:");
String input = answer.nextLine();
//Ask the user to enter a second String
//look at index method of string
System.out.println("Enter another word:");
String input2nd = answer.nextLine();
int counter = 0;
for(int i=0; i<input.length(); i++) {
if(input.charAt(i) == input2nd.charAt(0)) {
counter++;
}
}
System.out.println(input2nd + " appears " + counter + " times.");
When I type banana into first string, and second string is "an", the only thing come up is number 3, and it is for character a which appear 3 time, but not two as it suppose to only be 2 "an"
Consider this trick I learned years ago:
replace the searched word in the original word by emptychars...
get the diff between the length of both... searched chars and the original with replaced
divide that by the len of the searched word...
private static void searchString() {
Scanner answer = new Scanner(System.in);
// Prompt the user to enter a string
System.out.println("Enter a word:");
String input = answer.nextLine();
// Ask the user to enter a second String
// look at index method of string
System.out.println("Enter another word:");
String input2nd = answer.nextLine();
String a = input.replace(input2nd, "");
int counter = (input.length() - a.length()) / input2nd.length();
System.out.println(input2nd + " appears " + counter + " times.");
}
with the input banana and an will print 2

Letter Counter Code [duplicate]

This question already has answers here:
How do I count the number of occurrences of a char in a String?
(48 answers)
Closed 7 years ago.
//The Prompt is: Write a program that asks the user to enter a string, and //then ask the user to enter a character. The program should count and display //the number of times that the specified character appears in the string.
import java.util.Scanner;
public class LetterCounter{
Scanner keyboard = new Scanner (System.in); //Scanner
// Declare Variables
String userString; // String user entered
String userCharacter; // Character user entered
int StringSize;
// Ask the user to enter a string
System.out.println("Please Enter a String.");
userString = keyboard.nextLine();
// Ask the user to enter a charcter
System.out.println("Please Enter a Character.");
userCharacter = keyboard.nextLine();
// Count and display the number of times that character appears in the
// string chosen by the user.
int character;
character = Integer.parseInt(userCharacter);
StringSize = userString.charAt(character);
}
}
For some reason I can't get it to work, I just don't know where to go from here. Do I possibly need a FOR-LOOP?
Thanks for your help
Hi have a look at this
package gmit;
import java.util.Scanner;
public class LetterCounter{
public static void main(String[] args) {
String keyBoardChar;
Scanner keyboard = new Scanner (System.in); //Scanner
// Declare Variables
String userString; // String user entered
char userCharacter; // Character user entered
int StringSize;
// Ask the user to enter a string
System.out.println("Please enter a string");
userString = keyboard.nextLine();
// Ask the user to enter a charcter
System.out.println("Please Enter a Character.");
char kChar = keyboard.next().charAt(0);
// Count and display the number of times that character appears in the
// string chosen by the user.
int character = 0;
//character = Integer.parseInt(userCharacter);
//StringSize = userString.charAt(character);
char[] StringToChar = userString.toCharArray();
for(int i = 0; i < StringToChar.length - 1; i++){
if ( StringToChar[i] == kChar){
character++;
}
}
System.out.println("character count is " + character);
}
}
I selected the letter using
char kChar = keyboard.next().charAt(0);
and converted the String to a Char array, ran a for loop going through each letter and checking if it was the same as the selected character. Each time the check was true I added one to the character counter.
Yes, you'll need to use a for loop.
int count = 0;
for (char ch: userString.toCharArray()) {
if(userChar == ch) count++;
}

Prevent the user entering numbers in java Scanner?

I am having some trouble preventing the user from entering numbers with the scanner class. This is what I have:
package palindrome;
import java.util.Scanner;
public class Palindrome {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String word;
String inverse = "";
System.out.println("Write a sentence or word: ");
while (!input.hasNext("[A-Za-z]+")) {
System.out.println("Not valid! Try again: ");
input.nextLine();
}
word = input.nextLine();
word = word.replaceAll("\\s+","");
word = word.toLowerCase();
int length = word.length();
length = length - 1;
for (int i = length; i >= 0; i--) {
inverse = inverse + word.charAt(i);
}
if (word.equals(inverse)) {
System.out.println("Is a palindrome.");
} else {
System.out.println("Is not a palindrome.");
}
}
}
Basically when I enter a word or sentence I want it to check if it has any numbers anywhere in the input, if it has then you need to enter another one until it doesn't. Here is an example of output:
Write a sentence or word:
--> 11
Not valid! Try again:
--> 1 test
Not valid! Try again:
--> test 1
Is not a palindrome.
As you can see it works for most cases, but when I enter a word FIRST and then a space followed by a number it evaluates it without the number. I am assuming this is happening because in the while loop is checking for only input.hasNext but it should be input.hasNextLine I believe to check the entire string. However I cannot have any arguments if I do that. Help much appreciated!
Change your regex from: [A-Za-z]+ to ^[A-Za-z]+$ in order to prevent numbers anywhere in the input-string

Sorting names entered by the user in alphabetical order according to the last name

I have completed most of the code by myself (with the help of a bit of Googling) but I have run into an unexpected problem. First-off, I have to sort a user entered list of names in aplhabetical order of their last names using selection sort. Here is my code:
import java.util.*;
class Name_Sort
{
public static void main (String args[])
{
Scanner in = new Scanner (System.in);
System.out.print ("Enter the number of names you wish to enter: ");
int n = in.nextInt();
String ar[] = new String [n];
for (int i = 0; i<ar.length; i++)
{
System.out.print("Please enter the name: ");
ar[i]= in.nextLine();
}
String temp;
for (int b = 0; b<n; b++)
{
for (int j=b+1; j<n; j++)
{
if ((compareLastNames(ar[b], ar[j]))>0)
{
temp = ar[b];
ar[b] = ar[j];
ar[j] = temp;
}
}
}
System.out.println ("The names sorted in alphabetical order are: ");
for (int a = 0; a<n; a++)
System.out.print (ar[a]+"\t");
}
private static int compareLastNames(String a, String b)
{
int index_a = a.lastIndexOf(" ");
String surname_a = a.substring(index_a);
int index_b = b.lastIndexOf(" ");
String surname_b = b.substring(index_b);
int lastNameCmp = surname_a.compareToIgnoreCase(surname_b);
return lastNameCmp;
}
}
The problem (I think) is arising when I'm taking the names from the user, specifically, this part:
Scanner in = new Scanner (System.in);
System.out.print ("Enter the number of names you wish to enter: ");
int n = in.nextInt();
String ar[] = new String [n]; //Array to store the names in.
for (int i = 0; i<ar.length; i++)
{
System.out.println("Please enter the name: ");
ar[i]= in.nextLine();
}
The output on the terminal window of BlueJ shows up as
Name_Sort.main({ });
Enter the number of names you wish to enter: 5
Please enter the name:
Please enter the name:
That is not what it's supposed to display. What could I be doing wrong? I've pondered over it for a while, but nothing comes to mind.
And, even if I do move forward and enter a few names despite the error above, I get another error in this part of my code here:
private static int compareLastNames(String a, String b)
{
int index_a = a.lastIndexOf(" ");
String surname_a = a.substring(index_a);// This is the line the compiler highlights.
int index_b = b.lastIndexOf(" ");
String surname_b = b.substring(index_b);
int lastNameCmp = surname_a.compareToIgnoreCase(surname_b);
return lastNameCmp;
}
the error is :
java.lang.StringIndexOutOfBoundsException: String index out of range: -1 (injava.lang.String)
Does this mean that the white-space character " " is not present? But why?
This is a screenshot of the terminal window:
http://imgur.com/l7yf7Xn
The thing is, if I just initialize the array with the names first (and not take any input from the user) the codes runs fine and produces the desired result. Any help please?
Also, since I know some people here are very particular about this, yes, this is a homework assignment, yes, I did do all of the code by myself, I googled on how to sort the names in alphabetical order as I couldn't exactly code out the original idea I had.
Which was comparing the ASCII values of each character of two surnames to see which should come first. Like: if((int) surname1.charAt(0)>(int) surname2.charAt(0)) then surname2 should come before surname1, else if they both have the same first character, take the second character and so on.
Thanks for taking the time to read this.
The problem is with the in.nextInt() command it only reads the int value. So when you continue reading with in.nextLine() you receive the "\n" Enter key. So to get around this you will have to add an extra in.nextLine() before going into the loop. Or, use another scanner.
int n = in.nextInt();
String ar[] = new String [n]; //Array to store the names in.
in.nextLine(); // < --- an extra next Line
for (int i = 0; i<ar.length; i++)
{
System.out.println("Please enter the name: ");
ar[i]= in.nextLine();
}

How to count the key characters?

I have the following code:
import java.util.Scanner;
public class chara{
public static void main(String[]args){
Scanner input = new Scanner(System.in);
System.out.println("Input a string");
String user=input.nextLine();
if(user.length()<7)
{
return;
}
else
{
}
System.out.println("now input a letter to be replaced");
String letter = input.next();
String user2 = user.replace(letter, "-");
String user3 = user.replace(letter, "");
System.out.println(user2);
System.out.println(user3);
}
}
the code needs to do three things take a string and a letter and :
replace the key letter in the string with "-"
remove the key letter of the string
count the amount of times the key letter appears.
At present I have two problems. I don't know how to count the amount of times the letter
appears because technically it is a string and not a char and i do not know how to count
strings. Second, I need to make it so that if the strings are not of the desired length it
simply asks again instead of exiting the program. I have tried to use the getString() method but for some reason it always says that the method is undefined.
For issue #1:
Near the top of the main method:
int count = 0;
After user3 is assigned:
count += (user3.length() - user.length());
With full credit to user1324109 for their solution to issue #1, here is how you can solve your issue #2:
import java.util.Scanner;
public class StringReader {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String user1 = "", user2 = "", user3 = "";
int count = 0;
while(user1.equals("") || user1.length() < 7) {
System.out.println("Input a string");
user1 = input.nextLine();
}
if(!user1.equals("")) {
System.out.println("now input a letter to be replaced");
String letter = input.next();
user2 = user1.replace(letter, "-");
user3 = user1.replace(letter, "");
System.out.println(user2);
System.out.println(user3);
count += (user1.length() - user3.length());
System.out.println("letter was found to be present "+count+" times");
}
}
}
To help with issue #3:
int count = 0;
for(char c : user.toCharArray() ){
if ( c == letter.charAt(0)) count++;
}
System.out.println("Number of occurences: "+count);

Categories