What is wrong with this code? It says cannot convert from String to int, but I have already converted it.
public static void main(String[] args) {
String x = JOptionPane.showInputDialog(null, "Hur många värden haver du?");
int i = Integer.parseInt(x);
for (int y = 0; i >= y; y++) {
String z = JOptionPane.showInputDialog(null, "Skriv in värdet");
int sum = Integer.parseInt(z);
sum = (sum + z);
}
}
No you have converted z to int and store the result in sum so sum is the int value of z but z is still a variable of type String. What you are trying to do here is the same as multiplying sum by two.
But i assum you want to sum all input values, so you can do sum = (sum + Integer.parseInt(z)); and put the declaration of sum outside the loop, otherwise you initialize it on every iteration. Another bug is that if you input x it will iterate x + 1 times because of i >= y. Fixed version below.
String x = JOptionPane.showInputDialog(null, "Hur många värden haver du?");
int i = Integer.parseInt(x);
int sum = 0;
for (int y = 0; i > y; y++)
{
String z = JOptionPane.showInputDialog(null, "Skriv in värdet");
sum = (sum + Integer.parseInt(z));
}
System.out.println(sum);
Input: 3 (number of iterations)
Input: 7
Input: 5
Input: 6
Output: 18
Java don't do automatic conversion between types. So you can't add Strings with numbers and expect it to do math.
What Java does do it auto boxing of primitive types to objects. And it will automatically attempt to call toString() on objects if you use it in a String concatenation.
So as Reimeus wrote. You need to convert the String to a number before you start using it in math
Cannot convert from String to int
sum=(sum+z) // int+string // this was the problem
change your z to int as:
int iz= Integer.parseInt(z);
sum = (sum + iz);
int sum = 0;
for (int y = 0; i >= y; y++) {
try{
String z = JOptionPane.showInputDialog(null, "Skriv in värdet");
sum = (sum + Integer.parseInt(z));
} catch (Exception e){
System.out.println("This was not an Integer: " + z);
}
}
The exception will prevent your program from crashing, but it will not screw up your 'sum'. So you can put an other value again, and go on...
Related
I need to get from the user the length and the value of the array and return the digit that shows the most times. for example: the user gave me the length "4" and the numbers {83,238,8,54} the function will return " the numbers that shows the most times is 8";
but it send an error massage if the user enter more than 10 digits in general.
String sum = "";
// get the length
System.out.println("Enter the size of the array :");
int size = in.nextInt();
// create the array
String[] arr = new String[size+1];
// get value
System.out.println("Enter the elements of the array:(max capity 10 digits) ");
for(int i=0; i<arr.length; i++) {
arr[i] = in.nextLine();
sum+=arr[i];
}
System.out.println("the numbers that you gave me are: "+sum);
int all = Integer.parseInt(sum);
System.out.println("the digit that shows the most time is: "+maxOccurring(all));
}
static int countOccurrences(int x,int d) {
int count = 0;
while (x > 0)
{
if (x % 10 == d)
count++;
x = x / 10;
}
return count;
}
static int maxOccurring( int x)
{
if (x < 0)
x = -x;
int result = 0;
int max_count = 1;
for (int d = 0; d <= 10; d++)
{
int count = countOccurrences(x, d);
if (count >= max_count)
{
max_count = count;
result = d;
}
}
return result;
}
}
```
You get an NumberFormatException at the following line:
int all = Integer.parseInt(sum);
Exception trace is:
Exception in thread "main" java.lang.NumberFormatException: For input string: "25445648942"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
at java.base/java.lang.Integer.parseInt(Integer.java:652)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at scan.ScannerTest.main(ScannerTest.java:27)
This exception is telling you that Integer.parseInt can't interpret the number you're passing through it (obtained by concatenating all the entered digits), in this precise example: "25445648942"
That's because this function is trying to yield an Integer from all those digits, which has a maximum capacity of 2^31 - 1 = 2,147,483,647. The entered number is higher that this, so it logically fails.
You should treat each entered number separately and count the digits in each, then do a sum of all to get your answer.
BTW, you don't ever need to convert to a number type to count the digits. It's simple string processing
The following code is designed to factorize a number typed into the variable x.
public class testMod{
public static void main(String[]args){
double x = 11868681080091051216000;
StringBuilder output = new StringBuilder("1 * ");
for(double y = 2; y <= x; y++){
while (x % y == 0) {
System.out.print("Calculating... \n");
String printNumber = y + " * ";
x = x / y;
output.append(printNumber);
System.out.print(output.substring(0, output.length() - 2) + "\n");
}
}
}
}
The problem is that the compiler treats 11868681080091051216000 as an int, regardless of the attempt to assign it to a double. As such, it's out of range.
To specify a double literal, you can simply append D to the end – but do note that you'll lose precision this way:
double x = 11868681080091051216000D;
System.out.println(x); // prints 186868108009105E22
If you need the full precision, you can use a BigInteger instead, but you'll still need to specify that number in expressions that Java can handle, such as a product of its factors.
I am trying to write a program that receives from the user two numbers. one (x) is a number between 0 - 9 and the second (y) is any natural number. the problem is that I want to check how many times x is in y for example: if x = 2 and y = 2245 then the output would be 2
int x = 3;
int y = 233457693;
int total = 0;
String[] ys = String.valueOf(y).split("");
for (String s : ys) {
if (s.equals(String.valueOf(x))) total++;
}
System.out.println(total);
prints 3
My trick is to transform int in String, after find with Matcher class and count how many String x are in the String y.
So, I try something like that and it's worked:
int x = 2;
int y = 2245;
Pattern pattern = Pattern.compile(x + ""); //Create the pattern with the x number
Matcher matcher = pattern.matcher(y + ""); //Create the matcher wtih de pattern and insert y in string
int c = 0;
while (matcher.find()) c++; //Count the matches
System.out.println(c); //Print
Ouput:
2
Here is solution for Java 8 and higher using Stream:
int x = 2;
int y = 2245;
long count = String.valueOf(y).chars().filter(ch -> ch == Character.forDigit(x,10)).count();
You can convert x and y to String and use charAt() method.
int x = 2;
int y = 2245;
int counter = 0;
String xString = String.valueOf(x);
String yString = String.valueOf(y);
for(int i=0; i<yString.length(); i++)
{
if(yString.charAt(i)==xString.charAt(0))
counter++;
}
System.out.println(counter);
If a user enters a value for
x y and z coordinates, what steps would need to take in order to create a range from -x/y/z to +x/y/z? Is there a function that will give the numbers in that range even though a double is entered?
This is my code so far im not finished yet, I'm not sure if its right. After it gets the x,y,z points and the number of data points the user wants, it will then print the n number of points with random points (x , y, z) x, y, z being anywhere from -x to x etc.
import java.io.*;
public class MultiDimArray
{
public static void main (String [] args) throws IOException
{
BufferedReader myInput = new BufferedReader (new InputStreamReader (System.in));// Buffered Reader reads the number inputed
double range;
System.out.println("How many points do you want returned? ");
String numPointsA = myInput.readLine();
int numPoints = Integer.parseInt(numPointsA);
System.out.println("Enter X length: ");
String xlengthA = myInput.readLine();
double xlength = Double.parseDouble(xlengthA);
System.out.println("Enter Y length: ");
String ylengthA = myInput.readLine();
double ylength = Double.parseDouble(ylengthA);
System.out.println("Enter Z length: ");
String zlengthA = myInput.readLine();
double zlength = Double.parseDouble(zlengthA);
int[][][][] dataPoint = new int[3][xlength][ylength][zlength];
for (int i = 0; i < (xlength * 2); i++){
range = (0 -( xlength - i) + 1);
System.out.println(range);
}
for (int i = 0; i < (ylength * 2); i++){
range = (0 -( ylength - i) + 1);
}
for (int i = 0; i < (zlength * 2); i++){
range = (0 -( zlength - i) + 1);
}
}
}
range is infinite if you want to include all fractional numbers otherwise you can do that manually.
for (int i=-x; i<=x; i++)
operate(i, y, z);
another solution for your problem is that you don't generate range.
you just store those values x y and z.
then, when you need to test if a number is in range you can do it easily with if statement.
what I mean that this a wrong way to design your solution. try to get values you want in another way. something like reverse engineering. then you test if those values are in range.
post your problem. then we can help you.
Code that generates numPointsA random numbers between -x and x:
Random random = new Random();
double start = -x;
double end = x;
for (int i=0;i<numPointsA;i++)
{
double ran = random.nextDouble();
double result = start + (ran * (end - start));
System.out.println(result);
}
To get a random number between 0 and n-1, use
Random rand = new Random();
int r = rand.nextInt(n);
This is a homework problem
How would I reverse an integer in Java with a for loop? The user will input the integer (I don't know how long it will be) and I need to reverse it. ie: If they enter 12345, my program returns 54321.
Here's the catch, you can't use String, StringBuffer, arrays, or other advanced structures in this problem.
I have a basic idea of what I need to do. My problem is...in the for loop, wouldn't the condition need to be x < the length of the integer (number of digits)? How would I do that without String?
Thanks for any input, and I'll add more information if requested.
EDIT:
Of course, after introspection, I realized I should use another for loop to do this. What I did was create a for loop that will count the digits by dividing by 10:
int input = scan.nextInt();
int n = input;
int a = 0;
for (int x = 0; n > 0; x++){
n = n/10;
a = a + 1;
}
EDIT 2:
This is what I have
int input = scan.nextInt();
int n = input;
int a = 0;
int r = 0;
for (int x = 0; n > 0; x++){
n = n/10;
a = a + 1;
}
for (int y = 0; y < n; y++) {
r = r + input%10;
input = input/10;
}
System.out.println(input);
When I run it, it isn't reversing it, it's only giving me back the numbers. ie: if I put in 1234, it returns 1234. This doesn't make any sense to me, because I'm adding the last digit to of the input to r, so why wouldn't it be 4321?
While your original number is nonzero, take your result, multiply it by 10, and add the remainder from dividing the original by 10.
For example, say your original number is 12345. Start with a result of 0.
Multiply result by 10 and add 5, giving you 5. (original is now 1234.)
Multiply result by 10 and add 4, giving you 54. (original is now 123.)
Multiply result by 10 and add 3, giving you 543. (original = 12.)
Multiply result blah blah 5432. (original = 1.)
Multiply, add, bam. 54321. And 1 / 10, in int math, is zero. We're done.
Your mission, should you choose to accept it, is to implement this in Java. :) (Hint: division and remainder are separate operations in Java. % is the remainder operator, and / is the division operator. Take the remainder separately, then divide the original by 10.)
You will need to use math to access each of the digits. Here's a few hints to get your started:
Use the % mod operator to extract the last digit of the number.
Use the / division operator to remove the last digit of the number.
Stop your loop when you have no more digits in the number.
This might not be the proper way but
public static int reverseMe(int i){
int output;
String ri = i + "";
char[] inputArray = ri.toCharArray();
char[] outputArray = new char[inputArray.length];
for(int m=0;m<inputArray.length;m++){
outputArray[inputArray.length-m-1]=inputArray[m];
}
String result = new String(outputArray);
output = Integer.parseInt(result);
return output;
}
public static void reverse2(int n){
int a;
for(int i = 0; i < n ; i ++){
a = n % 10;
System.out.print(a);
n = n / 10;
if( n < 10){
System.out.print(n);
n = 0;
}
}
}
here is the Answer With Correction of Your Code.
import static java.lang.Math.pow;
import java.util.*;
public class MyClass {
public static void main(String args[]) {
Scanner scan=new Scanner(System.in);
int input = scan.nextInt();
int n = input;
int a = 0;
int r = 0;
for (; n > 0;){
n = n/10;
a = a + 1;
}
for (int y = 0; y < input;a--) {
r =(int)( r + input%10*pow(10,a-1));
input = input/10;
}
System.out.println(r);
}
}