Position method to use with countletters method. - java

I have updated my code with two methods to use instead of the previous one. But I'm still stuck and don't know How can I create and call a method that will replace Character.isLetter(s.charAt(i)). This method is suppose to receive a char, and return a int to be used with the countLetter() method.
The methods are:
int [] countLetters (string s), int pos(char x), and void printResults(int[] counts)
And yes, the int [] countLetters does need to return an array. I'm just wondering how to get the pos method to work instead of the character.isLetter.
Here is what I got so far:
import java.util.Scanner;
public class CharCount {
public static Scanner kbd = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Enter a string: ");
printResults(null);
}
/*
* This method counts the number of occurrences in the inputed
* string and returns the array with the count.
*/
public static int[] countletters(String s){
int[] counts = new int[26];
for(int i = 0; i < s.length(); i++){
if (Character.isLetter(s.charAt(i))){
counts[(int)s.charAt(i) - 'a']++;
}
}
return counts;
}
public static int pos(char x){
return (int)charAt();
}
private static int charAt() {
// TODO Auto-generated method stub
return 0;
}
/*
* This method prints the results of the string count
*/
public static void printResults(int[] counts){
String s = kbd.nextLine();
counts = countletters(s.toLowerCase());
System.out.println("\nLetter frequencies:");
for (int i =0; i < counts.length; i++){
if (counts[i] != 0){
System.out.println((char)('a' + i) + " - " + counts[i] );
}
}
}
}
I feel like I need to start with counts[(int)s.charAt(i) - 'a']++ and move it to the print method.
Thanks.

I won't post code for you, as this is homework, but your pos method should return the relative position of the char in the alphabet. So 'a' would return 0, 'b' returns 1, 'c' returns 2,...
Myself, I'd change the char upper case or lower case, your choice, then subtract a number (or actually a char) from it, and return it.
Then the pos(...) method will be used in the countletters(...) method inside of the for loop to determine which array index to increment. Note that you should discared your charAt() method since it serves no purpose other than to confuse.

Related

Alternate Character arrangement using java

public class Main {
public static int count = 0;
public static void main(String[] args) {
String str = "AAAA";
System.out.println(delete1(str));;
}
private static int delete1(String str) {
if (str.length() > 1) {
for (int i = 1; i < str.length(); i++) {
if (str.charAt(i-1) == str.charAt(i)) {
count++;
str = str.substring(i, str.length());
delete1(str);
}
}
}
return count;
}
}
count should come as 3 in this case...but coming as 4
For loop inside recursive method does not have break statement. put break; statement after delete1(str); statement will work.
delete1(str);
break;
while using recursive you should know where to break the loop and how functional flow happens in java.
in your case for all sub strings of length more than 2 will call delete method more than once. that's why you got output as 4.
There are multiple things wrong with your code:
You have the count on class-level and also let your method return this count.
You continue your loop after your recursive call
Not really wrong, but your if(str.length() > 1) check is redundant since your loop is already looping in the range [1, length), so the loop wouldn't start anyway if the length is smaller than or equal to 1.
Keeping the things above in mind, you could change it to this:
class Main {
public static void main(String[] args){
String str = "AAAA"; // Expected output: 3
countChars(str);
System.out.println(count);
}
private static int count = 0;
private static void countChars(String str){
int length = str.length();
for(int i = 1; i < length; i++){
if(str.charAt(i-1) == str.charAt(i)){
count++;
String substr = str.substring(i, length);
countChars(substr);
break;
}
}
}
}
Which puts the count at 3 in the end as you expected.
Try it online.
I'm still not entirely sure what you are trying to accomplish however. For example, what would the expected output be for AAAABABBAB or ABAAAAABBABA? Also, it would be better if the count isn't a static class-level field so it can more easily be re-used.

Java - breaking out of a incursion method and returning the value

Good morning all,
Today is my first time trying to make a recursion method. Just when I thought it would work I got the error; missing return statement. This confuses me because it literally has a return value ( the total string from the Stringbuilder ) after n < 1
This is what I got:
import java.util.Scanner;
public class P5_4MethodRepeatString {
public void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string followed by the times you want
it repeated:");
String input = sc.nextLine();
int count = sc.nextInt();
String total = repeat(input, count);
System.out.println(total);
}
public static String repeat(String str, int n) {
StringBuilder full = new StringBuilder();
if(n < 1) {return full.toString();}
repeat(str, n - 1);
for(int i = 0; i < n; i++){
full.append(str);
}
}
}
if(n < 1) {return full.toString();} but if n >= 1 you don't return anything. It should be return repeat(str, n - 1); but then you need to move the for... part
The immediate cause of your problem is that not all conditional flows in your repeat() method have a return value. But I am not sure if even making that change would result in working code. Consider the following refactor:
public void repeat(StringBuilder result, String str, int n) {
if (n == 0) return;
result.append(str);
repeat(result, str, n - 1);
return;
}
Here we are passing in a StringBuilder object which we want to contain our repeated string results. We also pass the string to be repeated, and the number of remaining turns. The base case occurs where there are no more turns, in which case we simply return from the recursive method. Otherwise, we add one copy of the string and make a recursive call.
Your original recursive attempt had the following for loop:
for (int i=0; i < n; i++) {
full.append(str);
}
This does not look recursive, and looping to repeatedly add the string defeats the point of doing recursion (though I would probably use a loop in real life if I had to do this).

Java Testing if a variable equals a value in the array if not print -1

I need to see when a given variable value in an array is first occurred and once occurred change that variable to the number when it first occurs, and if it does not occur than change the value to -1.
For example 32 appears first in the array so it should print 1 but 100 never appears in the array so it should print -1 but how do I make a second if statement in my loop so that the variable will be -1 but it test the original value to find it appears. Sorry if I did not explain it well enough.
here is the code for the loop and the first if statement
public static int occurrence(int[] a) {
Scanner scnr = new Scanner(System.in);
int occurrence = scnr.nextInt();
for (int i = 0; i < a.length; i++)
if (a[i] == occurrence)
occurrence = i + 1;
return occurrence;
The JDK library comes with an Arrays class just for things like this.
First, import the class:
import java.util.Arrays;
Now all you have to do is this:
System.out.println(Arrays.binarySearch(a, occurrence));
And that's basically it. The "binarySearch()" method takes two parameters, those being the name of the array you're referencing (a), and the value you are searching for in that array (occurrence). It then returns the index of the value. If the value is not found in the array, it returns -1.
Take a look at this. Try to separate your input code (scanner) from the function logic. That will make the occurrence method reusable.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
int data[] = { 2,5,7};
Scanner scnr = new Scanner(System.in);
int inputValue = scnr.nextInt();
int index = occurrence( data, inputValue);
System.out.println("value at index: " + index);
}
//
// find first match, then exit the loop if found.
//
public static int occurrence(int[] a, int inputValue) {
int result = -1;
for (int i = 0; i < a.length; i++)
if (a[i] == inputValue) {
result = i;
break;
}
return result;
}
}

"Method in class cannot be applied to given types" error when trying to call method

I'm new here so if my question is wrong somehow let me know and I apologize in advance.
I'm creating a program for taking user input, putting it into an array and then reverse the arrays and checking for palindromes. The program will then print the palindromes from 101 to the user input number. Right now I just want to check if the loop I created for reversing the arrays is working, but when I call on the method I get the error
"method reverseArray in class Palindrome cannot be applied to given types"
required: char[]
found: no arguments
reason: actual and formal arguments differ in length
Here is the code (bottom three methods are empty right now because I haven't gotten to writing them yet).
public static void main(String[] args)
{
Scanner promptUser = new Scanner(System.in);
System.out.print("Enter an Integer greater than 100: ");
Integer userInt = new Integer(promptUser.nextInt());
String userString = userInt.toString();
char[] charUser = userString.toCharArray();
if (userInt <= 100)
{
System.out.print("That integer is not greater than 100,"
+ " restart program and try again!");
}
System.out.println(reverseArray());
}
/**Takes the integer provided by the user and turns it into a string
* then takes that string and puts it into a char[], then there is a for loop
* to reverse that array.
* #param userArray array used to store the reversed string.
* #revArray char array used to store data from charChange array.
* #return returns charChange now with the reversed string.
*/
public static char[] reverseArray(char[] userArray)
{
char[] revArray = new char[userArray.length];
for(int i = 0; i < revArray.length; i++)
{
userArray[i] = revArray[revArray.length - 1 - i];
}
return userArray;
}
public static boolean arraysAreEqual(char[] arrayPal1, char[] arrayPal2)
{
}
public static boolean isPrime(int Primes)
{
}
public void printArray(char[] charChange)
{
}
You didn't pass any paramter to function, and it expect array as a paramter:
reverseArray(charUser);
and are you expecting to print the array through
System.out.println(reverseArray());
this will print the address for the array, you will have to loop over the array elements to print it, something like:
char[] resultArray = reverseArray(charUser);
for(int i = 0; i < resultArray.length; i++)
{
System.out.println(resultArray[i]);
}

How to find end of line and perform addition of two integer arrays in java?

How to find how many tokens are there in a line in the below program and then
I need to add two integer arrays using Java, since I am more familiar with php, this is a bit challenging for me . Also I am getting the input from a text file. Hence, here is how I have my program so far.
The input file would have multiple lines like this
3736 17234 29823 84478 123745 2371 34237 823712
import java.io.*;
import java.util.*;
public class Sum {
//must use a constant for the length of the array
static int[] total= new int[25];
static int[] val = new int[25];
static int line= 0;
static int word =0;
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(new File("Input.txt"));
// System.out.println("0");
processFile(input);
}
public static void processFile(Scanner input) {
//in this method you need to read your input file
//. read one line at a time and call the method processLine to
while (input.hasNextLine())
{
line++;
String line = input.nextLine();
Scanner lineScan = new Scanner(line);
//System.out.println("1");
processLine(input);
//System.out.println(line);
}
}
public static void processLine(Scanner data) {
//in this method you read tokens from line that has been passed to
// this methd as the parameter. method transfer needs to be called to
// transfer each token into an array of length DIGITS. Note that in a
// line you might only have one token
while(data.hasNext())
{
String x = data.next();
//System.out.println("2");
transfer(x,val);
}
}
public static void transfer(String data, int[] digits) {
//This method transfer the string into array of integers value.
int len = data.length();
int n=24;
for(int i=0;i<=n;i++)
digits[i]=0;
//System.out.println("3");
while(len>0)
{
// System.out.println(data.charAt(len-1));
char z=data.charAt(len-1);
int d = Character.digit (z, 10);
digits[n]=d ;
len=len-1;
n=n-1;
}
for(int i=0;i<=n;i++)
digits[i]=0;
for(int i=0;i<25;i++)
{
//System.out.println(digits[i]);
}
System.out.println("\n");
add(digits);
}
public static void add(int[] digits) {
word++;
if (word>1)
{
for(int i=0; i<= 4; i++)
{
total= total[i]+digits[i];
}
}
if(word==0)
total=digits;
}
public static void print(int[] digits) {
//For printing
}
}
Use a for loop to go through the 2 arrays and add each element.
Quick example code below:
private int[] sumTwoArrays(int [] a, int [] b){
if(a.length!=b.length){
throw new IllegalArgumentException("Arrays are not of same length!");
}
int[] sum = new int[a.length];
for(int i=0;i<a.length;i++){
sum[i] = a[i]+b[i];
}
return sum;
}
UPDATE: After the comments below I added another method on how to add just the elements in one array.
private void readFile(){
long sum=0;
//do your FILE I/O here
//for each line you read into an array called input[] you call this method
sum += sumArray(input);
System.out.println(sum);
}
private long sumArray(long [] a){
long sum=0;
for(int i=0;i<a.length;i++){
sum += a[i];
}
return sum;
}
You complicated this far more than is necesary.
To begin with, you can remove the multiple function references, the scanner class can actually parse your file into integers, and can read multiple lines - so you don't need a new scanner for each line.
I think you can simply have one Scanner per file, and then constantly use the Scanner.nextInt() function to find the next integer value in that file.
Now depending on your definition of add, there are two things you could do.
If you're attempting to add corresponding elements of each array, to come with with a third array where x[i] = y[i] + z[i], then you simply need a for loop with the previous statement in it. Remember of course to substitute the real names of the variables.
If you're attempting to add up all the integers in both the arrays to get one integer (or long), you could use two for loops, one after another and constantly add the current element of the current array to a variable.

Categories