How do I fix this code? - java

import java.util.Scanner;
import java.util.Arrays;
public class AttendanceManager {
public static void main(String args[])
{
System.out.println("Enter the number of students that are to be recorded.");
Scanner studentNum = new Scanner(System.in);
int x = studentNum.nextInt();
final int number[] = new int[x];
for(int i=0; i<x; i++)
{
System.out.println("Enter 1 if the student is present and 0 if the student is not.");
final Scanner attendance = new Scanner(System.in);
int inp = attendance.nextInt();
int y = inp;
switch (inp)
{
case 1:
number[y] = 1;
y = y++;
break;
case 0:
number[y] = 2;
y = y++;
break;
default:
System.out.println("Please enter 1 or 0.");
i--;
}
}
System.out.println("Total Students: " + number.length);
for(int k=0; k<number.length; k++)
{
if (number[k] == 1)
System.out.println("Student " + (k+1) + " is " + "present.");
else if (number[k] == 2)
System.out.println("Student " + (k+1) + " is " + "absent.");
else
System.out.println("error");
}
}
}
Output:
Enter the number of students that are to be recorded.
5
Enter 1 if the student is present and 0 if the student is not.
1
Enter 1 if the student is present and 0 if the student is not.
0
Enter 1 if the student is present and 0 if the student is not.
1
Enter 1 if the student is present and 0 if the student is not.
1
Enter 1 if the student is present and 0 if the student is not.
0
Total Students: 5
Student 1 is absent.
Student 2 is present.
error
error
error
why do the last 3 not get assigned to 1 or 0?

You're using the WRONG array index:
int inp = attendance.nextInt();
int y = inp;
switch (inp)
{
case 1:
number[y] = 1;
y = y++;
y is the value the user input, e.g. 1 or 0, which you then use as your number array index. But since the user only enters 1 or 0, you NEVER set array indexes 2, 3, 4, etc... So you're trying to output array entries that never got defined.
It should be
number[i] = 1;
^--

You are introducing another counter y which has no use, just keep the i one alone.
As the possible values of y where 0 or 1 , none of the other indexes of your array would be populated correctly.
Even worse with your current code :
Index 0 will always contain 1 if 0 was provided (0 otherwise)
Index 1 will always contain 2 if 1 was provided (0 otherwise)
Other indexes are never populated, and will always contain 0.
for(int i=0; i<x; i++)
{
System.out.println("Enter 1 if the student is present and 0 if the student is not.");
final Scanner attendance = new Scanner(System.in);
int inp = attendance.nextInt();
//int y = inp;
switch (inp)
{
case 1:
number[i] = 1;
break;
case 0:
number[i] = 2;
break;
default:
System.out.println("Please enter 1 or 0.");
i--;
}
}

Related

Needed to create a function thet recieves an array of 2 degits nums , Switch between the digits and print but got an error

Write a function that receives double-digit numbers, until a number that is not double-digit is received.
• For each number received the program will generate a reverse number and print it. For example : 67 will be printed 76.
• The program will print a count of some of the received numbers thet contains the digit 5 ​​in the digit
Unity (right digit).
I researched the error I got a couple of times but couldn't solve it, if you guys can help much appreciated.
public static void switchInput() {
Scanner star = new Scanner(System.in);
int x=0 , temp=0 , y=1 , i , b=0;
x= star.nextInt();
int[] Switch = new int[x];
//input
for(i=0 ; i<y ; i++){
System.out.println("insert num "+ y + " :");
temp= star.nextInt();
x++;
y++;
Switch[i]=temp;
if(temp<10||temp>99) {
y=i;
}
if(temp%10==5) {
b++;
}
temp=0;
}
star.close();
//Switch
int j , temp2 , temp3=0;
for(j=0 ; j<x ; j++) {
temp3=Switch[j]/10;
temp2=Switch[j]%10;
temp3+=temp2*10;
Switch[j]=0;
Switch[j]=temp3;
}
//print
for(int z = 0;z<x-1;z++) {
System.out.print(" "+Switch[z]+ " ");
}
System.out.println("Number of times 5 was used is : " + b);
}
I got the error :
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 44 out of bounds for length 44
at hagashaShadi.q1.switchInput(q1.java:37)
at hagashaShadi.q1.main(q1.java:67)
See x= star.nextInt(); here your providing size of array suppose its x=3
which means int[] Switch = new int[3]; but when you are running for loop you are getting like this Switch[4] which is out of bound for the array of size 3. So solution is to use either while loop and insert only when it satisfy the condition and it should break once it cross size of array or if you want to use for loop then break out of loop when i>length-of-array
Have a look at the below code for more understanding
public static void switchInput() {
Scanner star = new Scanner(System.in);
int i=0 , countDigit=0;
List<Integer> numList=new ArrayList<>();
boolean isTwoDigitNumber=true;
//Insert all input number of 2 digit
while(isTwoDigitNumber)
{
System.out.println("insert num "+ (i+1)+ " :");
int temp= star.nextInt();
if(temp%10==5){
countDigit++;
}
if(temp>10&&temp<99) {
numList.add(temp);
i++;
}else {
isTwoDigitNumber=false;
}
}
star.close();
//Switch
//reverse the number and print
for(int j=0 ; j<numList.size() ; j++) {
int num = numList.get(j), reversed = 0;
//System.out.println("Original Number: " + num);
// run loop until num becomes 0
while(num != 0) {
// get last digit from num
int digit = num % 10;
reversed = reversed * 10 + digit;
// remove the last digit from num
num /= 10;
}
System.out.println("reverse Number: " + reversed);
}
//print number of times 5
System.out.println("Number of times 5 was used is : "+countDigit);
}

Storing Random Numbers in an Array

I am a bit confused on how I would take the randomly generated number in a range from my program, store that into an array, and read and print out from the array how many times that the number was generated.
For the random import I am using java.util.concurrent.ThreadLocalRandom;
public static void main(String[] args) {
char quitOption = 'q';
char continueOption = 'c';
char input;
int[] myArray;
Scanner console = new Scanner(System.in);
do {
int roll = ThreadLocalRandom.current().nextInt(1, 6);
System.out.println("Roll is " + roll);
System.out.println("Enter c to continue or enter q to quit ");
input = console.nextLine().charAt(0);
if (input == continueOption || input == 'C') {
roll = ThreadLocalRandom.current().nextInt(1, 6);
System.out.println("Roll is " + roll);
System.out.println("Enter c to continue or enter q to quit ");
input = console.nextLine().charAt(0);
} else if (input == quitOption || input == 'Q') {
System.exit(0);
}
} while (continueOption == 'c' || continueOption == 'C');
}
I would use a HashMap<Integer, Integer> lets call it rollMap.
Each time you roll you get int currentRoll = randomRoll().
If I were you, I would then say:
if(rollMap.containsKey(currentRoll)){
rollMap.put(currentRoll, rollMap.get(currentRoll) + 1);
}else{
rollMap.put(currentRoll, 1);
}
You can then get how many times each number was rolled by saying:
System.out.println(rollMap.get(<rollid>));
You must figure out how to overcome two problems:
Figure out how many rolls there will be, as Array's are fixed sized
Count how many time a number is rolled
You could use a List, and then use built in methods such as Collections.frequency, or if you are confined to an Array, check to make sure that adding another number will not be out of bounds, (And if it will be then copying it to a new Array) and then iterating over the Array and counting how many times each number occurs.
However, we know the range of numbers that will occur. So why not initialize an Array with six elements, and let 0 be 1, 1 be 2, and so on. Then every time that number is rolled, we increment the index of the respective number. So something like:
int roll = ThreadLocalRandom.current().nextInt(1, 6);
arr[roll -1]++;
So if a two is rolled, we will add one to the 1th index:
[0, 1, 0, 0, 0, 0]
And so on. Then when you need to count the index its a simple loop:
for(int i = 0; i < arr.length; i++) {
System.out.println(i + 1 + " occurs: " + arr[i] + " times");
}
Also you are over complicating your loop. It can be simplified to:
char input;
int[] myArray = new int[6];
Scanner console = new Scanner(System.in);
do {
int roll = ThreadLocalRandom.current().nextInt(1, 6);
System.out.println("Roll is " + roll);
myArray[roll -1]++;
System.out.println("Enter c to continue or enter q to quit ");
input = console.nextLine().charAt(0);
} while (input == 'c' || input == 'C');
for(int i = 0; i < myArray.length; i++ ) {
System.out.println(i + 1 + " occurs: " + myArray[i] + " times");
}
Sample run:
Roll is 4
Enter c to continue or enter q to quit
c
Roll is 1
Enter c to continue or enter q to quit
c
Roll is 3
Enter c to continue or enter q to quit
c
Roll is 3
Enter c to continue or enter q to quit
c
Roll is 1
Enter c to continue or enter q to quit
c
Roll is 1
Enter c to continue or enter q to quit
q
1 occurs: 3 times
2 occurs: 0 times
3 occurs: 2 times
4 occurs: 1 times
5 occurs: 0 times
6 occurs: 0 times

Printing the two highest values from user input

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

Java Programming Looping

Write a java programs that prompts the user to enter user's name and 4 numbers, reads them, then prints the smallest and largest of all the numbers typed in by the user. The program will continue looping if the largest number is greater or equal to 10. At the end, program will show how many times the program has looped. How can i loop and find how many times the program looped ?
import java.io.*;
import java.util.*;
class largestLoop
{
public static void main(String [] args) throws IOException
{
String name;
int[] num = new int[4]; // save 4 number in array
int smallest = num[0], largest = num[0];
do{
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter your name : ");
name = stdin.readLine();
System.out.println(name + ", Please enter 4 numbers");
// Read for number using for loop
Scanner inData = new Scanner(System.in);
for(int i = 0; i < num.length; i++)
{
System.out.print("Enter " + (i+1) + " : "); // value i will + 1
num[i] = inData.nextInt();
}
// Find larger and smallest
for (int i : num)
{
if (i < smallest)
{
smallest = i;
} // end finding smallest
else if (i > largest)
{
largest = i;
} // end finding largest number
} // end finding largest and smallest values
System.out.println("Largest = " + largest);
System.out.println("Smallest = " + smallest);
}while(largest >= 10);
}
}
Output :
Enter your name : testing
testing, Please enter 4 numbers
Enter 1 : 2
Enter 2 : 6
Enter 3 : -5
Enter 4 : 16
Largest : 16
Smallest : 0
Enter your name : google
google, Please enter 4 numbers
Enter 1 : 5
Enter 2 : 8
Enter 3 : 1
Enter 4 : 6
Largest : 16
Smallest : 0
Enter your name : ....
The program become infinite loop. It should stop whenever user enter numbers that less than or equal to 10. The Largest and Smallest also does not right, when user enter <= 10 in next loop number. It will display a previous value or Largest. Also , the smallest keep display a 0 value.
First of all the assignment:
int smallest = num[0], largest = num[0];
is not dynamic in nature. Meaning the value of smallest and largest is not going to change everytime the value of num[0] changes. You need to do that manually everytime new values are entered.
Secondly you have not used any variable to actually count the number of loops.
Making these changes your code should look something like this:
package com.abhinav.testing;
import java.io.*;
import java.util.*;
class largestLoop
{
public static void main(String [] args) throws IOException
{
String name;
int[] num = new int[4]; // save 4 number in array
int smallest=0,largest=0;
int count=0;
do{
count++;
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter your name : ");
name = stdin.readLine();
System.out.println(name + ", Please enter 4 numbers");
// Read for number using for loop
Scanner inData = new Scanner(System.in);
for(int i = 0; i < num.length; i++)
{
System.out.print("Enter " + (i+1) + " : "); // value i will + 1
num[i] = inData.nextInt();
}
smallest = num[0];
largest = num[0];
// Find larger and smallest
for (int i : num)
{
if (i < smallest)
{
smallest = i;
} // end finding smallest
else if (i > largest)
{
largest = i;
} // end finding largest number
} // end finding largest and smallest values
System.out.println("Largest = " + largest);
System.out.println("Smallest = " + smallest);
}while(largest >= 10);
System.out.println("Number of times the loop ran= "+count);
}
}

Java exception error on main

Hi guys im trying to make a average calculator (I'm learning java now), everything works fine except 1 thing.
Here is my code:
package projects;
import java.util.Scanner;
public class average {
public static void main (String[]args){
Scanner sc = new Scanner(System.in);
System.out.println("/////////////////////////////////");
System.out.println("/// Average Calculator ///");
System.out.println("/////////////////////////////////");
System.out.println("How many numbers: ");
int totalnumbers = sc.nextInt();
int average = 0;
int[] list;
list = new int [totalnumbers];
for(int X = 1 ; X <= totalnumbers ; X++){
System.out.println("Please choose number " + X +": ");
list[X] = sc.nextInt();
average+=list[X];
}
System.out.println("Your average is:" + (average/totalnumbers));
sc.close();
}
}
i cant figure out whats wrong but when its supposed to give me the average, it gives me this error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at projects.average.main(average.java:19)
Array indexing goes from 0 to N-1.
The runtime exception occurs when you attempt to access list[X] with x == totalnumbers.
Change this:
for(int X = 1 ; X <= totalnumbers ; X++){
System.out.println("Please choose number " + X +": ");
list[X] = sc.nextInt();
average+=list[X];
To this:
for(int X = 0 ; X < totalnumbers ; X++){
System.out.println("Please choose number " + (X+1) +": ");
list[X] = sc.nextInt();
average+=list[X];
An array of totalnumbers items starts with index 0 and ends in index totalnumbers-1.
Your X iterates from 1 to totalnumbers, hence the exception when X reaches totalnumbers.

Categories