OK, now that I have change the public static String to public static int the last function does not print out.
Thank you all for you're help.
Here is the full program. The last function does not seem to print.
import java.lang.String;
import java.util.Scanner;
public class stringFuncts{
/**
* #param <String> <str> <Takes in a String and reverses it.>
* #return <rev> <returns the reversed string>
*/
public static String reverseString (String str){
String rev = "";
int length = str.length();
for ( int i = length - 1 ; i >= 0 ; i-- ){
rev = rev + str.charAt(i);
}
return rev;
}
/**
* #param <int> <n> <It will sum up the odds of a set number>
* #return <results> <Will print out the total of the odds values>
*/
public static int sumOfOdds (int n){
int results = 0;
for(int i = 1; i <= n*2; i += 2){
results = results + i;
}
return results;
}
/**
* #param <int> <blanks> <Will count the amount of whitespace in the phrase>
* #return <numBlanks> <Will return the amount of whitespace found in the String>
*/
public static int numberOfBlanks(String blanks){
int numBlanks = 0;
for(int i = 0; i < blanks.length(); i++) {
if(Character.isWhitespace(blanks.charAt(i)))
numBlanks++;
}
return numBlanks;
}
public static void main(String [] args){
Scanner input = new Scanner(System.in);
String str;
int n = 0;
String blanks;
System.out.println("Enter a string to reverse");
str = input.nextLine();
System.out.println("The reverse output is: " + reverseString(str));
System.out.println("");
System.out.println("Enter a value to sum the odds");
n = input.nextInt();
System.out.println("The sum of the odds " + sumOfOdds(n));
System.out.println("");
System.out.println("Enter a string to find the amount of blanks");
blanks = input.nextLine();
System.out.print("The number od blanks in the string is: " + numberOfBlanks(blanks));
}
}
In your numberOfBlanks() return type is of String data type
change it to int data type
Your function is declared as public static String. You're trying to return a number, so the correct declaration would be public static int.
import java.lang.String;
import java.util.Scanner;
public class stringFuncts{
/**
* #param <String> <str> <Takes in a String and reverses it.>
* #return <rev> <returns the reversed string>
*/
public static String reverseString (String str){
String rev = "";
int length = str.length();
for ( int i = length - 1 ; i >= 0 ; i-- ){
rev = rev + str.charAt(i);
}
return rev;
}
/**
* #param <int> <n> <It will sum up the odds of a set number>
* #return <results> <Will print out the total of the odds values>
*/
public static int sumOfOdds (int n){
int results = 0;
for(int i = 1; i <= n*2; i += 2){
results = results + i;
}
return results;
}
/**
* #param <int> <blanks> <Will count the amount of whitespace in the phrase>
* #return <numBlanks> <Will return the amount of whitespace found in the String>
*/
public static int numberOfBlanks(String blanks){
int numBlanks = 0;
for(int i = 0; i < blanks.length(); i++) {
if(Character.isWhitespace(blanks.charAt(i)))
numBlanks++;
}
return numBlanks;
}
public static void main(String [] args){
Scanner input = new Scanner(System.in);
String str;
int n = 0;
String blanks;
System.out.println("Enter a string to reverse");
str = input.nextLine();
System.out.println("The reverse output is: " + reverseString(str));
System.out.println("");
System.out.println("Enter a value to sum the odds");
n = input.nextInt();
System.out.println("The sum of the odds " + sumOfOdds(n));
System.out.println("");
input.nextLine();
System.out.println("Enter a string to find the amount of blanks");
blanks = input.nextLine();
System.out.print("The number od blanks in the string is: " + numberOfBlanks(blanks));
}
}
Output:
Enter a string to reverse
this
The reverse output is: siht
Enter a value to sum the odds
3
The sum of the odds 9
Enter a string to find the amount of blanks
this is spartan!
The number od blanks in the string is: 2
Related
I know how to code to find the factorial of a number:
public static void factorialcalculations()
{
int usernumber, calculation, fact = 1;
System.out.println("Enter an integer to calculate it's factorial");
Scanner in = new Scanner(System.in);
usernumber = in.nextInt();
if ( usernumber < 0 )
System.out.println("Number should be non-negative.");
else
{
for ( calculation = 1 ; calculation <= usernumber ; calculation++ )
fact = fact*calculation;
System.out.println("Factorial of "+usernumber+" is = "+fact);
{
But what I need is for is to display what numbers it is being multiplied by for example if it was 5
I need it to display the factorial is: 5*4*3*2*1=120
Use recursion. The value you want to display for n=1 is "1=". For any other n, it's "n*" + display(n-1).
display(2) => "2*" + display(1) => "2*1="
display(3) => "3*" + display(2) => "3*2*1="
and so on.
There is lot of ways to do it. With your existing code you can print it within your existing loop. Recursive will be the elegant way to find the factorial.
public static int factorial(int n) {
System.out.print("factorial is : ");
int result = 1;
for (int i = n; i >= 1; i--) {
result = result * i;
System.out.print(i!=1 ? (i+"*"): (i+"="));
}
System.out.println(result);
return result;
}
PS: As a best practice you need to handle the all scenarios in here. (String/negative/.. inputs)
Here is what you seem to be looking for man:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number whose factorial is to be found: ");
int n = scanner.nextInt();
int result = factorial(n);
System.out.println(getFactString(n,result));
}
public static int factorial(int n) {
int result = 1;
for (int i = 1; i <= n; i++) {
result = result * i;
}
return result;
}
public static String getFactString(int n, int result){
String output= "";
int count = n;
for (int i = count; i > 0; i--) {
if (n==1) {
output = output + n +" = ";
break;
}
output = output + n+" * ";
n--;
}
return output + result;
}
It's also possible to do this will StringBuilder as well. With the getFactorString() method, it doesn't matter what n is, you will get the correct string returned to display.
I want to take any user input integer between 1 and 9999 and return that number with its digits reversed. The problem with my code is it's returning the sum of the entered integer and I have no idea how to fix it. This is the code that that I came up with so far:
import java.util.Scanner;
class Reverse{
public static void main(String []args){
Scanner input = new Scanner(System.in);
System.out.print("Enter a number between 1 and 9999: ");
int user = input.nextInt();
if(user>1 && user<9999){
System.out.println("The number with its digits reversed is : " + reverseDigit(user));
}else{
System.out.println("Invalid Input");
}
}
public static int reverseDigit(int num){
return (num%10 + (num%100)/10 + (num%1000)/100 + num/1000); //This is the problem
}
}
You could replace :
return (num%10 + (num%100)/10 + (num%1000)/100 + num/1000);
with:
return ((num%10)*1000 + ((num%100)/10 )*100+ ((num%1000)/100)*10 + num/1000);
The reason that the first was wrong is because you get:
last digit:num%10
third digit:num%100)/10
second digit:(num%1000)/100
first digit:num/1000
so you was just adding all the digits before
But the Above works only for numbers from 1000-9999 .So you could replace the reverseDigit method with this simple method that works for every number:
public static int reverseDigit(int num){
int reverse=0;
while( num != 0 )
{
reverse = reverse * 10;
reverse = reverse + num%10;
num = num/10;
}
return reverse;
}
First, convert the number into a string then reverse the string and reconvert it into a number.
public static int reverseDigit(int num)
{
String str;
str = String.valueOf(num);
str = new StringBuilder(str).reverse().toString();
return (Integer.parseInt(str));
}
public static int reverseDigit(int num) {
int result = 0;
while(num != 0 ) {
result *=10;
int temp = num % 10;
result += temp;
num /=10;
}
return result ;
}
To do it using int (although String would be better).
public void test() {
System.out.println("Reversed: " + 1234 + " = " + reverseDigits(1234, 4));
}
public static int reverseDigits(int num, int digits) {
int reversed = 0;
for (int i = 0; i < digits; i++) {
reversed *= 10;
reversed += num % 10;
num /= 10;
}
return reversed;
}
My program reads in values from a file and uses a recursive method to print patterns of asterisks based on those values. I'm just having a problem getting everything to line up properly.
The output is supposed to look like this:
*
* *
* * *
* *
*
Regarding the format of the output, the directions are:
"Note that the pattern is aligned symmetrically (vertically) about the center line. The pattern should be aligned symmetrically on each line (horizontally) as well- hint: use the line value to help space."
But my output looks like this:
*
* *
* * *
* *
*
The code I'm using to get this pattern:
public static void makePattern(int thisRow, int num) {
if(thisRow >= num) {
for(int i = 0; i < num; i++) {
System.out.print(" " + "*" + " ");
}
System.out.println();
}
else {
for(int i = 0; i < thisRow; i++) {
System.out.print(" " + "*" + " ");
}
System.out.println();
makePattern(thisRow + 1, num);
for(int i = 0; i < thisRow; i++) {
System.out.print(" " + "*" + " ");
}
System.out.println();
}
}
Also my main method:
import java.util.Scanner;
import java.io.*;
public class Program3 {
public static void main(String[] args) throws Exception {
int num = 0;
int thisRow = 1;
java.io.File file = new java.io.File("../instr/prog3.dat");
Scanner fin = new Scanner(file);
while(fin.hasNext()) {
num = fin.nextInt();
if(num >=0 && num <= 25)
makePattern(thisRow, num);
System.out.println();
}
fin.close();
}
Any suggestions on how to edit my code to make my output appear like the example pattern I included?
Let's analyse the output first!!
First step is to analyse the output
Conclusions:
The total number of characters on every line is always n (=3)
Number of Spaces has the following pattern:
1st line 3 - 1 spaces
2nd line 3 - 2 spaces
3rd line 3 - 3 spaces
4th line 4 - 3 spaces
5th line 5 - 3 spaces
So
if(num < thisRow) {
numberOfSpaces = thisRow - num;
} else {
numberOfSpaces = num - thisRow;
}
Number of Stars is always [n - the number of spaces]
So
int numberOfStars = num - numberOfSpaces;
And the recursion should end on the 6th line, i.e. when current line number is n*2
So the return condition in your recursive method should be
if(thisRow == num * 2)
return;
Final Code : Putting the peices together
When we put the peices together, we get:
public static void makePattern(int thisRow, int num) {
//the termination condition
if(thisRow == num * 2)
return;
//the number of spaces
int numberOfSpaces = 0;
if(num < thisRow) {
numberOfSpaces = thisRow - num;
} else {
numberOfSpaces = num - thisRow;
}
//the number of stars
int numberOfStars = num - numberOfSpaces;
//compose the string before printing it
StringBuffer outputBuffer = new StringBuffer(num);
for (int i = 0; i < numberOfSpaces; i++){
outputBuffer.append(" ");
}
for (int i = 0; i < numberOfStars; i++){
outputBuffer.append("* ");
}
//print the string
System.out.println(outputBuffer.toString());
//recursion
makePattern(thisRow + 1, num);
}
This is code for printing diamond shaped pattern using recursion technique.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class patternRecursion {
static int n,k;
public static void main(String[] args) throws IOException{
try(Scanner s = new Scanner(System.in)){
n=Integer.parseInt(reader.readLine());
k=n-1;
printPattern(n);
}
}
public static void printChar(int m,char c){
if(m==0) return;
try{
printChar(m-1,c);
System.out.print(c);
}catch(StackOverflowError s){return;}
}
public static void printPattern(int m){
if(m==0){
return ;
}else{
printChar(m-1,' ');
printChar(n-m,'#');
printChar(n-m+1,'#');
System.out.println();
printPattern(m-1);
printChar(m,' ');
printChar(k-m,'#');
printChar(k-m+1,'#');
System.out.println();
}
}
}
I have a program that I have been working on for quite awhile now. I am need to make a program that solves a user specified summation puzzle through backtracking.
The user enters three separate strings, the first two strings added together should equal the third string.
example:
java + next = scala
4656 + 7980 = 12636
I believe I am on the right track, but I need to take the index's of each value on the <Character> ArrayList and have them sum to a number less than 20,000. How would I go about doing this?
below is the code I have so far:
import java.util.*;
public class SummationPuzzle
{
public static ArrayList<Character> fsList = new ArrayList<Character>();
public static ArrayList<Character> lastW = new ArrayList<Character>();
public static ArrayList<Character> finaList = new ArrayList<Character>();
/**
* Reads in 3 words entered by user and converts the first two string into a single <Character> ArrayList
* takes the third string entered and converts it into it's own <Character>ArrayList
* #param firstW
* #param secondW
* #param thirdW
*/
public static void convertStr(String firstW, String secondW, String thirdW)
{
String combined = firstW + secondW;
for(int i = 0; i< combined.length(); i++)
{
fsList.add(combined.charAt(i));
}
for(int j = 0; j< thirdW.length(); j++)
{
lastW.add(thirdW.charAt(j));
}
System.out.println( fsList +" "+lastW);
swapAdd(fsList, lastW);
//feeds the resulting lists into the swapAdd method
}
/**#param
* This method Swaps the first char of fsList with the char at fsList[1]to make sure it matches the char at lastW[1]
* #param fsList
* #param lastW
*/
public static void swapAdd(ArrayList<Character> fsList, ArrayList<Character> lastW)
{
Collections.swap(lastW, 0,1);
System.out.println(lastW + " lastW swap first char");
char temp = lastW.get(1);
int j= 0;
System.out.println(fsList+ " before swap");
if(!fsList.get(1).equals(temp) && fsList.contains(temp))
{
j = fsList.indexOf(temp);
Collections.swap(fsList,1,j);
}
System.out.println(fsList+ " after swap");
removeDuplicate(fsList, lastW);
}
/**
* Combines two <Character> ArrayList into a one <Character> ArrayList with single instances of the char
* #param fsList
* #param lastW
*/
public static void removeDuplicate(ArrayList<Character> fsList, ArrayList<Character> lastW)
{
ArrayList<Character> tempList = new ArrayList<Character>();
tempList.addAll(fsList);
tempList.addAll(lastW);
for(char dupLetter : tempList)
{
if(!finaList.contains(dupLetter))
{
finaList.add(dupLetter);
}
}
System.out.println(finaList + "This is the list with duplicates removed");
System.out.println(lastW);
}
//main method
public static void main(String[] args)
{
//Receive user input
Scanner userIn = new Scanner(System.in);
System.out.println("Please enter your first word");
String firstW = userIn.next().trim();
System.out.println("Please enter your Second word");
String secondW = userIn.next().trim();
System.out.println("Please enter your Third word");
String thirdW = userIn.next().trim();
//print the summation puzzle
System.out.println(firstW+ " + " + secondW + " = "+ thirdW);
convertStr(firstW, secondW, thirdW);
}
}
Note: Just a practice problem, not for marks.
This is a practice problem given in a first year Java course:
Design and implement an application that reads an arbitrary number of integers, by the user, that are in the range 0 to 50 inclusive, and counts how many occurrences of each are entered. After all the input has been processed, print all of the values (with the number of occurrences) that were entered one or more times.
In addition, write a method that returns no value which would compute the average of the occurrences of all numbers entered by the user.
This is what I have (I have skipped the "average occurrence" part until I clean this up):
import java.util.Scanner;
public class Main
{
public static Scanner scan = new Scanner(System.in);
public static int[] userIntegers() // this method will build the array of integers, stopping when an out-of-range input is given
{
System.out.println("Enter the number of integers to be recorded: ");
int numInts = scan.nextInt();
int[] userArray = new int[numInts];
int i = 0;
while(i < numInts)
{
System.out.println("Enter an integer between 1-50 inclusive: ");
int userInteger = scan.nextInt();
if(isValidInteger(userInteger))
{
userArray[i] = userInteger;
i++;
}
else if(isValidInteger(userInteger) == false)
{
System.out.println("Try again.");
}
}
return userArray;
}
public static void occurrenceOutput(int[] input) // this method will print the occurrence data for a given array
{
int[] occurrenceArray = new int[51];
int j = 0;
while(j < 51) // iterates through all integers from 0 to 50, while the integer in the array is equal to integer j, the corresponding occurance array element increments.
{
for(int eachInteger : input)
{
occurrenceArray[j] = (eachInteger == j)? occurrenceArray[j]+=1: occurrenceArray[j];
}
j++;
}
int k = 0;
for(int eachOccurrence : occurrenceArray) // as long as there is more than one occurrence, the information will be printed.
{
if(eachOccurrence > 1)
{
System.out.println("The integer " + k + " occurrs " + eachOccurrence + " times.");
}
k++;
}
}
public static boolean isValidInteger(int userInput) // checks if a user input is between 0-50 inclusive
{
boolean validInt = (51 >= userInput && userInput >= 0)? true: false;
return validInt;
}
public static void main(String[] args)
{
occurrenceOutput(userIntegers());
}
}
Can someone point me in a more elegant direction?
EDIT: Thanks for the help! This is where I am at now:
import java.util.Scanner;
public class simpleHist
{
public static void main(String[] args)
{
getUserInputAndPrint();
getIntFreqAndPrint(intArray, numberOfInts);
}
private static int numberOfInts;
private static int[] intArray;
private static int[] intFreqArray = new int[51];
public static void getUserInputAndPrint()
{
// The user is prompted to choose the number of integers to enter:
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of Integers: ");
numberOfInts = input.nextInt();
// The array is filled withchInteger = integer; integers ranging from 0-50:
intArray = new int[numberOfInts];
int integer = 0;
int i = 0;
while(i < intArray.length)
{
System.out.println("Enter integer value(s): ");
integer = input.nextInt();
if(integer > 50 || integer < 0)
{
System.out.println("Invalid input. Integer(s) must be between 0-50 (inclusive).");
}
else
{
intArray[i] = integer;
i++;
}
}
// Here the number of integers, as well as all the integers entered are printed:
System.out.println("Integers: " + numberOfInts);
int j = 0;
for(int eachInteger : intArray)
{
System.out.println("Index[" + j + "] : " + eachInteger);
j++;
}
}
public static void getIntFreqAndPrint(int[] intArray, int numberOfInts)
{
// Frequency of each integer is assigned to its corresponding index of intFreqArray:
for(int eachInt : intArray)
{
intFreqArray[eachInt]++;
}
// Average frequency is calculated:
int totalOccurrences = 0;
for(int eachFreq : intFreqArray)
{
totalOccurrences += eachFreq;
}
double averageFrequency = totalOccurrences / numberOfInts;
// Integers occurring more than once are printed:
for(int k = 0; k < intFreqArray.length; k++)
{
if(intFreqArray[k] > 1)
{
System.out.println("Integer " + k + " occurs " + intFreqArray[k] + " times.");
}
}
// Average occurrence of integers entered is printed:
System.out.println("The average occurrence for integers entered is " + averageFrequency);
}
}
You are actually looking for a histogram. You can implement it by using a Map<Integer,Integer>, or since the range of elements is limited to 0-50, you can use an array with 51 elements [0-50], and increase histogram[i] when you read i.
Bonus: understanding this idea, and you have understood the basics of count-sort
To calculate occurences, you can do something like this:
for(int eachInteger : input) {
occurrenceArray[eachInteger]++;
}
This will replace your while loop.