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();
}
Related
I'm very new to Java, most of the time I don't know what I'm doing. I'm trying to make a code where you can choose how many numbers to generate, the maximum and the minimum number of a random number generated.
It keeps on generating the numbers within the max and min range infinitely.
import java.util.Scanner;
import java.util.Random;
public class random_unfinished {
public static void main(String[] args) {
int numofgen, max, min, generated, avg, i;
Scanner scan = new Scanner(System.in);
Random random = new Random();
System.out.println("How many numbers would you like to generate?");
numofgen = scan.nextInt();
System.out.println("What is the maximum number?");
max = scan.nextInt() + 1;
System.out.println("What is the minimum number?");
min = scan.nextInt();
for (int value = min; value <= max;) {
value = random.nextInt(max - min) + min;
System.out.println("numbers are " + value);
}
}
}
Okay so the for loop is problematic.
Get used to this:
for (int i = 0; i < n; i++) {
if your for loop doesn't look like that, unless you're quite advanced you're probably doing it wrong.
In your case for instance:
for (int value = min; value <= max;) {
You initialise a variable called value to be the minimum.
Your test to continue is whether value is less than max (which it will be unless min is greater than max)
The thing you do each time after executing the body of the loop is ... nothing.
Hence you loop infinitely.
Compare with the gold standard:
for (int i = 0; i < n; i++) {
It initialises a variable i to 0
Its test whether to continue is if i is less than a certain number n
After each execution of the body of the loop it increments i.
Ergo - unless we do something naughty to i, (or do an early exit with a break or return) we will repeat the body of the loop n times.
Cf:
for (int value = min; value <= max; [_____you forgot this bit____] ) {
The problem is that your for-loop is going from min to max. Also, it is missing an update clause—which means that value never changes. Hence, you’re stuck with an infinite loop.
Instead, you should go from 0 to numofgen and make sure to update your i by 1 each time. This will generate as many numbers as the user desires.
import java.util.Scanner;
import java.util.Random;
public class random_unfinished {
public static void main(String[] args) {
int numofgen, max, min, generated, avg, i;
Scanner scan = new Scanner(System.in);
Random random = new Random();
System.out.println("How many numbers would you like to generate?");
numofgen = scan.nextInt();
System.out.println("What is the maximum number?");
max = scan.nextInt() + 1;
System.out.println("What is the minimum number?");
min = scan.nextInt();
for (int i = 0; i < numofgen; i++) {
value = random.nextInt(max - min) + min;
System.out.println("numbers are " + value);
}
}
}
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.
I need to write a code where you insert 10 grades and get back the average of those ten grades. I know how to do it, except I don't know how to calculate the sum of all the grades. I found on this site this code:
public int sumAll(int... nums) { //var-args to let the caller pass an arbitrary number of int
int sum = 0; //start with 0
for(int n : nums) { //this won't execute if no argument is passed
sum += n; // this will repeat for all the arguments
}
return sum; //return the sum
}
so I wrote my code like this and it worked!:
import java.util.Scanner;
public class Loop7 {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
System.out.println("Please enter how many grades you want to insert : ");
int num1 = scan.nextInt();
int num;
double sum =0;
for(int i= 0; i<num1; i++)
{
System.out.println("Please enter a grade: ");
num = scan.nextInt();
sum += num;
}
System.out.println("the average is: "+(sum)/num1);
}
so my question is what sum+=num; mean? how does that line give me the sum? and why I had to write double sum= 0?
Over here I explain each of those lines to better help you understand this code.
public class Loop7 {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in); //this is what allows the user to input their data from the console screen
System.out.println("Please enter how many grades you want to insert : "); //this just outputs a message onto the console screen
int num1 = scan.nextInt(); //This is the total number of grades the user provides and is saved in the variable named num1
int num; //just a variable with nothing in it (null)
double sum =0; //this variable is to hold the total sum of all those grades
for(int i= 0; i<num1; i++) //loops as many times as num1 (if num1 is 3 then it loops 3 times)
{
System.out.println("Please enter a grade: "); //output message
num = scan.nextInt(); //every time the loop body executes it reads in a number and saves it in the variable num
sum += num; //num is then added onto sum (sum starts at 0 but when you add 3 sum is now 3 then next time when you add 1 sum is now 4 and so on)
}
System.out.println("the average is: "+(sum)/num1); //to get the average of a bunch of numbers you must add all of them together (which is what the loop is doing) and then you divide it by the number of items (which is what is being done here)
}
sum += num; Means that your sum which is declared 0 is added with num which you get from the console. So you simply make this: sum=sum+num; for the cycle. For example sum is 0, then you add 5 and it becomes sum=0+5, then you add 6 and it becomes sum = 5 + 6 and so on. And it is double because you are using division.
The reason you needed to write
double sum = 0.0;
is because you needed to initialize the sum first. Next the
sum += num;
means
sum = sum + num;
just in a more simple way.
I have an assignment where I have to write a code which lets the user decide an amount of int values to be written in, and then decides what these values should be. There has to be atleast 2 inputs from the user. The program will then compare the values from the input and then print out the two highest values. So far I managed to print out the highest value, but I'm not sure whats wrong with the way I've done it since the output just becomes 0 if I choose to print out 2 numbers and the highest one is entered in first. And I'm also not sure how to keep track of the second highest number either. Would appreciate some help.
import java.util.Scanner;
public class ToStoersteTall{
public static void main(String[] args){
System.out.println("How many numbers? (minimum 2)?:");
Scanner reader = new Scanner(System.in);
if (reader.hasNextInt()) {
int numbers = reader.nextInt();
if (numbers >= 2) {
System.out.println("Enter value #1");
if (reader.hasNextInt()) {
int num1 = reader.nextInt();
System.out.println("Enter value #2");
if (reader.hasNextInt()) {
int num2 = reader.nextInt();
int biggest = 0;
for (int i = 3; i <= tall; i++) {
System.out.println("Enter value #" + i);
int num3 = reader.nextInt();
biggest = num1;
if(biggest < num3){
biggest = num3;
}
}
System.out.println(biggest);
} else {
System.out.println("Please enter an integer");
}
} else {
System.out.println("Please enter an integer");
}
} else {
System.out.println("Please enter an integer equal or higher than 2.");
}
} else {
System.out.print("Vennligst oppgi et heltall større eller lik 2.");
}
}
}
I have an assignment where I have to write a code which lets the user decide an amount of int values to be written in, and then decides what these values should be. There has to be atleast 2 inputs from the user. The program will then compare the values from the input and then print out the two highest values. So far I managed to print out the highest value, but I'm not sure whats wrong with the way I've done it since the output just becomes 0 if I choose to print out 2 numbers and the highest one is entered in first. And I'm also not sure how to keep track of the second highest number either. Would appreciate some help.
A couple things:
good practice to close scanner (and IO-related resources in general)
reduced if-statement blocks bloat for easier readability
you specify 2 guaranteed numbers, so attempt to parse those before looping
can remove system.exit calls or replace system.exit and move bulk of code back into the larger if-else blocks as originally state in OP (but I refer back to the sake of readability)
added check for the first and second numbers input to make sure high1 is highest value, and high2 is second highest value.
keep order while looping and checking values (note: does not use array), if the number is a new high, replace high1 and move high1's value down to high2, or if the number is a second (new) high, replace high2. If values are equal, this logic is excluded and you may want to specify based on your own constraints
import java.io.IOException;
import java.util.Scanner;
public class ToStoersteTall {
public static void main(String[] args) throws IOException {
System.out.println("How many numbers? (minimum 2)?:");
Scanner reader = new Scanner(System.in);
int n = 0;
if (reader.hasNextInt()) {
n = reader.nextInt();
} else {
System.out.println("Vennligst oppgi et heltall større eller lik 2.");
System.exit(-1); // quits execution
}
if (n < 2) {
System.out.println("Please enter an integer equal or higher than 2.");
System.exit(-2);
}
// Since guaranteed 2 numbers, parse and assign now
int high1 = 0, high2 = 0;
System.out.println("Enter value # 1");
if (reader.hasNextInt())
high1 = reader.nextInt();
System.out.println("Enter value # 2");
if (reader.hasNextInt())
high2 = reader.nextInt();
// check to see if a switch to keep correct highest order, swap values if so
if (high1 < high2) {
int t = high2;
high2 = high1;
high1 = t;
}
// loop won't execute if only 2 numbers input, but will if 3 or more specified at start
for (int i = 2; i < n; ++i) {
System.out.println("Enter value #" + (i + 1));
if (reader.hasNextInt()) {
int t = reader.nextInt();
if (t > high1) {
high2 = high1; // throw away high2 value and replace with high1
high1 = t; // replace high1 value with new highest value
} else if (t > high2) {
high2 = t;
}
} else {
System.out.println("Please enter an interger");
}
}
reader.close();
System.out.println("The two highest numbers are: " + high1 + ", " + high2);
}
}
You're already keeping track of the biggest, so why not keep track of the second biggest? Another easy way of solving this problem is to keep all the numbers in a list, sort the list by number size, and grab the two highest entries.
I tried your code and used an array to solve the problem.
import java.util.Scanner;
public class Main {
static int secondHighest(int... nums) {
int high1 = Integer.MIN_VALUE;
int high2 = Integer.MIN_VALUE;
for (int num : nums) {
if (num > high1) {
high2 = high1;
high1 = num;
} else if (num > high2) {
high2 = num;
}
}
return high2;
}
public static void main(String[] args) {
System.out.println("How many numbers? (minimum 2)?:");
Scanner reader = new Scanner(System.in);
if (reader.hasNextInt()) {
int numbers = reader.nextInt();
int[] array = new int[numbers];
if (numbers >= 2) {
System.out.println("Enter value #1");
if (reader.hasNextInt()) {
int num1 = reader.nextInt();
array[0] = num1;
System.out.println("Enter value #2");
if (reader.hasNextInt()) {
int num2 = reader.nextInt();
array[1] = num2;
int biggest = 0;
for (int i = 3; i <= numbers; i++) {
System.out.println("Enter value #" + i);
int num3 = reader.nextInt();
array[i-1] = num3;
}
System.out.println("second largest number is" + secondHighest(array));
int largest = 0;
for(int i =0;i<array.length;i++) {
if(array[i] > largest) {
largest = array[i];
}
}
System.out.println("Largest number in array is : " +largest);
} else {
System.out.println("Please enter an integer");
}
} else {
System.out.println("Please enter an integer");
}
} else {
System.out.println("Please enter an integer equal or higher than 2.");
}
} else {
System.out.print("Vennligst oppgi et heltall større eller lik 2.");
}
}
}
Test
How many numbers? (minimum 2)?:
6
Enter value #1
3
Enter value #2
4
Enter value #3
5
Enter value #4
6
Enter value #5
7
Enter value #6
8
second largest number is7
Largest number in array is : 8
There is a logic error in your program. If numbers is 2, then the for loop never gets executed, and the value of biggest remains zero because it is never updated. Change your declaration of biggest to reflect the current maximum value found so far.
int biggest = num1 > num2 ? num1 : num2;
That way if the for loop never executes then biggest will be the maximum value of the first two numbers.
As for keeping track of the second highest value, you could introduce another variable secondBiggest, initialised in a similar manner to biggest, and then write logic to update this value in your for loop. However, in my opinion, it would be much easier to change your strategy to hold the entered values into an array, then when all inputs have been entered, calculate whichever values you desire from the array. This would lead to a much cleaner solution IMO.
(I have assumed that tall in the for loop is actually meant to be numbers...)
import java.util.Scanner;
public class Foo{
public static void main(String[] args){
System.out.println("How many numbers? (minimum 2)?:");
Scanner reader = new Scanner(System.in);
if(reader.hasNextInt()){
int numbers = reader.nextInt();
if(numbers >= 2){
int[] list = new int[numbers];
for(int i = 0; i < numbers; i++){
System.out.println("Enter value #" + (i + 1));
if(reader.hasNextInt())
list[i] = reader.nextInt();
}//for
int biggest = 0;
int secondBiggest = 0;
// find the values you want
for(int i = 0; i < numbers; i++){
if(list[i] > biggest){
secondBiggest = biggest;
biggest = list[i];
}//if
else if(list[i] > secondBiggest)
secondBiggest = list[i];
}//for
// print your results
System.out.println("The biggest integer is: " + biggest);
System.out.println("The second biggest integer is: " + secondBiggest);
}//if
}//if
}//main
}//class
Right now for a Java course I'm trying to build a Mastermind-like game. In this game a 4-digit random number is generated, and the user tries to guess the number. With each guess the computer states how many correct digits are in the right order, and how many correct digits are in the wrong order.
For some reason, everything works up to my binary search for this program, which is really the heart of the program. I've spent hours tweaking it and I still cant get it. Any ideas?
In this example I'm trying to guess 9935, I realize that's not a random number though.
Thanks so much!
EDIT: When I run this program and use the guess "9875", it does not give me the right results.
The guesses and results I'm required to find are:
Please enter a four-digit number: 9874
The number of correct digits but in the wrong place: 0
The number of correct digits in the right place: 1
Please enter a four-digit number: 9899
The number of correct digits but in the wrong place: 1
The number of correct digits in the right place: 1
Please enter a four-digit number: 9593
The number of correct digits but in the wrong place: 3
The number of correct digits in the right place: 1
Please enter a four-digit number: 9935
The number of correct digits but in the wrong place: 0
The number of correct digits in the right place: 4
You are correct!
public class Mastermind {
public static void main(String[] args) {
Random randomGenerator = new Random();
Scanner input = new Scanner(System.in);
int randomNumber = 9935;
int[] randomArray = new int[4];
int temp = randomNumber;
for (int i = 3; i >= 0; i--){
int n = temp%10;
randomArray[i] = n;
temp /= 10;
}
boolean found = false;
while (found == false){
System.out.print(Arrays.toString(randomArray));
int[] guessArray = new int[4];
System.out.print("Please enter a four-digit number: ");
int guessTemp = input.nextInt();
for (int i = 3; i >= 0; i--){
int n = guessTemp%10;
guessArray[i] = n;
guessTemp /= 10;
}
if (Arrays.equals(randomArray, guessArray)){
System.out.println("You are correct!");
found = true;
} else {
int numberRightRight = 0;
int numberRightWrong = 0;
int indexFound = 0;
for(int i = 0; i < guessArray.length; i ++){
System.out.println(randomArray[i]);
indexFound = Arrays.binarySearch(guessArray, randomArray[i]);
System.out.println(indexFound);
if (indexFound >= 0){
if(indexFound == i){
numberRightRight++;
} else {
numberRightWrong++;
}
}
}
System.out.println("The number of correct digits but in the wrong place: " + numberRightWrong);
System.out.println("The number of correct digits in the right place: " + numberRightRight);
}
}
}
If you are not required to use Arrays.binarySearch(int[], int) you could use your own simple lookup method for an unsorted Array:
public static int findInArray(int[] array, int value) {
for (int i = 0; i < array.length; i++) {
if (array[i] == value) {
return i;
}
}
return -1;
}
now instead of calling Arrays.binarySearch(guessArray, randomArray[i]); just call findInArray(guessArray, randomArray[i])