How to change string into integer and add them? - java

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

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.

Parsing a String to an Integer

So my biggest problem is that I cannot seem to remember how to parse a string into an int so that I can idiot proof my code. My goal here is to find out if the user enters in a word instead of an int and then I can explain to them what an integer is. Can someone please help? I just need a simple list of parsing commands so that I can study them for use in the future, once there is a simple list I think I'll be able to figure all the others out from there.
import java.util.Scanner;
import java.util.*;
public class SelfTestNumberNine
{
public static void main(String[] args)
{
boolean test = false;
int num = 0;
int sum = 0;
int count = 0;
int pos = 0;
int neg = 0;
Scanner in = new Scanner(System.in);
while(!test)
{
num = 0;
System.out.print("Enter in an Integer Value: ");
String letta = in.next();
if(??parsing stuff goes here!!)
{
num = in.nextInt();
count++;
if(num > 0)
{
pos++;
sum = sum + num;
}
else if(num < 0)
{
neg++;
sum = num + sum;
}
else
{
test = true;
}
}
else
{
System.out.println("An Integer is a number that is positive or
negative,\nand does not include a decimal point.");
}
}//end while
System.out.println("Total: " + sum);
double avg = sum / count;
System.out.println("Average: " + avg);
}//end main
}//end class
Basically, the program asks the user to input integers, counts the number of positive and negatives, and prints out the total and average (Ignoring 0). The program ends when the user inputs a 0.
P.S. Thanks for your time!! ]:-)
If you want to ensure that the user has entered an int without throwing an exception if they don't you can use the hasNextInt() method:
System.out.println("Enter an int (0) to quit");
//While the user has not entered a valid int
while (!input.hasNextInt()) {
System.out.println("Please enter an integer: ");
//Consume the bad input
input.nextLine();
}
Which will loop until they enter a valid int. A sample run (- denotes user input):
Enter an int (0 to quit)
-No
Please enter an integer:
-Never!!
Please enter an integer:
-Ok ok fine
Please enter an integer:
-3
You can do this in two ways.
- Integer.parseInt()
- Integer.valueOf()
String myStr = "1";
int parsedInt = Integer.parseInt(myStr);
int valueOf = Integer.valueOf(myStr);
System.out.println("Parse Int: " + parsedInt);
System.out.println("Value Of: " + valueOf);
Note: You might get exception if the input is not parseable. NumberFormatException.
You can use a Boolean method and a try-catch to check if you can parse the string to an Integer.
public static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch(NumberFormatException e) {
return false;
} catch(NullPointerException e) {
return false;
}
// only got here if we didn't return false
return true;
}

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)

Scanner String Confusion

The Programm is supposed to let me enter a value a and a string. While it lets me input he integer when it comes to the string, it prints the question but does not let me enter anything.
import java.util.Scanner;
public class PrSumN {
public static void main(String args[]) {
System.out.println("Enter a value");
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int sum = 0;
int pr = 1;
System.out.println("Do you want the sum of the numbers or the products of the numbers?");
String answer = sc.nextLine();
//Itdoesnotletmeinputmystringatthispoint
if (answer == "sum") {
sum(a, sum);
} else {
product(a, pr);
}
}
public static void sum(int a, int sum) {
for (int i = 0; i < a; i++) {
sum = sum + (a - i);
}
System.out.println("The sum of the numbers is " + sum);
}
public static void product(int a, int pr) {
for (int i = 0; i < a; i++) {
pr = pr * (a - i);
}
}
}
After you call int a = sc.nextInt(); you enter an integer in the console and press enter. The integer you entered gets stored in a, whereas the newline character (\n) is read by your String answer = sc.nextLine(); and so it doesn't accept a string from you.
Add this line
sc.nextLine(); // Will read the '\n' character from System.in
after
int a = sc.nextInt();
Another method: You can scan for a string instead of an int and get a by parsing for int:
try {
int a = Integer.parseInt(sc.nextLine());
}
catch (ParseException ex) { // Catch
}
On another (side) note, do not use if (answer=="sum"), instead you would want to use
if (Object.equals (answer, "sum")
Refer to this.
After this line:
int a = sc.nextInt();
Add this:
sc.nextLine();
The reason you need to add sc.nextLine() is because nextInt() does not consume the newline.
Alternatively, you may scan for a String and parse it to the respective type, for example:
int a = Integer.parseInt(sc.nextLine());
Add: And something not related to your primary question, when comparing the value of a String, use .equals and not ==.
We use == to compare identity, so it should be:
if (answer.equals("sum"))

check for positive integers only. no negative integer, no non-numeric strings

I have to write a java program that computes the greatest common divisor of two positive integers. Program has to check for the positive integers only. My problem is that when I enter a negative integer and then a non-numeric string, my program stops running. Bellow is my code:
import java.util.Scanner;
class GCD {
public static void main (String[] args){
Scanner sc = new Scanner(System.in);
int a, b, m, n, remainder;
System.out.print("Enter a positive integer: ");
while (!sc.hasNextInt()){
System.out.print("Please enter a positive integer: ");
sc.next();
}
a = sc.nextInt();
while (a <= 0){
System.out.print("Please enter a positive integer: ");
a = sc.nextInt();
}
System.out.print("Enter another positive integer: ");
while (!sc.hasNextInt()){
System.out.print("Please enter a positive integer: ");
sc.next();
}
b = sc.nextInt();
while (b <=0){
System.out.print("Please enter a positive integer: ");
b = sc.nextInt();
}
m = a;
n = b;
while (n != 0){
remainder = m%n;
m = n;
n = remainder;
}
System.out.println("The GCD of " +a+ " and " +b+ " is " +m);
}
}
Try this:
import java.util.Scanner;
public class A {
public static void main (String[] args){
int a, b, m, n, remainder;
a = validInput();
b = validInput();
m = a;
n = b;
while (n != 0){
remainder = m%n;
m = n;
n = remainder;
}
System.out.println("The GCD of " +a+ " and " +b+ " is " +m);
}
static int validInput() {
Scanner sc = new Scanner(System.in);
while(true){
System.out.print("Please enter a positive integer: ");
String tmp = sc.next();
if (tmp.matches("^\\d+$")) {
return Integer.parseInt(tmp);
}
}
}
}
I suggest you to make your programs more modular, as you can see it's benefits in a simple program like this.
/* prompt a */
String a = sc.next();
/* prompt b */
String b = sc.next();
if (isValid(a) && isValid(b)) {
int ia = Integer.parseInt(a);
int ia = Integer.parseInt(b);
/* calculations and such */
}
boolean isValid(String num) {
try {
int i = Integer.parseInt(num);
if (i < 0) {
return false;
}
} catch (NumberFormatException e) {
return false;
}
return true;
}
It shound work, even if i don't try it. I have just 2 advise as you look new in coding :
-When you make code, try to use function. Normally, you should never copy/paste.
-Try to put full name to your variable, particulary if you share your code on a forum, it would be more simple to people to understand what you did, and help you :)
import java.util.regex.Pattern;
import java.util.Scanner;
class GCD {
public static void main (String[] args){
Scanner sc = new Scanner(System.in);
int a, b, m, n, remainder;
a=askInt();
b=askInt();
m = a;
n = b;
while (n != 0){
remainder = m%n;
m = n;
n = remainder;
}
System.out.println("The GCD of " +a+ " and " +b+ " is " +m);
}
private int askInt(){
System.out.print("Enter a positive integer: ");
String tampon = sc.nextLine();
while(!Pattern.matches("\p{Digit}",tampon)){
System.out.print("Please enter a positive integer: ");
String tampon = sc.nextLine();
}
return Integer.valueOf(tampon);
}
}
In your first while you call next(), but in your second you use nextInt(). If you enter at the first time a negative Integer, you ll step to the next while with the nextInt(). So you ll get an exception if the user is entering a String with something else than numbers, because the scanner cant get the value of keys or something else. A smarter way would be to catch the exception and use it for a endless while like this:
while(true)
System.out.print("Please enter a positive Number: ");
try{
a = sc.nextInt();
if(a>-1){
break;
}
}catch(Exception ignore){
}
}
This code will run until the user enters a positive number. If he enters something else than numbers, the exception will come and will be ignored and the while will go on, if the number was not positive (bigger than -1 in this case) the while will not break.

Categories

Resources