I'm having some troubles with the beginning of this program.
It's supposed to take a number and determine whether or not it is perfect.
Currently I have it asking how many numbers to check, whenever I input any positive number, it asks again.
AND, whenever I input a negative number for the second question, the program ends and doesn't prompt again.
Any ideas on how to fix this?
import java.util.Scanner;
public class aermel_Perfect
{
public static void main ( String args [] )
{
int gN = getNum();
int gP = getPerfect();
}
public static int getNum() //Get amount of numbers to check
{
Scanner input = new Scanner ( System.in );
System.out.print( "How many numbers would you like to test? " );
int count = input.nextInt();
int perfect = 1;
boolean vN = validateNum(count, perfect);
return count;
}
public static boolean validateNum( int count, int perfect ) //Check if number is valid
{
if (( count <= 0) || ( perfect <= 0))
{
System.out.print( "Non-positive numbers are not allowed.\n");
}
else
{
return true;
}
return false;
}
public static int getPerfect() //Gets the numbers to test
{
Scanner input = new Scanner ( System.in );
int perfect = -1;
int count = getNum();
System.out.print("Please enter a perfect number: " );
perfect = input.nextInt();
boolean vN = validateNum(perfect, count);
return perfect;
}
}
Use a while loop in your get methods e.g. to repeatedly ask for input until a valid number is entered.
public static int getNum() //Get amount of numbers to check
{
Scanner input = new Scanner ( System.in );
System.out.print( "How many numbers would you like to test? " );
int count = input.nextInt();
int perfect = 1;
boolean vN = validateNum(count, perfect);
while(!vN ){
System.out.println("Invalid input. Try again");
count = input.nextInt();
vN = validateNum(count, perfect);
}
return count;
}
Simiilarly, update the getPerfect method and remove int count = getNum(); statement from this method.
EDIT: To repeatedly ask for perfect number count times, update your main method as below:
public static void main ( String args [] )
{
int gN = getNum();
for(int indx=0; indx <gN; indx++){
int gP = getPerfect();
//use your gP numbers in the way you want
}
}
EDIT1: To call How many numbers would you like to test? " tow times, I think you can simply call your getNum() method two times in the main method as below:
public static void main ( String args [] )
{
int gN = getNum();//first call
gN = getNum(); //second call
int gP = getPerfect();
}
int count = getNum();
System.out.print("Please enter a perfect number: " );
perfect = input.nextInt();
You get two numbers here.
Related
So I'm learn java for the first time and can't seem to figure how to set up a while loop properly .
my assignment is Write a program that reads integers, finds the largest of them, and counts its occurrences.
But I have 2 problems and some handicaps. I'm not allowed to use an array or list because we haven't learned that, So how do you take multiple inputs from the user on the same line . I posted what I can up so far . I am also having a problem with getting the loop to work . I am not sure what to set the the while condition not equal to create a sential Value. I tried if the user input is 0 put I cant use user input because its inside the while statement . Side note I don't think a loop is even needed to create this in the first place couldn't I just use a chain of if else statement to accomplish this .
package myjavaprojects2;
import java.util.*;
public class Max_number_count {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int count = 0;
int max = 1;
System.out.print("Enter a Integer:");
int userInput = input.nextInt();
while ( userInput != 0) {
if (userInput > max) {
int temp = userInput;
userInput = max;
max = temp;
} else if (userInput == max) {
count++ ;
}
System.out.println("The max number is " + max );
System.out.println("The count is " + count );
}
}
}
So how do you take multiple inputs from the user on the same line .
You can use scanner and nextInput method as in your code. However, because nextInt only read 1 value separated by white space at a time, you need to re-assign your userInput varible at the end of while loop to update the current processing value as below.
int userInput = input.nextInt();
while ( userInput != 0) {
//all above logic
userInput = input.nextInt();
}
The code:-
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int max = 0, count = 0, num;
System.out.println("Enter numbers:-");
while ((num = sc.nextInt()) != 0) {
if (num > max) {
max = num;
count = 1;
} else if (num == max) {
count++;
}
}
System.out.println("\nCount of maximum number = "+count);
}
}
And you don't have to use ArrayList or Array. Just keep inputting numbers till you get 0.
You can implement this with a single loop. The traditional concise pattern for doing so involves the fact that assignment resolved to the value assigned. Thus your loop can use (x = input.nextInt()) != 0 to terminate (handling exceptions, and non-integer input left as an exercise for the reader). Remember to display the max and count after the loop and reset the count to 1 when you find a new max. Also, I would default max to Integer.MIN_VALUE (not 1). That leaves the code looking something like
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a Integer:");
int count = 0, max = Integer.MIN_VALUE, userInput;
while ((userInput = input.nextInt()) != 0) {
if (userInput > max) {
max = userInput;
count = 1;
} else if (userInput == max) {
count++;
}
}
System.out.println("The max number is " + max);
System.out.println("The count is " + count);
}
import java.util.Scanner;
class Main {
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args) {
int testNumber = userInput.nextInt();
do{
System.out.println(newNumber * 2);
newNumber++;
}while( testNumber < 1000000);
}
}
You need to update the number after you multiply it by 2:
newNumber = newNumber * 2;
System.out.println(newNumber);
Also you are using newNumber and testNumber and newNumber doesn't appear to be defined anywhere...
}while( ***testNumber***newNumber*** < 1000000);
You need to pick one because if you are updating newNumber but comparing testNumber in your loop you will have created an infinite loop.
The code you have shown shouldn't compile unless you are leaving something out of your post.
You have the right idea with your loop, but you have multiple problems with your variables.
Your first problem is that you read in a variable from the user - testNumber, but then you are (incorrectly) manipulating a completely different variable - newNumber.
Your second problem is that you are testing the unchanged variable as your stop condition.
You probably want your loop to be something like:
do {
testNumber = testNumber * 2;
System.out.println(testNumber);
} while(testNumber < 1000000);
You can also make a recursive method for it.
public int reachMillion(int num) {
if(num<=0)
return -1; // indicating it is not possible.
if(num>=1000000) // Base Condition denoting we have reached 1 million
return num;
return reachMillion(num*2); // recursive part to multiply by 2 until we reach 1 million
}
class Main {
private static Scanner userInput = new Scanner(System.in);
public static void main(String[] args) {
int newNumber = 0;
do{
System.out.println("Enter a positive number: ");
try{
newNumber = userInput.nextInt();
}catch(Exception ignored){ }
System.out.println("");
}while(newNumber <= 0);
System.out.println("----- " + newNumber + " multiply by 2 ------");
while(newNumber <= 1_000_000){
System.out.print("2 * " + newNumber +" = ");
newNumber <<= 1;//in some compilers left shift is faster than multiply
System.out.println(newNumber);
}
}
#brso05 has done well describing what went wrong here. I'd like to offer a complete example:
import java.util.Scanner;
public class Main {
private static Scanner userInputScanner = new Scanner(System.in);
public static void main(String[] args) {
System.out.print("Please input a number: ");
int userInputNumber = userInputScanner.nextInt();
System.out.println();
int newNumber = userInputNumber;
while (newNumber < 1_000_000) {
newNumber *= 2; // Take the variable on the left, multiply it by the number on the right, and save it in the variable on the left
System.out.println(newNumber);
}
}
}
Try it online!
Beware! That code does not handle any bad user input. For instance, if you give it 0, it will loop forever, and if you give it foo, it will crash. In case you want to handle all the edge cases of user input, this will do that:
import java.util.*;
public class Main {
private static Scanner userInputScanner = new Scanner(System.in);
public static void main(String[] args) {
int userInputNumber;
//
while(true) {
System.out.print("Please input a number: ");
if (userInputScanner.hasNext()) {
// The user gave us something, but we don't know if it's a number
String rawUserInput = userInputScanner.next();
try {
userInputNumber = Integer.parseInt(rawUserInput);
// If that previous line runs, the user has given us an integer!
System.out.println();
if (userInputNumber > 0) {
// The user has given a valid number. Break out of the loop and multiply it!
break;
}
else {
// The user has given a bad number. Tell them why and ask again.
System.out.println("The number has to be greater than 0.");
}
}
catch (NumberFormatException exception) {
// The user has given us something, but it wasn't an integer
System.out.println();
System.out.println("That is not a number: " + exception.getMessage());
}
}
else {
// There is no input, so we can't do anything.
return;
}
}
// Done looping through user input
int newNumber = userInputNumber;
while (newNumber < 1_000_000) {
newNumber *= 2; // Take the variable on the left, multiply it by the number on the right, and save it in the variable on the left
System.out.println(newNumber);
}
}
}
Try it online!
There is a tricky part of do-while loops. In that type of loops, do part is executed firstly. For the example below, although the input is already bigger than 1000000, it prints 1000001.
public void doWhileLoop() {
int num = 1000001;
do {
System.out.println(num);
num *= 2;
} while (num < 1000000);
}
Therefore, it will be a good idea to use some guard-clauses (aka, if-statements) before doing something in do-while loops. Like,
public void doWhileLoop() {
int num = 1000001;
if(num >= 1000000) {
return;
}
do {
System.out.println(num);
num *= 2;
} while (num < 1000000);
}
again I have a problem with doing practice prepare for the exam.
Would everyone help me? Thanks a lot
write a program input an integer in the range 100 to 200 inclusive. If the user enters invalid input then your algorithm should re-prompt the user until the input is valid. Your algorithm should then count how many numbers between 500 and 1000 which are multiples of the number input. Finally, the count should be output to the user. You should make good use of sub-modules.
Here my code
import java.util.*;
public class Exam3
{
public static void main(String args[])
{
int count = 0;
int input = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter number: ");
input = sc.nextInt();
while(input < 100 || input > 200)
{
System.out.println("Enter number between 100 to 200");
input = sc.nextInt();
count ++;
}
System.out.println("count is: " + count);
}
public static void int getCount(int input, int count)
{
for(int i = 499;i <= 1000; i++ )
{
if(i % input==0)
{
count++;
}
}
return count;
}
}
The algorithm should be:
Having correct input, find all multiples of it that are in range [500, 1000]. Count them.
It's a bad approach to check all the numbers, as we know from our math knowledge, that between k*a and k*a + a there is no number divisible by a.
Knowing that and having input we enlarge our temp initialized with value of input by input. If it's in range [500, 1000] we enlarge our counter. Simple as that.
public static void main(String args[]) {
int count = 0;
int input = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter number: ");
input = sc.nextInt();
while (input < 100 || input > 200) {
System.out.println("Enter number between 100 to 200");
input = sc.nextInt();
count++;
}
System.out.println(input + " fits " + count(input) + " times");
}
private static int count(int input) {
int result = 0;
int temp = input;
while (temp <= 1000) {
if (temp >= 500) {
result++;
}
temp += input;
}
return result;
}
According to your code, I see some issues. I'll point them out, as it is important for practicing Java.
Method can be either void or return int. You can't have void int. In this case, we return int, so int is the return type,
It's important to stick to Java styling. Don't put too many empty lines, keep indents.
Use Eclipse or IntelliJ (IntelliJ is more pro). They will point unused code blocks, so you would know that that getCount wasn't called.
I want to write a program that reads an integer number and shows the user the Max digits of that number. What is the problem with my code ?
I have tried some codes here but eclipse doesn't allow !
what is the correct form ? How should I change it to correct form ?
import java.util.Scanner;
public class TestMaxDigits {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
long n;
long max = 0;
if(n%10>max){
max = n%10 ;
System.out.println("max ="+max) ;
}
}
}
You should use hasNextInt() and nextInt() (or hasNextLong() and nextLong() ) method from Scanner class to read integer number form user input.
Try with this code:
public static void main( String[] args )
{
Scanner input = new Scanner( System.in );
while( input.hasNextInt() )
{
int n = input.nextInt();
long max = 0;
if( n % 10 > max )
{
max = n % 10;
System.out.println( "max =" + max );
}
}
}
You should describe more what exactly you want to do.
It's not working because logically your code is buggy..
public class TestMaxDigits {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
long n;// you never read any input form the keyboard
long max = 0;
if(n%10>max){//this check once for the condition and if found true
//then assign the value to max in next step.
max = n%10 ;
System.out.println("max ="+max) ;
//but since number may have more than one digit which you never checked in your logic
}
}
}
Here is one Way to do it
public class Test {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Input number");
int input=keyboard.nextInt();
keyboard.close();
int max=0;
if(input>=0){
while(input!=0){
if(max<input%10)
max=input%10;
input=input/10;
}
}else{
System.out.println("Invalid Input");
}
System.out.println(max);
}
}
What I'm assigned to do is create an object-oriented validator. The user is prompted to input an integer, and the application validates it. The end result will display on the console as follows (first 3 inputs being invalid, 4th being valid):
Welcome to the Validation Tester application
Int Test
Enter an integer between -100 and 100: X
Error! Invalid integer value. Try again.
Enter an integer between -100 and 100: -101
Error! Number must be greater than -101
Enter an integer between -100 and 100: 101
Error! Number must be less than 101
Enter an integer between -100 and 100: 100
I've been assigned to create a validation class before but never in the way I'm being asked to now. Before, I've been able to pass the sc and the prompt to the Validation class and have the methods process them accordingly. For example:
//MAIN
Scanner sc = new Scanner(System.in);
int x = Validator.getInt(sc, "Enter an integer: ", 0, 1000);
//VALIDATION CLASS
public class Validator{
public static int getInt(Scanner sc, String prompt)
{
int i = 0;
boolean isValid = false;
while (isValid == false)
{
System.out.print(prompt);
if (sc.hasNextInt())
{
i = sc.nextInt();
isValid = true;
}
else
{
System.out.println("Error! Invalid integer value. Try again.");
}
sc.nextLine(); // discard any other data entered on the line
}
return i;
}
public static int getInt(Scanner sc, String prompt,
int min, int max)
{
int i = 0;
boolean isValid = false;
while (isValid == false)
{
i = getInt(sc, prompt);
if (i <= min)
System.out.println(
"Error! Number must be greater than " + min + ".");
else if (i >= max)
System.out.println(
"Error! Number must be less than " + max + ".");
else
isValid = true;
}
return i;
}
Done as above, I understand what is happening.
However now I'm assigned get the same results using similar methods but this time the sc has its own constructor.
public class OOValidator
{
public OOValidator(Scanner sc){}
public int getInt(String prompt){}
public int getIntWithinRange(String prompt, int min, int max){}
}
I'm not asking anyone to do the assignment for me in its entirety, but I'm at a loss as to how I can both prompt the user and pass the user's input using a class that has the sc and prompt separated.
I've tried several to code it several difference ways, non of which compile.
Just create an instance of your class
//MAIN
Scanner sc = new Scanner(System.in);
OOValidator val = new OOValidator(sc);
int x = val.getInt("Enter an integer: ");
// ...
int y = val.getIntWithinRange("Enter an integer: ", 0, 1000);
//VALIDATION CLASS
public class OOValidator {
private Scanner sc;
private static final String ERROR = "Error! Invalid integer value."
+ "Try again.";
public OOValidator(Scanner sc) {
this.sc = sc;
}
public int getInt(String prompt) {
while (true) {
System.out.print(prompt);
if (sc.hasNextInt()) {
i = sc.nextInt();
sc.nextLine(); // discard any other data entered on the line
break;
} else {
System.out.println(ERROR);
sc.nextLine(); // discard any other data entered on the line
}
}
return i;
}
public int getIntWithinRange(String prompt, int min, int max) {
// same logic - use directly sc which is an instance field
}
}