So I wrote this code and I wrote " int number = input.nextInt(); " in it as an experiment. The program does exactly what I want it to, but I don't understand why this works. The variable is not used at all later on in the program, but if I remove it, the program stops working. Any ideas? My code below:
import java.util.Scanner;
/*
* Name: Ki
*/
public class Countdown {
public static void main(String[] args) {
//Create a Scanner object to accept the input from user
Scanner input = new Scanner(System.in);
// Prompt the user to enter starting number, I just set it to 5 because
// that's what the program had as standard input.
System.out.println("Enter the beginning number: ");
// I don't know how this works. I had this here as an experiment, but
// the program now doesn't work without it so I guess I'll leave it here.
int number = input.nextInt();
// sets max countdown value
int i=5;
// Make a loop that makes the program countdown until it reaches 2
while(i>1)
{
System.out.print(i + " ... \n");
i--;
}
// Makes the program print 1 without dots and print stopped at the end
if (i==1) System.out.println(i);
System.out.print("Stopped");
}
}
int number = input.nextInt();
// sets max countdown value
// Make a loop that makes the program countdown until it reaches 2
while(number>1)
{
System.out.print(number + " ... \n");
number--;
}
// Makes the program print 1 without dots and print stopped at the end
if (number==1) System.out.println(number);
System.out.print("Stopped");
Here you create Scanner, but it doesn't do anything for the user yet.
Scanner input = new Scanner(System.in);
With nextInt() the program will wait for the user input.
int number = input.nextInt();
But after that you always use i, which is set to 5.
I guess you want to use the input number as the starting number. Change the later half to this:
// You can remove: int i=5;
while(number>1)
{
System.out.print(number + " ... \n");
number--;
}
// Makes the program print 1 without dots and print stopped at the end
if (number==1) System.out.println(number);
System.out.print("Stopped");
Related
I am trying to magically learn Java in 5 weeks because of a college class. That is not enough time to learn anything. I'm trying to complete this lab in ZyBooks, but I can't figure it out and I have no information to help. I am trying to call this checkEntry method. My results are constantly 0. Please someone explain how to do this properly.
Instructions:
Ask the user for input using the following prompt (precisely): "Please
enter a number between 15 and 45. Enter 1 to exit." Store the user's
input in a variable with the integer data type. Use a while loop to
repeat the program, checking the user's entry in case they entered a 1
to exit the program. (1) Within the loop, place the prompt (user
instructions) described above. (2) Next, within the loop, collect the
user's input and store it in a variable. (3) Finally, still within the
loop, display the output string precisely as follows, then call the
checkEntry method, passing in the variable containing the user's
input. "Output: " (do not forget the space after the colon) A separate
method called "checkEntry" has been created for you in the starting
template below (note: You can restore the default code if you wish to
start over by clicking the "Load default template…" link). Within this
method, create an IF and an ELSE, using a condition for the IF that
checks to see if the value is greater than or equal to 35. If the user
enterd a value of less than 35, the checkEntry method must multiply
that value by 5 and return the result to main(). If the user enterd a
value greater than or equal to 35, the program must instead add 10 to
their number and return the result to main().
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
/* Type your code below this line. Create additional lines as needed. */
Scanner scnr = new Scanner(System.in);
int userNum;
userNum = 0;
while (userNum != 1) {
System.out.println("Please enter a number between 15 and 45. Enter 1 to exit.");
userNum = scnr.nextInt();
System.out.println("Output: " + checkEntry(userNum));
}
} // do not delete this line
public static int checkEntry(int incoming) {
/* Type your code for the checkEntry method below this line. Create additional lines as needed. */
int userNum;
userNum = 0;
if (userNum >= 35) {
userNum = userNum + 10;
} else {
userNum = userNum * 5;
}
return userNum;
} // do not delete this line
} // do not delete this line
Notice that your method checkEntry() never makes use of incoming; instead, it initializes userNum to 0, which means it always returns 0. It should therefore be:
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
/* Type your code below this line. Create additional lines as needed. */
Scanner scnr = new Scanner(System.in);
int userNum;
userNum = 0;
while (userNum != 1) {
System.out.println("Please enter a number between 15 and 45. Enter 1 to exit.");
userNum = scnr.nextInt();
System.out.println("Output: " + checkEntry(userNum));
}
} // do not delete this line
public static int checkEntry(int incoming) {
/* Type your code for the checkEntry method below this line. Create additional lines as needed. */
int userNum=0;
if (incoming >= 35) {
userNum = incoming + 10;
} else {
userNum = incoming * 5;
}
return userNum;
} // do not delete this line
} // do not delete this line
A simpler version would be:
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
/* Type your code below this line. Create additional lines as needed. */
Scanner scnr = new Scanner(System.in);
int userNum;
userNum = 0;
while (userNum != 1) {
System.out.println("Please enter a number between 15 and 45. Enter 1 to exit.");
userNum = scnr.nextInt();
System.out.println("Output: " + checkEntry(userNum));
}
} // do not delete this line
public static int checkEntry(int incoming) {
/* Type your code for the checkEntry method below this line. Create additional lines as needed. */
if (incoming >= 35)
return incoming + 10;
return incoming*5;
} // do not delete this line
} // do not delete this line
You need to assign incoming arguments in the checkEntry method.
Replace the lines int userNum; and userNum = 0; with the following line:
int userNum = incoming;
I am trying to simulate a dice game experiment. The goal is to find the average amount of rolls it will take to get the same value of a die to show in the wanted amount of consecutive rolls.
My program asks the user how many times the user wants to run the program. So it will run the loop, then stop after they get their answer, then show the amount of throws it took. Then it will repeat as many times as the user specified.
I want to take the totalThrows from each experiment and add each totalThrows together then divide by my variable turns to get the average amount of throws it would take.
I am having some trouble getting the sum of all the totalThrows. And I can only get the last totalThrow. I would appreciate it if any of you could give some suggestions on how to resolve this. I think an array could help but I haven't learned arrays in class yet.
Here is my code.
public static void main(String[] args) {
// WRITE main's CODE HERE
Scanner keyboard = new Scanner(System.in);
Random randomNumber = new Random();
int value, turns=0, nSides, rollLength; //declare variables
int totalThrows=0, roll=0, count=0,finish=0;
//ask for input
System.out.println("Please enter the number of sides (2, 4, or 6): ");
nSides = keyboard.nextInt();
System.out.println("Enter the value sought. Must be in the range [1," + nSides + "]: ");
value = keyboard.nextInt();
System.out.println("Enter the length of the run.\n" + "Remember, the bigger it is the longer it will take to find it");
rollLength = keyboard.nextInt();
System.out.println("Enter number of times to run the experiment:");
turns = keyboard.nextInt();
System.out.println("\n");
do
{
//Countinue loop until count = rollLength
while(count!=rollLength){
roll = randomNumber.nextInt(nSides)+1;
totalThrows++; //will increment after every roll
//When roll comes up as a watched value I want to increment count by one
if(roll==value){
count++; //This should stop until count is my rollLength
}
else if (roll!=value){ //When an unwanted roll comes up start over
count=0;
}
}
//finish counts how many times the experiment was successful
if (count==rollLength){
finish++;
}
System.out.println("\n");
//Display totalThrows it took until rollLength variable occurs
System.out.println("Your total rolls is: "+ totalThrows);
} while(finish!=turns); //This will repeat the experiment
}
}
Simply declare another variable up top:
int averageThrows = 0;
Add to this value each time the loop ends:
do {
// ...
averageThrows += totalThrows;
} while( finish != turns );
And then divide it by the number of turns:
averageThrows /= turns;
That ought to do it for you.
I wonder if someone could explain why the scanner keeps waiting on input? I have to stop the process on eclipse before the code block executes and I am unsure why the scanner will keep taking input all day. I expect to press enter and for the code to execute after entering X amount of numbers.
public static void main(String[] args){
Scanner aScanner = new Scanner(System.in);
int sum = 0;
System.out.println("Enter Ints : ");
while(aScanner.hasNextInt()){
sum += aScanner.nextInt();
}
System.out.println(sum);
}
if you want the program to take only X amount of numbers, you could have a counter and break the while loop after it has executed X number of times. Alternatively, you could also use a for loop to make things easier.
You could also use Ctrl+Z in eclipse to stop console from waiting for inputs.
The simplest way to solve it is:
Enter the "end of file" marker, by the combination Ctrl + z (Ctrl + d in UNIX, if I'm not wrong).
Another way would be using a centinel value tu finish the while loop:
Scanner aScanner = new Scanner(System.in);
int sum = 0, input = 0;
System.out.println("Enter Ints (-999 to finish input): ");
while ((input = aScanner.nextInt()) != -999) {
sum += input;
}
System.out.println(sum);
so the input will finish when the user enters -999, of course you can change this value.
Note:
The last approach won't work if you expect any integer (including negatives and extrene values) as input.
In this program you (the user) keeps entering numbers until you enter a zero, which is when the list terminates & you get the sum of positive even & odd and negative numbers. I have tried my best in completing it, but the problem is that both http://ideone.com/ and DrJava hang when I try to run them. But they compile fine. Here's my program:
/**
*#author DarkIceDragon
*/
import java.util.*;
class huge_addition
{
public static void main (String[] args)
{
Scanner sc = new Scanner (System.in);
System.out.println ("Enter numbers. List terminates when you enter a zero. Enter a zero when you want to begin the addition.");
int a = sc.nextInt();
int esum=0;
int osum=0;
int nsum=0;
while (a !=0)
{
if (a>0)
{
if (a%2==0)
{
esum = esum+a;
}// end of 3rd innermost if statement
else
{
osum = osum+a;
}// end of 3rd else statement
}//end of 2nd middle if-else-loop
else if (a<0)
{
nsum=nsum+a;
}//end of 2nd middle else statement
}//end of while loop
System.out.println ("The sum of even positive numbers is "+esum);
System.out.println ("The sum of odd positive numbers is "+osum);
System.out.println ("The sum of negative numbers is "+nsum);
}//end of main
}//end of class
I'll admit that its for school, but I've completed all the rest by myself (there were around 16 or so), its 12:00AM at night and I've been trying to get this program to work for over an hour. And I'm still a complete novice (although noob would be more appropriate) in Java, so I just now only the basic commands and such. Heck, until today, I still used void main() instead of public static void main(String[] args) in my programs and spent 2 hours wondering why they weren't running on NetBeans. Too bad BlueJ stopped working for me.
Any help help would be appreciated greatly. Thanks for looking & Have a great day!
Because this is your school homework I will only answer a hint: examine the position of sc.nextInt() in your code.
Second hint: try to enter number zero as the first input when running the code.
You should accept the number each time in your while loop using sc.nextInt() , and what you were doing was just going inside the while loop, and doing nothing.Accept the number every time, and based on that number, check if it is even or odd,and then add.
Here is the corrected code:
import java.util.*;
class huge_addition
{
public static void main (String[] args)
{
Scanner sc = new Scanner (System.in);
System.out.println ("Enter numbers. List terminates when you enter a zero. Enter a zero when you want to begin the addition.");
// no need ->> int a = sc.nextInt();
int num=-1;
int esum=0;
int osum=0;
int nsum=0;
while (num !=0)
{
System.out.println("enter the number");
num= sc.nextInt();
if (num%2==0)
{
esum = esum+num;
}// end of 3rd innermost if statement
else
{
osum = osum+num;
}// end of 3rd else statement
//end of 2nd middle if-else-loop
if (num<0)
{
nsum=nsum+num;
}//end of 2nd middle else statement
}//end of while loop
System.out.println ("The sum of even positive numbers is "+esum);
System.out.println ("The sum of odd positive numbers is "+osum);
System.out.println ("The sum of negative numbers is "+nsum);
}//end of main
}//end of class
I am asked to print multiples of 2 only with a never ending loop.
Attempt:
import java.util.Scanner;
public class Infiniteloop {
public static void main (String [] args)
{
Scanner input=new Scanner (System.in);
int number,x;
System.out.print("Enter a number");
number=input.nextInt();
if(number%2==0)
{
while(number>=0)
{
x= (++number);
System.out.println(x);
}
}
}
}
I can only use while-loop. So I tried to set the remainder of 2 equal to zero. I tried using the counter but it doesnt increment it. Keeps printing out zeros. I need some help. Thanks.
Supposing that you want to prompt the user for a start number and then print all the following even numbers:
number = input.nextInt(); //read the input
number += number % 2; //if input is odd, add 1
while (true)
{
System.out.println (number);
number += 2;
}
Supposing you want to check for even numbers:
while (true)
{
number = input.nextInt();
if (number % 2 == 0) System.out.println (number);
}
Or if you don't care about empty lines:
while (true) System.out.println (input.nextInt () % 2 == 0 ? "even" : "");
EDIT: Same thing for powers of two:
public static void main (String [] args)
{
Scanner input = new Scanner (System.in);
int number;
while (true)
{
System.out.print ("Enter a number");
number = input.nextInt ();
while ( (number & 1) == 0) number >>= 1;
if (number == 1) System.out.println ("Perfect divisor.");
}
I am surprised this compiles.
x= (++number)
has no semi-colon at the end.
also, move the if statement inside of the while. If you are checking for multiples of 2, you will want that check after each iteration of the loop
edit: you changed your original code. Please copy/paste from your source instead of re-typing.
Question is not very clear but may be something like this would help you:
Scanner input=new Scanner (System.in);
int number;
do {
System.out.print("Enter a number: ");
number=input.nextInt();
if(number%2==0)
System.out.println(number);
} while (number > 0);
An infinite loop does not need a counter. It can be written like this:
if((number % 2) != 0) {
number++;
}
while(true) {
System.out.println(number);
number = number + 2;
}
edit: Added infinitely finding multiples of 2
I'm guessing that this is a homework question, so perhaps explaining the methodology will help you more than a full answer.
Firstly, you can use a while loop to ensure that your code gets executed more than once:
while loop
A while loop will keep executing the code inside it while the given boolean condition evaluates to true. So, you can wrap up your code with:
while(true) {
//...
}
and anything between the brackets will continually execute (line by line) forever.
If you get a number from the user at the beginning of the loop, the loop will stop executing any further code until the user types something (it will be blocked, waiting on IO).
Once you get the number, the loop will start executing the rest of the code, before returning to the top of the loop and repeating the process.
while (true) {
//ask user for number
//print out the number
// check that it is even
// print whether it is even or odd
}
class Fordemo
{
public static void main(String args[])
{
int k,x=0;
for(k=1;k<=10;k++)
{
x=k*2;
System.out.println("multiple of 2 is "+x);
}}}