How to invoke method to print? - java

https://its.hvcc.edu/jojo/?p=297
Doing this assignment I need the results of the method to print but I cant figure out how to invoke them.
public static int numWhitespace(String s) {
int count = 0,x;
for(x = 0; x<s.length();x++)
if(Character.isWhitespace(s.charAt(x)))
count++;
return count;
}
public static void main (String[] args) {
Scanner kb = new Scanner(System.in);
System.out.println("Enter a string for character classification: (EOF to end):");
while (kb.hasNext()){
String input = kb.nextLine();
System.out.println("inputLine = "+ input +"");
System.out.println("inputLine is "+ input.length() +" characters long and contains the following:");
System.out.println(); //Where i want all the other stuff
System.out.println("Enter a string for character classification: (EOF to end):");
}
}

You can call the numWhitespace() method like this:
System.out.println("whitespaces = " + numWhitespace(input));
or save it in a variable first:
int whitespaces = numWhitespace(input);
System.out.println("whitespaces = " + whitespaces);

Related

How can I get my output to be separated by commas based on user input from scanner?

I have a class which takes keyboard input, how could I go about making it so that it can take multiple double and char inputs on one line e.g. 1 2 a a a to then get the output:
"1","2","a","a","a" by splitting it into separate strings? this is what I've done so far:
public class MyInputInfo implements Comparable <MyInputInfo> {
public static double numeric;
public static char symbol;
public MyInputInfo(double numeric, char symbol) {
this.numeric = numeric;
this.symbol = symbol;
}
public static char getSymbol() {
int asciiValue = 97;
for (int i = asciiValue; i <= 122; i++) {
String convertedChar = Character.toString ((char) i);
System.out.println (convertedChar);
}
return symbol;
}
#Override
public int compareTo(MyInputInfo o) {
if (this.numeric < o.numeric) {
return 1;
} else if (this.getSymbol( ) < o.getSymbol ( )) {
return -1;
} else {
return 0;
}
}
#Override
public String toString() {
return "Numeric " + numeric + " Symbol " + symbol;
}
}
the class im working on right now
import java.util.*;
public class MyKeyboardInput {
public static void main(String[] args) {
Scanner s = new Scanner (System.in);
MyInputInfo.numeric = s.nextDouble();
MyInputInfo.symbol = s.next ( ).charAt (0);
System.out.println (MyInputInfo.numeric+ "," + MyInputInfo.symbol);
}
}
I'm new to java so apologies for coming off as slow. All help is appreciated!
There are two options:
Obtain numbers and chars in predictable order
Obtain numbers and chars in random order
Obtain numbers and chars in predictable order
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number of iterations: ");
int count = scanner.nextInt();
StringBuilder buffer = new StringBuilder();
for (int i = 0; i < count; i++) {
System.out.print("\nEnter a floating point number: ");
buffer.append(scanner.nextDouble() + " ");
System.out.print("\nEnter a character: ");
buffer.append(scanner.next().charAt(0) + " ");
}
scanner.close();
String output = buffer.toString().trim().replaceAll(" ", ", ");
System.out.println(output);
}
If you enter 1 a 2 b 3 c 4 d 5 e, the output will look like this
1.0, a, 2.0, b, 3.0, c, 4.0, d, 5.0, e
It's really that simple. The key is to use StringBuilder to "stage" the input and then convert all of the individual inputs into a single String output. To make it easier to remove the last comma, I just separated the entries by spaces, trimmed the string to remove the last space, and then prepended the remaining spaces with a comma.
Obtain numbers and chars in random order
This solution is similar, but in this case, just capture the input as a String and then figure out if the input is numeric or not. If it is not numeric, then it is a character.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number of iterations: ");
int count = scanner.nextInt();
StringBuilder buffer = new StringBuilder();
for (int i = 0; i < count; i++) {
System.out.print("\nEnter a number or character: ");
String s = scanner.next();
try {
Double num = Double.parseDouble(s);
buffer.append(num + " ");
} catch (NumberFormatException nfe) {
buffer.append(s.charAt(0) + " ");
}
}
scanner.close();
String output = buffer.toString().trim().replaceAll(" ", ", ");
System.out.println(output);
}
Caveats
You need to figure out what to do when something like "character" is provided as input. As you can see in the code, the code captures only charAt(0). This might or might not be correct for your use. But, this is typically how it is portrayed on the web how to get character from Scanner in Java.
Also, there is no error handling on the first solution if the input is not a number. You could try to prompt again if the character entered is not a number. Likewise, when prompted to enter a character, what happens if the input is a number? You will need to tweak the code to do what you want. With the second approach, you don't have to worry about this.

Problem: printing an index, value of index, length index in an array has a loop

import java.util.Scanner;
public class missYou {
public static void main(String[] args) {
System.out.println("Words");
System.out.print("Enter words: ");
Scanner input = new Scanner(System.in);
String word = input.nextLine();
String[] parts = word.split(" ");
String max = parts[0];
int max_box; int parts_L = parts.length;
int max_L; int i;
for (i = 1; i < parts_L; i++) {
if (parts[i].length() > max.length()) {
max = parts[i];
max_box = i;
max_L = parts[i].length();
}
}
/* the problem occurs in the next line where it does not print the max value,
and it considers max_L without a value which I did give it a value in the
loop and the I value should be the same as the index of the longest
string but it gives me the last index in the array */
System.out.print("The longest word is " + max + " contain " +
max_L + " letters, in box " + i);
input.close();
}
}
The problem is that you are mixing i with max_box. The following should work as you expect:
public class missYou {
public static void main(String[] args) {
System.out.println("Words");
System.out.print("Enter words: ");
Scanner input = new Scanner(System.in);
String word = input.nextLine();
String[] parts = word.split(" ");
String longestWord = parts[0];
int longestWordSize = longestWord.length();
int longestWordLocation = 0;
for (int i = 1; i < parts.length; i++) {
if (parts[i].length() > longestWordSize) {
longestWord = parts[i];
longestWordLocation = i;
longestWordSize = longestWord.length();
}
}
System.out.print("The longest word is " + longestWord + " contain " +
longestWordSize + " letters, in box " + longestWordLocation);
input.close();
}
}
Additionally, try to be explicit when naming your variables, max_L and max_box are not very good names because they are hard to understand.

Using a for loop to call a character method multiple times. The for loop will then convert each character to a string

The output should look like the attached screenshot. I am stuck on the very last step. Using a for loop to call the getCharacter method 10 times and converting the characters to a string using the Character.toString() method.
``
public static void main(String[] args) {
int count = countNumbers();
countPlay(count);
String word = getCharacter();
stringOf10(word);
}
public static double getRealNumber(){
Scanner sc = new Scanner(System.in);
System.out.print("Enter a real number, one that has a decimal point: ");
double realNumber = sc.nextDouble();
return realNumber;
}
public static int countNumbers(){
int count = 0;
do{
if (getRealNumber() == -1.0)
break;
count++;
} while(true);
System.out.println("The count is " + count);
return count;
}
public static int countPlay(int count){
int exponent = 4;
double result = 0;
result = Math.pow(count, exponent);
System.out.println(count + "^" + exponent + " is " + result );
return count;
}
public static char getCharacter(){
Scanner input = new Scanner(System.in);
System.out.println("You will be asked to enter 10 characters.");
System.out.print("Enter a character: ");
char character = input.next().charAt(0);
return character;
}
public static char stringOf10(String word){
char i = getCharacter();
i = Character.toString(word) ;
for (i = 0; i < 10; i++){
}
return word;
}
}
``
Consider the following block of code which will run in the main method:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String word = "";
//Print the instructions before the loop
System.out.println("You will be asked to enter 10 characters.");
//request characters inside the loop
for (int i = 0; i < 10; i++){
System.out.print("Enter a character: ");
word += input.next().charAt(0);
}
//print the result (or return from a method)
System.out.println("The word is: " + word);
//return word;
}
Besides the corrections in comments, note how we create a local variable word, and simply update/append that inside the for loop word += input.next().charAt(0);.
You can easily move this code to fit your needs and return the value to be printed:
public static void main(String[] args) {
//Call the method to get our word and save the result
String result = stringOf10();
//Print the result
System.out.println("The word is: " + result);
}
public static String stringOf10(){
//Creater a scanner once before the loop
Scanner input = new Scanner(System.in);
//Create a local variable to store the word as it is updated
String word = "";
//Print the instructions once before the loop
System.out.println("You will be asked to enter 10 characters.");
//Create a loop that will run 10 times "for (int i = 0; i < 10; i++)"
//The loop starts by creating an int that is 0 "int i=0"
//Each time the loop ends it will do "i = i+1"
//The loop will run until i is no longer less than 10 "i < 10"
//Once that happens the loop will end and the code after the loop will run
for (int i = 0; i < 10; i++){
//Dach time the loop will call this method and update the word
word += getCharacter(input);
}
return word;
}
public static char getCharacter(Scanner input){
//Each time this method is called we prompt the user to enter a character
System.out.print("Enter a character: ");
//We then return the character to the previous method
return input.next().charAt(0);
}

So my problem in this is that I cannot seem to add a void function in my code

I want to insert a void function in my code.
import java.util.*;
public class javellana {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Input String: ");
String str = scan.nextLine();
System.out.println("Input character: ");
char str1 = scan.next().charAt(0);
int num = str.length();
int i;
for (i = num - 1; i >= 0; i--) {
if (str1 == str.charAt(i)) {
System.out.println("The character " + str1 + " you intput is " + i);
break;
}
}
}
}
That is my code and I want to add a void function starting in "for". I want the for loop to be in a void function but I can't seem to do it. How do I fix this?
public class javellana {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Input String: ");
String str = scan.nextLine();
System.out.println("Input character: ");
char str1 = scan.next().charAt(0);
int num = str.length();
tt(num,str1,str);
}
static void tt(int num , char str1, String str)
{
for(int i = num - 1; i >= 0; i--) {
if (str1 == str.charAt(i)) {
System.out.println("The character " + str1 + " you intput is " + i);
break;
}
}
}
}
Apart from the code, what you wanna achieve from this is still
unclear.
You can add a void method as static and use it directly in main method.
public class javellana {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Input String: ");
String str = scan.nextLine();
System.out.println("Input character: ");
char str1 = scan.next().charAt(0);
int num = str.length();
int i;
func(str, str1);
}
static void func(String str, char str1) {
int num = str.length();
for (int i = num - 1; i >= 0; i--) {
if (str1 == str.charAt(i)) {
System.out.println("The character " + str1 + " you intput is " + i);
break;
}
}
}
}
EDIT:
You can simply use System.out.println(str.lastIndexOf(str1)); line, instead of the entire for loop for your problem
public class javellana {
String str;
char str1;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Input String: ");
str = scan.nextLine();
System.out.println("Input character: ");
str1 = scan.next().charAt(0);
func(); // call function here
}
static void func() {
int num = str.length();
for (int i = num - 1; i >= 0; i--) {
if (str1 == str.charAt(i)) {
System.out.println("The character " + str1 + " you intput is " + i);
break;
}
}
}
}
Try this for change
If
adding a void function
means adding(declaring) another method(function) in public static void main(String){};
then this is not allowed.
What you can do is; create an anonymous class or functional interface (Java 8). Which is not exactly what you want but somehow..
main() is static method, so only static method can be used from it.
Instead of using for loop, you can use String.lastIndexOf() method.
public static void main(String... args) {
try (Scanner scan = new Scanner(System.in)) {
System.out.print("Input String: ");
String str = scan.nextLine();
System.out.print("Input character: ");
char ch = scan.next().charAt(0);
lastIndexOf(str, ch);
}
}
private static void lastIndexOf(String str, char ch) {
int i = str.lastIndexOf(ch);
if (i >= 0)
System.out.println("The character " + ch + " you input is " + i);
}
You can't create a method within a method.
Currently, you're in main method.
But you can call as many methods you want from a method.
But there's some restriction. you can't call the nonstatic method within a static method.
Therefore the #pkgajulapalli answer is probably correct.

How to print return from overloaded methods in Java

I'm trying to sum the Ascii values of different strings while adhering to the following instructions:
Create two overloaded methods. One that will give the sum of the
ascii values of each character in a String and another which will
produce the sum of the ascii values of two Strings.
Using the methods that I already wrote, how could I print out the sum in my main? Thanks!
public class Exam3Question2
{
public static int sumAscii(String Input)
{
String s = Input;
int sum = 0;
for (int i = 0; i < s.length(); i++)
{
sum+= (int)s.charAt(i);
}
return sum;
}
public int sumAscii( String Input1, String Input2)
{
int sum = sumAscii(Input1) + sumAscii(Input2);
return sum;
}
public static void main(String[] args)
{
Exam3Question2 c = new Exam3Question2();
Scanner in = new Scanner(System.in);
String word;
System.out.println("Enter some text");
word = in.nextLine();
sumAscii(word);
int sum1 = c.sumAscii(Input1);
int sum2 = c.sumAscii(Input1, Input2);
int sum3 = sum1 + sum2;
System.out.println("The sum of the two strings is: " + sum3);
}
}
You may want to change your method for calculating the one String to this, so it takes the String as parameter and move the userInput outside of the method, to make it more clean
public int sumAscii(String userInput)
{
String s = userInput;
int sum = 0;
for (int i = 0; i < s.length(); i++)
{
sum+= (int)s.charAt(i);
}
return sum;
}
And your next method could actually use the previous method in the new overloaded method like this:
public int sumAscii(String userInput1, String userInput2)
{
int sum = sumAscii(userInput1) + sumAscii(userInput2);
return sum;
}
And your main would look like
public static void main(String[] args)
{
//something to invoke constructor and get strings
int sum1Str= sumAscii(userInput1)
int sum2Str = sumAscii(userInput1,userInput2)
System.out.println("The sum of one string is "+sum1Str);
System.out.println("The sum of two strings is " +sum2Str);
}
Using the two methods that you have written you would print like this
Exam3Question2 c = new Exam3Question2();
int one = c.sumAscii(0);
int two = c.sumAscii(0, 0);
System.out.println("The sum of one String is " + one);
System.out.println("The sum of two Strings is " + two);
You are passing integer(s) ValOne ValTwo to these functions and according to your comments you never planned to use them. These are dummy variables to create overloaded functions. Using String variables would be recommended for that purpose. Since #The Law has already suggested a solution for that with for loops, I will simply add a Java 8 alternative.
public int sumAscii(String s) {
return s.chars().sum();
}
public int sumAscii(String s1, String s2) {
return sumAscii(s1) + sumAscii(s2);
}
You would then call these in your main :
public static void main(String[] args) {
Exam3Question2 c = new Exam3Question2();
Scanner in = new Scanner(System.in);
System.out.println("Enter some text");
String word1 = in.nextLine();
System.out.println("Enter some text");
String word2 = in.nextLine();
int sum1 = c.sumAscii(word1);
System.out.println("The sum of one string is: " + sum1);
int sum2 = c.sumAscii(word1, word2);
System.out.println("The sum of two strings is: " + sum2);
}
Are you having an issue with your code compiling? I think you are because in your main statement you are passing variables that don't exist into functions:
public static void main(String[] args)
{
Exam3Question2 c = new Exam3Question2();
Scanner in = new Scanner(System.in);
String word;
System.out.println("Enter some text");
word = in.nextLine();
sumAscii(word);
int sum1 = c.sumAscii(Input1); //What is Input1
int sum2 = c.sumAscii(Input1, Input2); //What is Input2
int sum3 = sum1 + sum2;
System.out.println("The sum of the two strings is: " + sum3);
}
Another thing, there is no need to create an object of your current class to call the sumAscii() function, because they are a part of the current class:
public static void main(String[] args)
{
//You don't need this line
//Exam3Question2 c = new Exam3Question2();
// Remove the c. from the beginning of the function calls
int sum1 = sumAscii(Input1); //What is Input1
int sum2 = sumAscii(Input1, Input2); //What is Input2
//
}
What you want to be doing in main is calling sumAscii() on your word variable so that you can add the result into sum1:
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Enter some text");
String word = in.nextLine();
int sum1 = sumAscii(word);
System.out.println("The sum of the string " + word + " is: " + sum1);
}
If you want to call your overloaded sumAscii() method with 2 different word, you will need to get another word from the user:
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Enter some text");
String word = in.nextLine();
System.out.println("Enter some more text");
String word2 = in.nextLine();
int sum2 = sumAscii(word, word2);
System.out.println("The sum of the two strings is: " + sum2);
}
Lastly, your overloaded sumAscii() method can be simplified to:
public int sumAscii(String Input1, String Input2)
{
return sumAscii(Input1 + Input2);
}

Categories

Resources