I am trying to create a program that accepts two numbers and outputs the smallest digit in one number that is larger than the other number(for example, given 4687 and 5, the program should output 6).
The problem that I'm having is that when I compile the program, even though I'm getting no errors, after inputting the two numbers, no output is being shown. The cursor just continues blinking where it is. This is the code:
import java.io.*;
import java.util.*;
public class Numbers {
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(System.in);
int smallest = 10;
int num;
System.out.printf("Enter a value for n: \n");
int n = in.nextInt();
System.out.printf("Enter a value for num: \n");
num = in.nextInt();
int ch = System.in.read();
while (ch>n && ch<smallest) {
smallest=ch;
ch = System.in.read();
}
System.out.printf("Smallest number that is larger is %d", smallest);
}
}
I ran your program just fine. What you are experiencing is probably just that the program is waiting on input from you that you do not expect to enter.
It's expecting three inputs from the user, is that how you ran it?
Did you remember to hit the enter button on your keyboard after you input the numbers?
Here's a sample output from your program:
Enter a value for n:
100
Enter a value for num:
2
0 // <-- This value corresponds to your program prompting for int ch = System.in.read();
Smallest number that is larger is 10D
HINT: You probably want to convert the value entered for n to a String, then use the toCharrArray() method on String so you can traverse each character, like what you're doing in the while loop.
Try something like:
for(char ch : Integer.toString(n).toCharArray()) {
// rest of your while loop logic
}
Related
I am doing an open university course in Java, it's been smooth sailing up until now. We are covering loops in this section and the problem I am stuck on asks for the following.
Write a program that reads values from the user until they input a 0.
After this, the program prints the total number of inputted values
that are negative. The zero that's used to exit the loop should not be
included in the total number count.
This is my the program I have written and I have run the program and it works as it should, however I keep getting failed test back with the following statement.
When input was: 5 4 -3 1 0 "Give a number:" text should appear a total of 5 times. Now the count was 0 expected:<5> but was:<0>
Here is my code, as I said when I run the program locally it seems to work just as asked for.
import java.util.Scanner;
public class NumberOfNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int numbers = 0;
while (true) {
System.out.println("Give a number.");
int number = Integer.valueOf(scanner.nextLine());
if (number == 0){
break;
}
if (number >= 1){
numbers = numbers + 1;
}
}
System.out.println("number of values is " + numbers);
}
}
You have two problems with the code :
In the number test line,you check if a number is greater than or equal to one (number >= 1), but you should check that it is less than 0 because it is need to be negative numbers. (In the question : the total number of inputted values that are negative)
You are using with scanner.nextLine() But you don't get a line, you get a number (Int if it's integers, double if it's decimal numbers) on you to change it to : scanner.nextInt() :
Here the code :
Scanner scanner = new Scanner(System.in);
int numbers = 0;
while (true) {
System.out.println("Give a number.");
int number = Integer.valueOf(scanner.nextInt());// Scanner number !!
if (number == 0){
break;
}
if (number < 0){ // Less then zero !!!
numbers = numbers + 1;
}
}
System.out.println("number of values is " + numbers);
Your problem statement says that the count of negative numbers should be the output. But what you are returning is the count of positive numbers. Change the condition from if (number >= 1) to if (number < 0).
Hope this helps.
You need the total number of inputted values that are negative. So the condition in the while loop has to change from number >= 1 to number < 0.
Check this
import java.util.Scanner;
public class NumberOfNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int numbers = 0;
while (true) {
System.out.println("Give a number.");
int number = Integer.valueOf(scanner.nextInt());
if (number == 0) {
break;
}
if (number < 0) {
numbers = numbers + 1;
}
}
System.out.println("number of values is " + numbers);
}
}
Also, prefer to use nextInt() because you know your input is of integer type.
I could not get the exact problem. But some observations.
If you really input all numbers at the first ask and then hitting ENTER, obviously it would throw NumberFormatException as "5 4 -3.." is not a valid number and the loop wont proceed. Try input each number and hit ENTER.
Scanner must be closed. If you are using JDK 8, use "try (Scanner scanner = new Scanner(System.in)) {...}. This would automatically close the scanner.
How can I make it so that I can prompt the user to input multiple integers on one line that are seperated by spaces. And if the first integer is 0 or less than 0 it will print out "Bad Input" when all the integers are inputted and the user presses enter. Also how can I make it so that when the user enters a negative number at the end of the line, it will stop entering numbers and make multiply all of them together.
This is what I have so far but i'm not sure I am doing this right.
import java.util.Scanner;
public class tempprime {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
int count = 1;
String inputnumbers;
System.out.print("Enter integers: ");
inputnumbers = input.nextLine();
for (int i = 0; i < inputnumbers.length(); i++){
if (inputnumbers.charAt(i) == ' ')
count++;
}
int[] numbers = new int[count];
}
}
You already have it so the user can enter in values until they hit enter. Now you can do is use a split operation to break the string up into an array of values.
String[] values = inputnumbers.split('\s');
Then you could replace charAt with access to the array.
Alternatively, Scanner already allows the user to enter in as many integers as they need on the same line. nextLine() finds the first occurance of a new line, but you can use input.nextInt(), grabs the next int stopping at a space, multiple times and read them in one at a time. You can also check if there are any more values remaining using the scanners hasNext methods.
https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
You can see an example of reading multiple ints below. The user can enter them in one at a time, or 3 at a time and should still work the same.
Scanner in = new Scanner(System.in);
System.out.print("Enter 3 ints:");
int a,b,c;
a = in.nextInt();
b = in.nextInt();
c = in.nextInt();
System.out.printf("A: %d B: %d C: %d", a, b ,c);
import java.util.Scanner;
import static java.lang.System.out;
public class TestingStuf2 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
out.println("Enter a number");
int number = keyboard.nextInt();
while (number < 10) {
if (number < 10) {
out.println("This number is too small.");
keyboard.nextInt();
}else{
out.println("This number is big enough.");
}
}
keyboard.close();
}
}
I'm just having a little trouble looping this code. I've just started to learn Java a these loops have been confusing me the whole time. When I run this program, if I enter a number less than 10 I get the message that says ""This number is too small" and then it allows me to type again. However if I then type a number greater than 10 I get the same message. Also, if the first number I enter is greater than 10, I get no message at all, the program just ends. Why is this happening?
I think you have forgot to reassign the number variable. That's the reason why
However if I then type a number greater than 10 I get the same
message.
Please try the code below. Thanks for #Dev.Joel's comment. I have modified the loop to do-while to suit the case better.
import java.util.Scanner;
import static java.lang.System.out;
public class TestingStuf2 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
out.println("Enter a number");
int number = keyboard.nextInt();
do{
if (number < 10) {
out.println("This number is too small.");
/*
* You should reassign number here
*/
number = keyboard.nextInt();
}else{
out.println("This number is big enough.");
}
}while(number < 10);
keyboard.close();
}
}
I suggest you use break point to debug your problem. In your case, for example, you assign 2 to number, and "This number is too small" is printed. Next, you use keyboard.nextInt() to let user input another int. However, the number is still 2. Thus condition number < 10 is true no matter what you input this time, and "This number is too small" is printed again.
So the challenge is to prompt the user to enter an integer value "count". Next
prompt them to enter "count" more values. Then square each value entered and add it to a main
value sum.Then display the sum of the square of all the numbers entered.
An example of the build output is like :
Please enter an integer value: 3
Please enter 3 numeric values:
7 8 3.5
The sum of the squares of each of these numbers is: 125.25
I'm still new to learning code, so I'm a bit lost at how to square multiple values on a single user input and also totaling them up. Can anyone offer some help?
import java.util.Scanner;
public class Assign2 {
public static void main(String[] args) {
sum_squares();
}
public static void sum_squares(){
Scanner in = new Scanner(System.in);
System.out.println ("Please enter an integer value:");
int count = in.nextInt();
System.out.println ("Please enter" + count + "more values:");
int square = in.nextInt();
}
}
You need to add a for-loop after:
System.out.println ("Please enter" + count + "more values:");
The for-loop should run for count times, and each time the loop is run, it should ask the user for an input. You can then take that input and square it (remember - squaring is as easy as multiplying a number by itself! 2 * 2 = 4, or 2-squared) Once you have the squared number, add it to a sum variable which you will have created before the for-loop. Then just print out the sum after the for-loop.
Here is a great tutorial on for-loops!
I have a program that will average your numbers from the command line. Everything is in the main method.
1. The program should run allowing you to enter one number at a time and when you press enter it asks you for another number or offers the ability to press Q to get your average.
2. The program has a limit set to 20 numbers added. When you hit 21 the program notifies you that you added to many numbers and shuts down.
3. If you enter multiple numbers on the same line and press enter, for every number you enter it System.out.println a message once for every number instead of just once.
I would like to understand how to change the program to do these things.
How to get the System.out.println to only appear one time per entry.
How to get the program to output the average of 20 before it ends when someone enters 21
how do i change it to create a method for averaging outside of main then call on the averaging method inside the main.
import java.util.Scanner;
class programTwo {
public static void main (String[] args) {
Scanner scan = new Scanner(System.in);
double sum = 0;
int count = 0;
System.out.println ("Enter your numbers to be averaged:");
String inputs = scan.nextLine();
while (!inputs.contains("q")) {
Scanner scan2 = new Scanner(inputs); // create a new scanner out of our single line of input
while(scan2.hasNextDouble()) {
sum += scan2.nextDouble();
count += 1;
System.out.println("Please enter another number or press Q for your average");
}
if(count == 21)
{
System.out.println("You entered too many numbers! Fail.");
return;
}
inputs = scan.nextLine();
}
System.out.println("Your average is: " + (sum/count));
}
1.
scan2.hasNextDouble()
is parsing the line which contains multiple entries so it must be removed in the while loop. You can parse yourself using string tokenize and print the message only once.
2 . Simply add this line:
System.out.println("Your average is: " + (sum/count));
before returning in if condition to print the average before quitting.
3 . that really depends on what kind of function would you like. May be you can create a function that takes an array of numbers and prints out their average or maybe you want something else.
one possible function:
public double findAverage(ArrayList<Integer> numbers){
int sum=0;
for (Integer i: numbers){
sum+=i;
}
return sum/(double)numbers.size();
}
You can try with the following:
public static void main(String[] args){
if(args.length==20)
{
int sum=0;
sum += Integer.parseInt(args[0]); //do this for 20 array elements using loop
// do required calculation
}
else //print error message
}