I want to be able to separate a String of two numbers and then add them together, but I keep getting the int value of each character. If I enter "55" as a string I want the answer to be 10. How can I do that?
package org.eclipse.wb.swt;
import java.util.*;
public class ISBN13 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
System.out.println("enter a string");
String numbers = input.nextLine(); //String would be 55
int num1=numbers.charAt(0); //5
int num2=numbers.charAt(1); //5
System.out.println(num1+num2); //the answer should be 10
}
}
You are getting the ascii value of the characters; you can use Character.digit(char, int) to get the numeric value. Something like,
String numbers = "55";
int num1 = Character.digit(numbers.charAt(0), 10);
int num2 = Character.digit(numbers.charAt(1), 10);
System.out.println(num1 + num2);
Output is (as requested)
10
int x = Character.getNumericValue(element.charAt(0));
You can use string.toCharArray() method and then add them in a for loop
import java.util.Scanner;
public class MyClass {
public static void main(String[] args) {
Scanner scan = null;
try {
scan = new Scanner(System.in);
String line = scan.nextLine();
char[] charArray = line.toCharArray();
int sum = 0;
for (char character : charArray) {
sum += Integer.parseInt(String.valueOf(character));
}
System.out.println(sum);
} finally {
scan.close();
}
}
}
Related
In this program I'm trying to create I have a method to take a string to count the amount of uppercase letters. At the end of the program I want to show the smallest amount associated with it's string and the max amount associated with its string which is where I'm having trouble. Is there a way to somehow connect or associate these together? Here is my code so far:
import java.util.Scanner;
import java.util.Arrays;
public class test {
public static void main(String[] args) {
System.out.println("Please input a string:");
Scanner input = new Scanner(System.in);
String s1 = input.nextLine();
String s2 = input.nextLine();
String s3 = input.nextLine();
int i1 = sumLetter(s1);
int i2 = sumLetter(s2);
int i3 = sumLetter(s3);
int[] array = new int[3];
array[0] = i1;
array[1] = i2;
array[2] = i3;
Arrays.sort(array);
System.out.println(s1 + " has a maximum number of uppercase: "+ array[2]);
System.out.println(s3 + " has a maximum number of uppercase: "+ array[0]);
}
public static int sumLetter(String m) {
int count = 0;
for(int i = 0; i < m.length();i++) {
if(Character.isUpperCase(m.charAt(i)))
count++;
}
return count;
}
}
You can use regex to handle this, like so:
public static void main(String[] args) {
String str = "This string has FIVE uppercase characters within itself.";
System.out.println(str.replaceAll("[^\\p{javaUpperCase}]","").length());
}
Output:
5
This is roughly equivalent to the following:
public static void main(String[] args) {
String str = "This string has FIVE uppercase characters within itself.";
int uppercases = 0;
for(char c : str.toCharArray()) {
uppercases += Character.isUpperCase(c) ? 1 : 0;
}
System.out.println(uppercases);
}
Output:
5
Now, assuming that you have this functionality (which you do) within some method:
public static int sumLetter(String m) { ... }
You want to associate the String with the uppercase length. Make a simple data class:
final class StringWithUppercaseSize {
public final String string;
public final int uppercaseLength;
public StringWithUppercaseSize(String string, int uppercaseLength) {
this.string = string;
this.uppercaseLength = uppercaseLength;
}
public int getUppercaseLength() {
return this.uppercaseLength;
}
}
Now, you make an array of these objects:
Scanner input = new Scanner(System.in);
String s1 = input.nextLine();
String s2 = input.nextLine();
String s3 = input.nextLine();
int i1 = sumLetter(s1);
int i2 = sumLetter(s2);
int i3 = sumLetter(s3);
StringWithUppercaseSize[] sizes = { new StringWithUppercaseSize(s1, i1), new StringWithUppercaseSize(s2, i2), new StringWithUppercaseSize(s3, i3) };
Sort the array, by the uppercase size:
Arrays.sort(sizes, Comparator.comparing(StringWithUppercaseSize::getUppercaseLength));
Output the minimum/maximum uppercase string/lengths:
System.out.println(sizes[0].string + " has a minimum number of uppercase: "+ sizes[0].uppercaseLength);
System.out.println(sizes[2].string + " has a maximum number of uppercase: "+ sizes[2].uppercaseLength);
Input:
Abc
abc
aBC
Output:
abc has a minimum number of uppercase: 0
aBC has a maximum number of uppercase: 2
Here's my full test code:
Main.java
class Main {
public static void main(String[] args) {
System.out.println("Please input a string:");
Scanner input = new Scanner(System.in);
String s1 = input.nextLine();
String s2 = input.nextLine();
String s3 = input.nextLine();
int i1 = sumLetter(s1);
int i2 = sumLetter(s2);
int i3 = sumLetter(s3);
StringWithUppercaseSize[] sizes = { new StringWithUppercaseSize(s1, i1), new StringWithUppercaseSize(s2, i2), new StringWithUppercaseSize(s3, i3) };
Arrays.sort(sizes, Comparator.comparing(StringWithUppercaseSize::getUppercaseLength));
System.out.println(sizes[0].string + " has a minimum number of uppercase: "+ sizes[0].uppercaseLength);
System.out.println(sizes[2].string + " has a maximum number of uppercase: "+ sizes[2].uppercaseLength);
}
public static int sumLetter(String m) {
int count = 0;
for(int i = 0; i < m.length();i++) {
if(Character.isUpperCase(m.charAt(i)))
count++;
}
return count;
}
}
StringWithUppercaseSize.java
final class StringWithUppercaseSize {
public final String string;
public final int uppercaseLength;
public StringWithUppercaseSize(String string, int uppercaseLength) {
this.string = string;
this.uppercaseLength = uppercaseLength;
}
public int getUppercaseLength() {
return this.uppercaseLength;
}
}
Finally, as a note, don't do this in code you intend to keep and maintain. There are plenty of ways to make things more readable and maintainable. For example, you can write actual getters/setters for your data class. You can make the public data members private to preserve information hiding. You can append user inputs into a List, and then use things like a for-each loop to create another List of uppercase sizes. You can go over both those lists with a for-each loop to create a List of StringWithUppercaseSizes. You can probably use a Stream with Collectors.maxBy to find the maximum elements instead of sorting, etc.
I am trying to reverse the output of my code and it's working, the problem is when I input 12345678910 the "10" is not displayed.
import java.util.Scanner;
public class Test3{
public static void main(String args[]) {
Scanner in=new Scanner(System.in);
int num=0,rev=0,rev1=0,limit=0,num1=0;
System.out.print("Enter A Number: ");
limit=in.nextInt();
for (int i=0;i<limit;i++){
num=in.nextInt();
while (num >0) {
rev = rev*10 + num % 10;
num /= 10;
}
}
num1=rev;
while(num1>0){
rev1 = rev1 * 10 + num1 %10;
num1 /=10;
}
System.out.println(rev1);
}
}
12345678910 the "10" is not display
because this while loop while (num >0) is running twice for 10, as a result rev is overflowing and holding negative value (-539222978) since int can not hold more than 2^32-1 it wraps around to negative value (-539222978) . what is why you got revl initial value 0 got printed,
So try to use StringBuilder.
import java.util.Scanner;
import java.util.*;
public class Test3{
public static void main(String args[]) {
Scanner in=new Scanner(System.in);
StringBuilder sb = new StringBuilder();
String numStr;
System.out.print("Enter A Number: ");
int limit=in.nextInt();
for (int i=0;i<limit;i++){
numStr=in.next();
sb.append(numStr);
}
System.out.println(sb.reverse().toString());
}
}
Your code is a bit complicated:
public static String ReturnString()
{
long input = 12345678910L;
String inputAsString = Long.toString(input);
String rev = "";
for (int temp = inputAsString.length() - 1; temp > -1; temp--)
{
rev += inputAsString.charAt(temp);
}
return rev;
}
I need to know how to add the input as the number to be reversed. This questions answer should help anyone who has the need to make an input go into a program and come out modified.
import java.util.Scanner;
public class NumberReverse {
public int reverseNumber(int number){
System.out.print("Enter a number: "); <------ input
Scanner keyboard = new Scanner(System.in);
String input = keyboard.nextLine();
int reverse = 0;
while(number !=0){
reverse = (reverse*10)+(number%10);
number = number/10;
}
return reverse;
}
public static void main(String a[]){
NumberReverse nr = new NumberReverse();
System.out.println("Result: " +nr.reverseNumber(Where I want the input to go / or you can put a number here inside of the program, instead of using the interface.));
}
}
I think best way to handle input in the main method and then trigger to reverseNumber with input value;
public class NumberReverse {
public int reverseNumber(int number){
int reverse = 0;
while(number !=0){
reverse = (reverse*10)+(number%10);
number = number/10;
}
return reverse;
}
public static void main(String a[]){
System.out.print("Enter a number: ");
Scanner keyboard = new Scanner(System.in);
String input = keyboard.nextLine();
try {
NumberReverse nr = new NumberReverse();
System.out.println("Result: " +nr.reverseNumber(Integer.valueOf(input)));
} catch (NumberFormatException nme) {
System.err.println("You entered not numeric value...!");
}
}
}
You can pass the number as the argument of the main:
public static void main(String a[]) {
NumberReverse nr = new NumberReverse();
System.out.println("Result: "+ nr.reverseNumber(Integer.parseInt(a[0])));
}
If you don't want interface, then remove Scanner statements and pass number as argument like below
public int reverseNumber(int number){
int reverse = 0;
while(number !=0){
reverse = (reverse*10)+(number%10);
number = number/10;
}
return reverse;
}
public static void main(String a[]){
reverseNumber nr = new reverseNumber();
System.out.println("Result: " +nr.reverseNumber(52)); //pass the number you wish to reverse
}
I've been working on this program and am currently stuck. The HW prompt is to prompt a user to input numbers, save it as an array, find the number of odd numbers & the percentages then display those values back to the user.
Currently I am trying to write to part of the code that finds the percentage of the odd numbers in the array but the return isn't displaying and i just cant figure it out. Any ideas? Thank you!
import java.util.*; // import java course for Scanner class
public class Integers {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Please input a series of numbers");
int inputs = Integer.parseInt(console.next());
int[] arraysize = new int[inputs];
Oddvalues(arraysize);
}
public static int Oddvalues (int[] size) {
int countOdd = 0;
for (int i = 1; i < size.length; i++) {
if(size[i] % 2 != 0) {
i++;
}
}
return countOdd;
}
}
Consider the following code, which appears to be working in IntelliJ locally. My approach is to read in a single line from the scanner as a string, and then to split that input by whitespace into component numbers. This avoids the issue you were facing of trying to directly create an array of integers from the console.
Then, just iterate over each numerical string, using Integer.parseInt(), checking to see if it be odd.
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Please input a series of numbers");
String nextLine = console.nextLine();
String[] nums = nextLine.split(" ");
int oddCount = 0;
for (String num : nums) {
if (Integer.parseInt(num) % 2 == 1) {
++oddCount;
}
}
double oddPercent = 100.0*oddCount / nums.length;
System.out.println("Total count of numbers: " + nums.length + ", percentage odd: " + oddPercent);
}
In the function Oddvalues you promote i instead of promoting countOdd. And the loop should start from 0 not 1.
Try this
import java.util.*;
import java.lang.*;
import java.io.*;
public class OddVals{
public static void main(String[] args) throws java.lang.Exception {
Scanner sc = new Scanner(System.in);
int[] array = new int[sc.nextInt()]; // Get the value of each element in the array
System.out.println("Please input a series of numbers");
for(int i = 0; i < array.length; i++)
array[i] = sc.nextInt();
System.out.println("Number of Odds:" +Oddvalues(array));
printOdd(array);
}
public static int Oddvalues (int[] size) {
int countOdd = 0;
for (int i=0; i < size.length; i++){
if(size[i]%2 != 0)
++countOdd;
}
return countOdd;
}
public static void printOdd(int[] arr)
{
for(int i=0;i<arr.length;++i)
{
if(arr[i]%2==1)
System.out.print(arr[i]+" ");
}
}
import java.util.*; // import java course for Scanner class
public class Integers {
public static void main(String[] args) {
List<Integer> intList = new ArrayList<Integer>();
Scanner console = new Scanner(System.in);
System.out.println("Please input a series of numbers");
while (console.hasNext())
{
String str = console.next();
try
{
if(str.equals("quit")){
break;
}
int inputs = Integer.parseInt(str);
System.out.println("the integer values are" +inputs);
intList.add(inputs);
}
catch (java.util.InputMismatchException|NumberFormatException e)
{
console.nextLine();
}
}
console.close();
double d = Oddvalues(intList);
System.out.println("the percent is" +d);
}
public static double Oddvalues (List<Integer> list) {
int count = 0;
for( Integer i : list)
{
if(!(i%2==0))
{
count++;
}
}
double percentage = (Double.valueOf(String.valueOf(count))/ Double.valueOf(String.valueOf(list.size())))*100;
return percentage;
}
}
If this helps
Im trying to make a binary string into a decimal. It will terminate if -1 is entered. I am stuck with using an array. It was suggested to use: public static int binaryToDecimal (String binaryString) . But Im not sure how to do that. This is what I have:
import java.util.Scanner;
public class BinaryConversion {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String inString;
int decimal;
System.out.println("Enter a binary number: ");
inString = input.nextLine();
while (inString != "-1") {
int i;
int binaryLength;
binaryLength = inString.length();
for (i = 0, decimal = 0; i < binaryLength; i++) {
decimal = decimal * 2 + (inString[i] - 0);
System.out.print(decimal);
}
System.out.println("Enter a binary number: ");
inString = input.nextLine();
}
System.out.println("All set !");
}
}
It says there is a compilation problem with the array. Thank you!
inString is a String, not an array. So, you can't use inString[i]. To get the character at a given position in the string, use inString.charAt(i), which returns a char.
Then, you'll also have to convert that char into an int.
You can do this with Character.getNumericValue(char).
So in summary, instead of
inString[i]
you need to use
Character.getNumericValue(inString.charAt(i))
Try this one:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String inString;
int decimal;
System.out.println("Enter a binary number: ");
inString = input.nextLine();
//Character.getNumericValue(inString.charAt(i))
while (inString != "-1") {
int i;
int binaryLength;
binaryLength = inString.length();
for (i = 0, decimal = 0; i < binaryLength; i++)
{
decimal = decimal * 2 + (Character.getNumericValue(inString.charAt(i)) - 0);
System.out.print(decimal);
}
System.out.println("Enter a binary number: ");
inString = input.nextLine();
}
System.out.println("All set !");
}
}
As suggested, you have to use Character.getNumericValue
You can simplify the code by using Integer.parseInt():
public static void main(String[] args) {
final Scanner input = new Scanner(System.in);
String inString;
while (true) {
System.out.println("Enter a binary number: ");
inString = input.nextLine();
if (inString.equals("-1"))
break;
System.out.println(Integer.parseInt(inString, 2));
}
System.out.println("All set !");
}
You had few logical and few syntax errors.
This is working code :
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String inString;
int decimal;
System.out.println("Enter a binary number: ");
inString = input.nextLine();
while (!"-1".equals(inString)) {
int i;
int binaryLength;
binaryLength = inString.length();
for (i = binaryLength-1, decimal = 0; i >= 0; i--) {
if (inString.charAt(i) == '1') {
decimal += Math.pow(2, binaryLength-i-1);
}
}
System.out.println(decimal);
System.out.println("Enter a binary number: ");
inString = input.nextLine();
}
System.out.println("All set !");
}
Note that comparing String cannot be done with ==, you have to use equals or compareTo methods.
byte[] binary = {1,1,0,1};
int decimal = 0;
for(int i=binary.length-1, j=0; i>=0; i--, j++){
decimal += binary[i]*Math.pow(2, j);
}