How do i overgo a misMatchExeption in an armstrongnumber calculation in Scanner? - java

I have written the following code, with following conditions. I was not allowed to use any String or Math class, so I used for loops, to break the number down.
It works for e.g 153 and 54883 but for numbers like 4679307774 the Scanner Type gives me back a misMatchExeption. I do understand why, I tried using long type, the program works then, but does not (due to Two`s) give back a correct answer.
I want to know, how to solve that problem, or better said what other things I could try here.
Scanner sc = new Scanner(System.in);
System.out.println("Please enter any Integer above zero here : ");
System.out.println("Enter length of number, from 1 onwards: ");
int num = sc.nextInt();
int pow = sc.nextInt();
int narziss = 0; // TODO mismatchexeption
int single;
int a;
do {
a = 1;
single = num % 10; // takes each chiffre from behind, for as long as for runs.
System.out.println("single modulo : " + single);
num = num / 10;
for (int i = 0; i < pow; i++) {
a *= single;
System.out.println(a);
}
narziss += a;
System.out.println("narziss: " + narziss);
} while (num != 0);
System.out.println(" if the last shown number, " +
"is the same as you have typed in, " +
"you found an so-called armstrong number! ");
}
}

The problem i was asking, can be solved with a type other than Integer.
With long for example... or floating point types.
Be sure to change or cast all involved parts, like scanner, loops and so on.

Related

While loop works with the interaction pane, but not exactly

This is supposed to take the length of the input number and tell it. I have the print statements for this specific case in the main method, which are at the top of the code, and the actual method code below it.
case '1':
System.out.printf("Enter an int number: %d\n",num);
num = in.nextInt();
setLength(num);
System.out.printf("The length of %d is: %d\n",num, Program8.length);
break;
...
public static void setLength (int num) {
int count = 0;
while (num!=0) {
num = num % 10;
++count;
}
Program8.length = count;
}
When I type one of the test cases, i.e. Program8.setLength(0123400); Program8.length, I get the right number, but not written the right way. I should get:
The length of 0123400 is: 6
Instead, I get
The length of 0is: 66, with the last 6 lit in light blue as if I was initializing a variable. I'm not sure how to get it in the right format.
If this is not a homework and we do not need to prove our own implementation, then we may solve this with what java has already given us;
Program8.length=Integer.toString(num).length();
But, if we have to show our own implementation to someone, then this can show what you miss in your implementation, which has already pointed out in the comments above by #DevilsHnd;
/*
reportDigits(192837465);
reportDigits(19287465);
reportDigits(1927465);
reportDigits(193765);
reportDigits(37465);
*/
void reportDigits(int number) {
System.out.print(number + " has ");
int len = 0;
while (number > 0) {
len++;
number /= 10;
//number = ((number - number %10) / 10);
}
System.out.println(len + " digit(s)");
}

Arithmetic mean in java

Problem statement
Need to find the Arithmetic mean of numbers entered by user.
Constraints
We cannot ask user to define/share the number of "NUMBERS" user has planned to enter i.e. we cannot ask user to tell how many numbers he is going to enter.
If -1 is entered by user, the input should stop and Arithmetic mean should be displayed.
We are supposed to ask user only to enter the numbers for which Arithmetic mean is to be calculated. Like : User enters
2
4
7
10
-1
so we need to calculate arithmetic mean for 2,4,7,10 and display the result.
Code
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int sum = 0;
do {
System.out.println("Value is :" + n);
count++;
sum = sum + n;
}while ( n != -1);
}
It goes to infinite loop and I've also tried using if/else but i didn't work. Please assist.
For the input of :
3
9
4
-7
0
2
-1
The arithmetic mean should be calculated for 3,9,4,7,0,2,29 i.e. 1.8
Try this:
Scanner sc = new Scanner(System.in);
int sum = 0;
int count = 0;
int n = 0;
do {
System.out.println("Enter next number(-1 to exit): ");
n = sc.nextInt();
System.out.println("Value is :" + n);
if(n != -1)
{
count++;
sum = sum + n;
}
}while ( n != -1);
sc.close();
System.out.println("Mean is: " + (double) sum/count);
}
You needed to move your sc.nextInt(); into the loop so that you can keep entering in values. I also added an if statement so the -1 does not get used in the mean value.
You're reading "n" as input out of the while, then n has always the first value and the loop is infinite.
You just need to keep passing ints, otherwise n is forever the first value entered.
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int sum = 0;
do {
System.out.println("Value is :" + n);
count++;
sum = sum + n;
n = sc.nextInt();
}while ( n != -1);

Sorting evens and odds between the range of two integers using while loops?

NOTE: (I do not need anyone to write the whole program for me, I only need the algorithm!)
I need to create a program that prompts the user to enter two integers. The program then needs to list all the even numbers in between the two inputed integers and output the sum. And then the same for the odd numbers. (using While loops)
I will then need to rewrite the code to use a do-while loop, and then rewrite it AGAIN using a for loop.
Here is an example of what the result should look like:
Enter an integer: 3
Enter another integer larger than the first: 10
Even Numbers: 4, 6, 8, 10
Sum of even numbers = 28
Odd Numbers: 3, 5, 7, 9
Sum of odd numbers = 24}
I tried starting off with the even numbers with something like this, but it just gets stuck at the first number, even if the first number is even.
import java.util.Scanner;
public class EvenOddSum_While {
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter a number: ");
int num1 = keyboard.nextInt();
System.out.println("And another: ");
int num2 = keyboard.nextInt();
while (num1 < num2){
while (num1 %2 == 0){
System.out.print(num1 + ", ");
num1++;
}
}
}
}
The inner while has no end criteria, you need if there instead. Also, your num1++ Statement must be in the outer while loop, not the inner one.
Also, there is no real algorithm here, you're struggling with the language itself ;)
General advice: either run through your code with a step-by-step debugger, virtually every IDE has one OR place excessive log /System.out.println statements in your code to understand what it's doing
When you said 'in between' did you mean including the two integers? Because you did include them. Okay. So do this.
int x = 0;
int y = 0;
int even = 0;
int odd = 0;
int evenx = 0;
int oddx = 0;
int evena = 0;
int odda = 0;
Scanner scan = new Scanner(System.in);
//Prompts the user to input the first number
x = scan.nextInt();
//Prompts the user to input the second number
y = scan.nextInt();
for(int i = x;i<y;i++,x++;){
if(x%2 = 0){
even = even + x;
evenx++;
}
if(x%2 = 1){
odd = odd + x;
oddx++;
}
}
evena = even/evenx;
odda = odd/oddx;
//print it out. There. The algorithm.
God. Do this site have auto-format?

Simulating Logarithms by repeated Integer division

I'm trying to write a program that simulates logarithms by repeated integer division. A user inputs a base number and a value X that they want to take the log of. The code runs through a loop and increments a count after each successive division. The code is set to stop after the value of X gets smaller than the base because I'm only using int type variables.
This code works fine for some numbers and bases but for others it gives the wrong value. It does " log_2(64) is 6 " however it doesn't do log_10 of 100. It gives a count of 10.
public static void main(String[] args) {
Scanner inScan = new Scanner(System.in);
int base;
int X;
int response;
int n=0;
do{
System.out.println("Java Lab 3 Logarithm Solver.");
System.out.println("Please enter a base > 1");
base = inScan.nextInt();
System.out.println("Please enter a number, X>0.");
X = inScan.nextInt();
if (X > 0 && base > 1){
System.out.println("Logarithm base " +base+ " of " +X+" is ");
for ( ; X>base ;n++){
X=(X/base);
}
System.out.println(n);
} else {
System.out.println("Invalide numbers.");
}
System.out.println("Would you like to go again? Press 1, press 0 to quit");
response = inScan.nextInt();
} while (response == 1);
}
}
You are declaring n as a global variable; I suspect that if you check your tests, this algorithm works only the first time through every time you compile and run it. Instead of having n as global, declare it in your for loop like
for(int n = 0; X < base; n++)
since it looks like you need the value of n later, I suggest having a variable with a wider scope, perhaps declared in the do-while loop, to store the n in, like
do
{
int numberOfTimesThroughLoop = 0;
...
for(...)
{
x = x/base;
numberOfTimesThroughLoop = n;
}
}
as a side note, most of the time variables (even single letter variable, like your 'X') being with a lower case character

Code error. Getting wrong answer when it's perfect?

package Basics;
import java.util.Scanner;
public class ForLoop {
public static void main(String args[]){
Scanner Jee = new Scanner(System.in);
int Final = 0;
int HowManyRounds = 1;
for (int counter = 1; counter <= HowManyRounds; counter++){
System.out.println("Type your boundary: ");
int Limit = Jee.nextInt();
System.out.println("Type the number which you want the sum of all multiples in given boundary: ");
int number = Jee.nextInt();
System.out.println("Type your starting number: ");
int StartingNumber = Jee.nextInt();
for(int Answer = StartingNumber; Answer <= Limit;Answer += number){
Final += Answer;
}
}
System.out.println(Final);
Jee.close();
}
}
i'm getting wrong answer. i don't know why. when i type 1000 for boundary 5 for round and 0 for starting number, i'm supposed to get 99500 but i'm getting 100500 and when i type for 1000 3 0, i'm getting right answer where as i get same answer for 99 3 0...
Type your boundary:
1000
Type the number which you want the sum of all multiples in given boundary:
5
Type your starting number:
0
100500
Type your boundary:
1000
Type the number which you want the sum of all multiples in given boundary:
3
Type your starting number:
0
166833
Type your boundary:
999
Type the number which you want the sum of all multiples in given boundary:
3
Type your starting number:
0
166833
If you expect an answer of 99500 in the first case, that probably means you don't want to include the limit itself in your operation (which you are doing right now). Try to change the condition in the for loop to answer < limit (instead of <=):
for(int Answer = StartingNumber; Answer < Limit;Answer += number){
[...]
You are not zeroing Final when you start a new loop.
Instead, move the declaration of Final inside the loop:
for (int counter = 1; counter <= HowManyRounds; counter++){
int Final = 0; // now Final is zeroed automatically for every iteration
// rest of loop the same
}
And please adhere to java naming conventions: variables shoiuld start with a lowercase letter, ie int total, not int Total
You seem to having trouble making this work. Here's the whole method fixed, including fixing style issues. Whether the logic is correct, I can't say, because you haven't told us what it is you're actually doing.
private static final int ROUNDS = 3;
public static void main(String args[]){
Scanner keyboard = new Scanner(System.in);
for (int i = 0; i < ROUNDS; i++) {
System.out.println("Type your boundary: ");
int limit = keyboard.nextInt();
System.out.println("Type the number which you want the sum of all multiples in given boundary: ");
int number = keyboard.nextInt();
System.out.println("Type your starting number: ");
int start = keyboard.nextInt();
int total = 0;
for (int n = start; n <= limit; n += number) {
total += n;
}
System.out.println(total);
}
keyboard.close();
}

Categories