How to fix Scanner class taking an extra blank input - java

import java.util.Scanner;
public class sumAverageUsingArray {
public static void main(String[] args) {
/**
* LargestValue
*/
final int LENGTH = 5;
int[] values = new int[LENGTH];
int currentSize = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter values and Q to Quit");
while (sc.hasNextInt() && currentSize < values.length) {
values[currentSize] = sc.nextInt();
currentSize++;
}
sc.close();
int largest = values[0];
for (int i = 1; i < currentSize; i++) {
if (values[i] > largest) {
largest = values[i];
}
}
System.out.printf("Largest is : %d", largest);
}
Expected:
5,4,3,2,1
Largest is : 5
Actual:
6,5,4,3,2,1
Largest is : 6
Scanner class takes an extra input which has no effect on the behavior of the program, how to fix it?

Replace
while (sc.hasNextInt() && currentSize < values.length) {
by
while (currentSize < values.length && sc.hasNextInt()) {
hasNextInt() is forced to block until you enter something to know if... there is a next int or not. If you enter an int, it can return true. If you enter something else, it can return false. If you don't enter enything, it needs to wait until you enter something to know what to return.

Related

unable to sort or print out array

I got a task to write the methods to 1. take information in and save it into array, 2. to copy the array(only with previously given arguments) and 3. to sort the array to be in descending order. it seems to me like i got the first 2 parts working but i have been stuck on the third method for 2 days without any progress. i am still learning java so i'm pretty sure i have made a dumb mistake somewhere. thanks in advance.
import java.util.*;
public class RevisionExercise {
public static void main(String[] args) {
int[] tempArray = new int[100];
System.out.println("Type in numbers. Type zero to quit.");
int amountOfNumbers = askInfo(tempArray);
int[] realArray = new int[amountOfNumbers];
copyInfo(realArray, tempArray);
setArray(realArray);
printArray(realArray);
}
public static int askInfo(int[] tempArray) {
Scanner reader = new Scanner(System.in);
int i;
for (i = 0; i < tempArray.length; i++) {
System.out.print((i+1) + ". number: ");
tempArray[i] = reader.nextInt();
if (tempArray[i] == 0) {
return tempArray[i];
}
}
return i;
}
private static int[] copyInfo(int[] realArray, int[] tempArray)
{
int targetIndex = 0;
for( int sourceIndex = 0; sourceIndex < tempArray.length; sourceIndex++ )
{
if( tempArray[sourceIndex] != 0 )
tempArray[targetIndex++] = tempArray[sourceIndex];
}
realArray = new int[targetIndex];
System.arraycopy( tempArray, 0, realArray, 0, targetIndex );
return realArray;
}
public static int[] setArray(int[] realArray)
{
int temp = 0;
for (int i = 0; i <realArray.length; i++) {
for (int j = i+1; j <realArray.length; j++) {
if(realArray[i] >realArray[j]) {
temp = realArray[i];
realArray[i] = realArray[j];
realArray[j] = temp;
}
}
}
return realArray;
}
public static void printArray(int[] realArray ) {
System.out.println("\nOrdered array: ");
for(int i = 0; i < realArray .length; i++) {
System.out.println(realArray [i]);
}
}
}
the output i'm getting looks like this.
Type in numbers. Type zero to quit.
1. number: 3
2. number: 8
3. number: 5
4. number: 6
5. number: 9
6. number: 0
Ordered array:
while it should look like this:
Type in numbers. Type zero to quit.
1. number: 3
2. number: 8
3. number: 5
4. number: 6
5. number: 9
6. number: 0
Ordered array:
9
8
6
5
3
You made a mistake in calculating the total numbers entered by the user. Your function always return 0. So change it to something like this:
public static int askInfo(int[] tempArray) {
Scanner reader = new Scanner(System.in);
int totalNumbers = 0;
for (int i = 0; i < tempArray.length; i++) {
System.out.print((i+1) + ". number: ");
int number = reader.nextInt();
if (number != 0) {
totalNumbers++;
tempArray[i] = number;
} else {
break;
}
}
return totalNumbers;
}
Chage the sort function to this:
public static void setArray(int[] realArray) {
int temp = 0;
for (int i = 0; i < realArray.length; i++) {
for (int j = i+1; j < realArray.length; j++) {
// Use < for descending order and > for ascending order
if(realArray[i] < realArray[j]) {
temp = realArray[i];
realArray[i] = realArray[j];
realArray[j] = temp;
}
}
}
}
Your main program
public static void main(String[] args) {
int[] tempArray = new int[100];
System.out.println("Type in numbers. Type zero to quit.");
int amountOfNumbers = askInfo(tempArray);
int[] realArray = new int[amountOfNumbers];
copyInfo(tempArray, realArray, amountOfNumbers);
setArray(realArray);
printArray(realArray);
}
public static int askInfo(int[] tempArray) {
Scanner reader = new Scanner(System.in);
int totalNumbers = 0;
for (int i = 0; i < tempArray.length; i++) {
System.out.print((i+1) + ". number: ");
int number = reader.nextInt();
if (number != 0) {
totalNumbers++;
tempArray[i] = number;
} else {
break;
}
}
return totalNumbers;
}
private static void copyInfo(int[] tempArray, int[] realArray, int size) {
for( int sourceIndex = 0; sourceIndex < size; sourceIndex++ )
{
realArray[sourceIndex] = tempArray[sourceIndex];
}
}
public static void setArray(int[] realArray) {
int temp = 0;
for (int i = 0; i < realArray.length; i++) {
for (int j = i+1; j < realArray.length; j++) {
if(realArray[i] < realArray[j]) {
temp = realArray[i];
realArray[i] = realArray[j];
realArray[j] = temp;
}
}
}
}
public static void printArray(int[] realArray ) {
System.out.println("\nOrdered array: ");
for(int i = 0; i < realArray.length; i++) {
System.out.println(realArray [i]);
}
}
To begin with, in the askInfo method, the size of the realArray will always be 0, since amountOfNumbers is the return of
if (tempArray[i] == 0) {
return tempArray[i];
}
because your condition is tempArray[i] == 0, hence you are always returning 0. Then your copyInfo method is returning an array but you have nothing receiving the returned array. I would suggest changing your copyInfo method to
private static int[] copyInfo(int[] tempArray)
{
// same
int [] realArray = new int[targetIndex];
// same
}
and your main method to
public static void main(String[] args) {
//same
int[] realArray = new int[amountOfNumbers];
realArray = copyInfo(tempArray);
// same
}
General remark: Each of your methods returns an array but you never use this return value.
There are 2 modifications necessary to fix your code:
Keep the value of the method output:
realArray=copyInfo(realArray, tempArray);
So you put the result of the copy in the realArray variable.
You expect the askInfo method to return the number of entered numbers but in fact you return the value of the last entered number.
So instead of return tempArray[i]; you have to return i;

I need help! I have been trying to write a Java program that will print out the largest prime factor of a given number determined by user input

This is my code so far but I am having trouble. I tried to create an array with all the prime
factors and print the last index of the array but I having trouble figuring out the length the array should be. Am I doing this all wrong? Is there a better method?(New to stack overflow)(still learning java).
import java.util.*;
public class Main
{
public static void main(String [] args)
{
Scanner sc = new Scanner(System.in);
int num = sc.nextInt(); //Given Number
sc.close();
int n = 0;
int [] PrimeFactors = new int[num];
for(int i = 1; n < PrimeFactors.length; i++)
{
if(checkPrime(i) == false && num % i == 0)
{
PrimeFactors[n] = i;
n++;
}
}
System.out.println(PrimeFactors[PrimeFactors.length - 1]);
}
public static boolean checkPrime(int a)
{
boolean bool = false;
if(true)
{
for(int i = 2; i <= a / 2; i++)
{
if(a % i == 0)
{
bool = true;break;
}
}
}
return bool;
}
}

Loading space-separated user input to array

I'm new to Java. I've spent hours trying to figure out why this code doesn't work. It's supposed to take user input integers separated by whitespace, and load them into an int array. Then, the numbers are supposed to be sorted in descending order, and the frequency of repeated inputs has to be displayed in a separate int array.
I'm getting zeroes in the output though. Can anyone help me fix this program?
This is what I have:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] inputNumbers = new int[50];
int[] ocurrences = new int[50];
int size = 0;
System.out.println("How many numbers to enter? (At most 50)");
size = input.nextInt();
System.out.println("Enter eaach of the numbers. Please put a space between each number.");
String arrayString = input.next();
input = new Scanner(arrayString);
while(input.hasNextInt())
{
int nextNumber = input.nextInt();
if(!isInArray(inputNumbers, size, nextNumber))
{
inputNumbers[size] = nextNumber;
ocurrences[size] = 1;
size++;
}
else
{
int index = search(inputNumbers, size, nextNumber);
ocurrences[index]++;
}
}
sort(inputNumbers, ocurrences, size);
System.out.println("N\t\tCount");
for(int i = 0; i < size; i++)
{
System.out.println(inputNumbers[i] + "\t\t" + ocurrences[i]);
}
}
public static void sort(int[] inputNumbers, int[] ocurrences, int size)
{
for(int current = 0; current < size; current++)
{
int max = current;
for(int i = current; i < size; i++)
{
if(inputNumbers[i] > inputNumbers[max])
max = i;
}
int temp = inputNumbers[max];
inputNumbers[max] = inputNumbers[current];
inputNumbers[current] = temp;
temp = ocurrences[max];
ocurrences[max] = ocurrences[current];
ocurrences[current] = temp;
}
}
public static int search(int[] array, int size, int number)
{
for(int i = 0; i < size; i++)
{
if(array[i] == number)
return i;
}
return -1;
}
public static boolean isInArray(int[] array, int size, int number)
{
for(int i = 0; i < size; i++)
{
if(array[i] == number)
return true;
}
return false;
}
}
The current output is:
How many numbers to enter? (At most 50)
4
Enter eaach of the numbers. Please put a space between each number.
5 5 4 7 8
N Count
5 1
0 0
0 0
0 0
0 0
BUILD SUCCESSFUL (total time: 11 seconds)
It should have been something like
N Count
8 1
7 1
5 2
4 1
Initialize the array where we know the exact size, so it avoid unnecessary memory utilization.
Also input.next() will read only the next complete token not the entire line. That was the mistake in the code.
Finally the scanner resource was not closed.
I have refactored your code, please check it.
public static void main(String[] args) {
Scanner input = null;
try {
input = new Scanner(System.in);
int[] inputNumbers, ocurrences;
int index = 0, size;
System.out.println("How many numbers to enter? (At most 50)");
size = input.nextInt();
inputNumbers = new int[size];
ocurrences = new int[size];
System.out.println("Enter each of the numbers. Please put a space between each number.");
for (int i = 0; i < size; i++) {
int nextNumber = input.nextInt();
if (!isInArray(inputNumbers, nextNumber)) {
inputNumbers[index] = nextNumber;
ocurrences[index] = 1;
index++;
} else {
int oIndex = search(inputNumbers, nextNumber);
ocurrences[oIndex] ++;
}
}
sort(inputNumbers, ocurrences);
System.out.println("N\t\tCount");
for (int i = 0; i < index; i++) {
System.out.println(inputNumbers[i] + "\t\t" + ocurrences[i]);
}
} finally {
input.close();
}
}
public static void sort(int[] inputNumbers, int[] ocurrences) {
int size = inputNumbers.length;
for (int current = 0; current < size; current++) {
int max = current;
for (int i = current; i < size; i++) {
if (inputNumbers[i] > inputNumbers[max])
max = i;
}
int temp = inputNumbers[max];
inputNumbers[max] = inputNumbers[current];
inputNumbers[current] = temp;
temp = ocurrences[max];
ocurrences[max] = ocurrences[current];
ocurrences[current] = temp;
}
}
public static int search(int[] array, int number) {
int size = array.length;
for (int i = 0; i < size; i++) {
if (array[i] == number)
return i;
}
return -1;
}
public static boolean isInArray(int[] array, int number) {
int size = array.length;
for (int i = 0; i < size; i++) {
if (array[i] == number)
return true;
}
return false;
}

array called peopleTypes that can store a maximum of 50 integer values. enter a series of 1,2,3,4 and output how many of each number was inputed

import java.util.Scanner;
public class People
{
public static final Scanner keyboard = new Scanner(System.in);
static final int Max= 50;
public static void main(String[]args)
{
int index;
int check;
int infants = 0, children = 0, teens = 0, adults = 0;
System.out.println("Please enter value:");
int [] peopleTypes = new int[Max];
for(index=0; index<Max; index++)
{
peopleTypes[index] = keyboard.nextInt();
if(peopleTypes[index] == 1)
infants = infants + 1;
if(peopleTypes[index] == 2)
children = children + 1;
if(peopleTypes[index] == 3)
teens = teens + 1;
if(peopleTypes[index] == 4)
adults = adults + 1;
else
index = index-1;
System.out.print("");
}
So basically I have to create a code that allows a user to input 50 values (1,2,3,4) into a array and count how many of each was inputted and outputs that. I am stuck on creating the code to count the inputted values. I am new to array and am not sure if I'm on the right path.
Actually you don't need to store the input, take a (closer) look at a possible solution:
import java.util.Scanner;
public class People {
static final Scanner keyboard = new Scanner(System.in);
static final int MAX = 50;
static final String[] LABLES = {"infants", "children", "teens", "adults"};
public static void main(String[] args) {
int[] counts = new int[4];
for (int i = 0; i < MAX; i++) {
System.out.println("Please enter value:");
int current = keyboard.nextInt(); //problem input: "abc" -> java.util.InputMismatchException
while (current > 4 || current < 1) {//checks range
System.out.println("Please enter a valid value (between 1 and 4):");
current = keyboard.nextInt();//...and repeat
}
counts[current - 1]++;//increment counter, "current - 1", since 0-based array and 1-based input
}
System.out.println("Evaluation finished!");
for (int i = 0; i < 4; i++) {//print the output
System.out.println(LABLES[i] + ": " + counts[i]);
}
}
}
I maybe misunderstanding the context but I do not see the need for creating a peopleTypesArray. My understanding is that all you need is a count or teens , adults etc from a list of 50 people, so just keep incrementing the individual counters and display them outside the loop. Something like:
for(int i = 0 ; i < 50; i++){
int peopleType = keyBoard.nextInt();
if(peopleType == 0){
infantCount++;
}
---- and so on
}
System.ou.println(" infant = " + infantCount);
--- and so on

Print Fibonacci sequence up to nth place?

I am trying to print the entire fibonacci sequence up to a given place. So the user would decide how many numbers of the fibonacci sequence they want to see (up to 16 repetitions) and it would print the entire sequence.
My current code only prints the number in the sequences for the place that you choose.
ex: 4 prints 2 instead of 0 1 1 2.
public int Fibonacci(int number){
if(number == 1 || number == 2){
return 1;
}
int fib1=1, fib2=1, fibonacci=1;
for(int count= 3; count<= number; count++){
fibonacci = fib1 + fib2;
fib1 = fib2;
fib2 = fibonacci;
}
return fibonacci;
}
Here is my main method:
import java.util.Scanner;
public class FibonacciPrinter
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter an integer: ");
int input = in.nextInt();
FibonacciGenerator newNumber = new FibonacciGenerator();
for(int fibCount = 0; fibCount < input; fibCount++)
{
System.out.println(newNumber.Fibonacci(input));
}
}
}
I think here,
for(int fibCount = 0; fibCount < input; fibCount++)
{
System.out.println(newNumber.Fibonacci(input));
}
You almost certainly wanted,
for(int fibCount = 0; fibCount < input; fibCount++)
{
System.out.println(newNumber.Fibonacci(fibCount)); // <-- fibCount not input
}
You need to update your method to handle the zero case, for example
public int Fibonacci(int number) {
if (number == 0) return 0;
// ...
}
and in Java, the convention would name Fibonacci to fibonacci because method names are camel case starting with a lower case letter (classes start with a capital letter by convention).

Categories

Resources