How to work with the StringTokenizer class - java

I am supposed to evaluate a string by splitting the string in tokens using the StringTokenizer class. After that I am supposed to convert these tokens to int values, using "Integer.parseInt".
What I don't get is how I am supposed to work with the tokens after splitting them.
public class Tester {
public static void main(String[] args) {
String i = ("2+5");
StringTokenizer st = new StringTokenizer(i, "+-", true);
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
int x = Integer.parseInt();
//what exactly do I have to type in here, do convert the token(s) to an int value?
}
}
So if I understand this right I now have three tokens. That would be: "2", "+" and "5".
How exactly do I convert these tokens to int values?
Do I have to convert each of them seperatly?
Any help is appreciated.

Maybe you can use this:
String i = ("2+5");
StringTokenizer st = new StringTokenizer(i, "+-", true);
while (st.hasMoreTokens()) {
String tok=st.nextToken();
System.out.println(tok);
//what exactly do I have to type in here, do convert the token(s) to an int value?
if ("+-".contains(tok)) {
//tok is an operand
}
else {
int x = Integer.parseInt(tok);
}
}

To have a possibility to make some calculations with the Integers extracted from the String, you have to put them into an ArrayList. And you have to use try/catch operation to avoid a NumberFormatException. Further you can take the values directly from the ArrayList and do with them what you'd like. For example:
public static void main(String[] args) {
ArrayList <Integer> myArray = new ArrayList <>();
String i = ("2+5");
StringTokenizer st = new StringTokenizer(i, "+-/*=", true);
while (st.hasMoreTokens()) {
try {
Integer stg = Integer.parseInt(st.nextToken(i));
myArray.add(stg);
}
catch (NumberFormatException nfe) {};
}
System.out.println("This is an array of Integers: " + myArray);
for (int a : myArray) {
int x = a;
System.out.println("This is an Integer: " + x);
}
int b = myArray.get(0);
int c = myArray.get(1);
System.out.println("This is b: " + b);
System.out.println("This is c: " + c);
System.out.println("This is a sum of b + c: " + (b + c));
}
As a result you'll get:
This is an array of Integers: [2, 5]
This is an Integer: 2
This is an Integer: 5
This is b: 2
This is c: 5
This is a sum of b + c: 7

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.

Line by line input evaluation with operators and how to store the changing value until user types "."

I'm trying to make a program that evaluates a mathematic equation that's written one character or value per line at a time. The user will enter alternating numbers and operators, line by line, terminating with a ‘.’. That means I'm not trying to evaluate from a single string (and assume input will always alternate between number and operator).
I don't know how to make it so that it keeps taking input until the user types ".'
I also am not sure how to keep the value continuously changing as the user types the formula and how to store that.
Sample input:
1
+
6
-
3
.
The solution to your equation is: 4
import java.util.Scanner;
class Evaluator {
static int add (int a, int b)
{
return a + b;
}
static int multiply (int a, int b)
{
return a * b;
}
static int divide (int a, int b)
{
return a / b;
}
static int subtract (int a, int b)
{
return a - b;
}
static int modulus (int a, int b)
{
return a % b;
}
public static void main(String [] args)
{
Scanner input = new Scanner (System.in);
int a,b,c;
System.out.println("Enter the equation:");
a = input.nextInt();
String c = input.next();
b = input.nextInt();
if (c.contains("+")) {
int result = add (a,b);
}
else if (c.contains("*")) {
int result = multiply (a,b);
}
else if (c.contains("/")) {
int result = divide (a,b);
}
else if (c.contains("-")) {
int result = subtract (a,b);
}
else if (c.contains("%")) {
int result = modulus (a,b);
}
else if (c.contains(".")) {
break;
}
System.out.print("The solution to your equation is: " + result);
}
}
Your code is very close, in that you use Scanner next() and nextInt() in the correct order (to match the input rules). Here a while(true) loop is added around the pair of inputs; either a user enter a '.' and the loop breaks, or the user enters an operator followed by the next number. The result is kept up to date by using it repeatedly in the various math operators.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int b, result;
System.out.println("Enter the equation:");
result = input.nextInt();
while (true) {
String c = input.next();
if (c.contains(".")) {
break;
}
b = input.nextInt();
if (c.contains("+")) {
result = add(result, b);
} else if (c.contains("*")) {
result = multiply(result, b);
} else if (c.contains("/")) {
result = divide(result, b);
} else if (c.contains("-")) {
result = subtract(result, b);
} else if (c.contains("%")) {
result = modulus(result, b);
}
}
input.close();
System.out.print("The solution to your equation is: " + result);
}
Here is a simple while loop you can use to get input from the user. I have a check if it's a digit or something else. You can use this skeleton to grab input from the user and exit when someone presses "."
Scanner input = new Scanner (System.in);
int a,b,currentTotal = 0;
String inputFromUser = "nothing";
while(!inputFromUser.equals("."))
{
inputFromUser = input.nextLine(); //grab line by line
if(inputFromUser.matches("\\d+")){
//parse the number and set it to a value like a...
System.out.println("You entered a number: " + inputFromUser);
}
else if(!inputFromUser.equals(".")){
//check if you have value and try to apply your number to your current total
System.out.println("You entered something other than a number: " + inputFromUser);
}
}
If the user enters a number, set a variable to that number, perhaps a
If the user enters something other than a number and not a period then check if the input is a valid operation with your provided logic and apply it like operatorMethod(a, currentTotal)

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);
}

moving the characters in a text string a specified number of positions

I am new in programming and I am trying to write a program that moves the characters in a text string a specified number of positions.
The program must include a method whose inputs will be a text string (type String) and the number of positions (type int). The output will be a string with characters shifted.
For example, moving 4 positions:
rabbit eats a carrot
it eats a carrotrabb
Now I have this partial code. I can erase first characters but I don't know how to put them to the end of this text. How can i make it?
public static void main(String[] args) {
System.out.println("enter the text: ");
Scanner cti = new Scanner(System.in);
String a = cti.nextLine();
System.out.println("enter number of positions= ");
int b = cti.nextInt();
char firstLetter = a.charAt(0);
b--;
a = a.substring(b);
String m = a + firstLetter ;
System.out.println("now it is "+ m);
}
If you use regex, it's just one line:
return str.replaceAll("^(.{" + n + "})(.*)", "$2$1");
import java.util.*;
public class JavaApplication5 {
public static void main(String[] args) {
System.out.println("enter the text: ");
Scanner cti = new Scanner(System.in);
String a = cti.nextLine();
System.out.println("enter number of positions= ");
int b = cti.nextInt();
String firstPart = a.substring(0,b); // line 1
b--;
a = a.substring(b);
String m = a + firstPart ; // line 2
System.out.println("now it is "+ m);
}
}
See the changes above in statement marked with comment line 1 and line 2.
In line 1, we are getting the first part of string and in line 2, adding at the end of second string part.
public String foo(String s, int n) {
String s2 = s.substring(0, n);
s = s.substring(n) + s2;
return s;
}
you can put a few validations on this, like null string or n is less than s.length() etc.
It is better to use modulus operator to calculate number of shifts. When initial number of shift is more than string length. Check this :
public String shift(String string,int n){
int nshift = string.length() < n ? n%string.length() : n ;
String a = string.substring(0,nshift);
return string.substring(nshift) + a ;
}
One more version. All the work is essentially done in 1 line here:
String result = new StringBuilder(a).delete(0, b).append(a.substring(0,b)).toString();
Anyway, the full code is:
import java.util.*;
public class ShiftLetters {
public static void main(String[] args) {
System.out.print("enter the text: ");
Scanner cti = new Scanner(System.in);
String a = cti.nextLine();
System.out.print("Enter number of positions: ");
int b = cti.nextInt();
String result = new StringBuilder(a).delete(0, b).append(a.substring(0,b)).toString();
System.out.println(result);
}
}
Also, you might want to be more accurate with your indentation style to improve readability.

How to change string into integer and add them?

Im writing a code that will will take the entered number and only add the values that are in the even positions.
For example:
If user enters 53429
The sum of of the even positions is 5.
My issue is I'm trying to convert the strings of the even positions back into integers and add them together. This is what I have
I keep receiving an error when I try to parse the string to an integer.
Cannot find symbol
symbol : method parseInt(java.lang.String)
location: class Integer
Code:
import java.util.Scanner;
public class NumberSums {
public static void main(String [] args) {
Scanner keyboard=new Scanner(System.in);
System.out.print("Enter a number: ");
String x=keyboard.next();
String s1 = x;
int length = s1.length();
if (length<5) {
System.out.println("Invalid value");
System.exit(0);
}
if (length>5) {
System.out.println("Invalid value");
System.exit(0);
}
String s2 = s1.substring(0,1);
String s3 = s1.substring(1,2);
String s4 = s1.substring(2,3);
String s5 = s1.substring(3,4);
String s6 = s1.substring(4,5);
int a = Integer.parseInt(s3);
//int b = Integer.parseInt(s5);
//sum = (a + b);
System.out.println("The sum of all even positions is " + sum);
}
}
I'm willing to bet that you have a class named Integer, and Java is trying to use that rather than java.lang.Integer.
Rename your class, or use java.lang.Integer.parseInt(s3) instead.
code to add even placed chars in the string.
String str="1234567";
int sum=0;
for(int i=1;i<str.length();i=i+2){
sum+=(str.charAt(i)-'0');
}
System.out.println(sum);
And we can also take from keyboard and start the calculation:
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Please enter number : ");
String number=null;
try{
number = reader.readLine();
}
catch (IOException e) {
e.printStackTrace();
throw e;
}
int sum=0;
for(int i=1;i<number.length();i=i+2){
sum+=(number.charAt(i)-'0');
}
System.out.println(sum);
I ran the program and it works fine... if you uncomment the lines int b and sum = (a + b);. However, you have to declare the sum variable, i.e. int sum = (a + b);
What JDK are you running? The error you describe would only occur if Integer.parseInt(String foo); didn't exist, except it's been around since at least Java 1.4, so I'm not sure why you wouldn't find it; unless you have another Integer class defined in the same package, which could confuse the compiler.
Here is the complete program, including imports (which may be the problem, if you're importing a different Integer than java.lang.Integer), fixing the variable declaration and removing unnecessary code, fixing indentation, and adding a Scanner.close() statement:
import java.util.Scanner;
public class Test {
public static void main(String [] args)
{
Scanner keyboard=new Scanner(System.in);
System.out.print("Enter a number: ");
String x=keyboard.next();
String s1 = x;
int length = s1.length();
if(length != 5)
{
System.out.println("Invalid value");
System.exit(0);
}
String s3 = s1.substring(1,2);
String s5 = s1.substring(3,4);
int a = Integer.parseInt(s3);
int b = Integer.parseInt(s5);
int sum = (a + b);
System.out.println("The sum of all even positions is " + sum);
keyboard.close();
}
}
The Modified code. Try understanding it.
import java.util.Scanner;
public class EvenPos {
public static void main(String [] args)
{
Scanner keyboard=new Scanner(System.in);
System.out.print("Enter a number: ");
String x=keyboard.next();
String s1 = x;
int length = s1.length();
if(length<5) {
System.out.println("Invalid value");
System.exit(0);
}
if(length>5) {
System.out.println("Invalid value");
System.exit(0);
}
else{
char a = s1.charAt(1);
char b = s1.charAt(3);
int q = Character.getNumericValue(a); //Convert Char to Integer
int z = Character.getNumericValue(b); // //Convert Char to Integer
int sum = 0;
if (q % 2 == 0 && z % 2 == 0){ //If both even, then.....
sum = q+z;
System.out.println("Your sum: " + sum);
}
else{
System.out.println("No even Number found at even POS");
}
}
}
}

Categories

Resources