This question already has answers here:
reading from console with scanner in a loop for
(2 answers)
Closed 3 years ago.
This program is to take input from the user and to give output back showing how many numbers were above the average of the array and below it. I'm trying to put a condition on the loops to exit getting input.
import java.util.Scanner;
public class analyzeScores {
public static void count(int[] list) {
Scanner input = new Scanner(System.in);
for(int i = 0; i < list.length;i++) {
if(list[i] != 0)
list[i] = input.nextInt();
}
}
public static void sorts(int[] lists, int average) {
int high = 0;
int low = 0;
for(int i = 0; i < lists.length; i++) {
if(lists[i] >= average) {
high +=1;
}
else {
low += 1;
}
}
System.out.println("The number of higher then average scores is " + high);
System.out.println("The number of lower then average scores is " + low);
}
public static void main(String[] args) {
int[] list = new int[10];
System.out.println("Enter the scores: ");
count(list);
int total = 0;
for (int i = 0; i < list.length;i++) {
total += list[i];
}
total = total / list.length;
sorts(list, total);
}
}
I'm trying to figure out how to implement a way to input 0 to exit the loop in the count(int[] list) method. I tried to implement if(list[i] != 0) but messes the whole code up
you just have to add an else condition to your if statement in the loop,
This should work if the rest of your code works
import java.util.Scanner;
public class analyzeScores {
public static void count(int[] list) {
Scanner input = new Scanner(System.in);
for(int i = 0; i < list.length;i++) {
if(list[i] != 0){
list[i] = input.nextInt();
}else{
break;
}
}
}
public static void sorts(int[] lists, int average) {
int high = 0;
int low = 0;
for(int i = 0; i < lists.length; i++) {
if(lists[i] >= average) {
high +=1;
}
else {
low += 1;
}
}
System.out.println("The number of higher then average scores is " + high);
System.out.println("The number of lower then average scores is " + low);
}
public static void main(String[] args) {
int[] list = new int[10];
System.out.println("Enter the scores: ");
count(list);
int total = 0;
for (int i = 0; i < list.length;i++) {
total += list[i];
}
total = total / list.length;
sorts(list, total);
}
}
Related
My code is O(n^2), please to decrease as O(n).
My question is count of the left side odd numbers and right side odd numbers. If it is equal on the bothsides(left and right) then print the respecive element other wise print the "-1". my code logic was correct it executing the normal text cases, but it was failing to execute the large value of text cases.It shows the error as "time exceeded".It was exceeding the timelimit of the compiler.i want to decrease the time limit of my code.
example: my input is 4 1 4 3 8 and my output:-1 4 -1 -1
example 2: my input is 6 1 3 4 8 5 7 and my output: -1 -1 4 8 -1 -1
enter code here
import java.util.*;
public class Hello {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int temp = 0;
int count = 0;
int flag = 0;
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = s.nextInt();
}
for (int i = 0; i < n; i++) {
temp = a[i];
for (int j = 0; j < i; j++) {
if (a[j] % 2 != 0) {
count++;
}
}
for (int k = i + 1; k < n; k++) {
if (a[k] % 2 != 0) {
flag++;
}
}
if (count == flag) {
System.out.print(temp + " ");
} else {
System.out.print("-1 ");
}
count = 0;
flag = 0;
}
}
I have not tested it yet but it should work.
Your algorithm is O(n^2) and this one is O(n).
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
int n=s.nextInt();
int a[]=new int[n];
for(int i=0;i<n;i++) {
a[i]=s.nextInt();
}
int total = 0;
for(int i=0;i<n;i++) {
if(a[j]%2!=0) {
total++;
}
}
int leftTotal = 0;
for(int i=0;i<n;i++) {
int k = a[i];
if (k%2!=0) {
leftTotal++;
}
if (leftTotal = (total-leftTotal)) {
System.out.println(k);
} else {
System.out.println(k);
}
}
}
enter code here
import java.util.*;
public class Hello {
public static void main(String[] args) {
//Your Code Here
Scanner s=new Scanner(System.in);
int n=s.nextInt();
int a[]=new int[n],flag=0,count=0;
for(int i=0;i<n;i++) {
a[i]=s.nextInt();
if(a[i]%2!=0)
count++;
}
for(int i=0;i<n;i++) {
if(a[i]%2!=0)
count--;
if(flag==count)
System.out.print(a[i]+" ");
else
System.out.print("-1 ");
if(a[i]%2!=0)
flag++;
}
}
}
so in my program is where the user enters list of numbers one at a time, and when I would end the list numbers with the "end" statement which is set to -1, and once I do that I get my average, and maximum, and minimum, my problem is that when I do get the minimum output it would be -1 everytime, I'm having trouble to remove the -1 from the array, any ideas???
import java.util.Scanner; //import scanner to user scanner tool
public class Average { //creating public class
public static void main(String[]args) { //creating public static main
Scanner input = new Scanner(System.in); //creating scanner input to grab user input
System.out.println("Please enter a list of numbers, entering -1 to end the list: ");
double[] numbers = new double[20]; //creating 20 count array
double sum = 0;
int count = 0;
double average;
int end = -1;
for(int i = 0; i<numbers.length; i++) {
System.out.print("Enter a number: ");
numbers[i] = input.nextDouble();
if(numbers[i]== end) {
break;
}
sum+= numbers[i];
count++;
}
// gets average from user input of numbers
average = sum/count;
System.out.println("Average is: " + average);
double max = maxim(numbers);
System.out.println("Max: " + max);
double min = minim(numbers);
System.out.println("Min: " + min);
}
//method for finding out maximum number from user input
public static double maxim(double[] array) {
double maxNum = array[0];
for(int i = 1; i<array.length; i++) {
if(array[i] > maxNum) {
maxNum = array[i];
}
}
return maxNum;
}
//method for finding out minimum number from user input
public static double minim(double[] array) {
double minNum = array[0];
for(int i = 1; i<array.length; i++) {
if(array[i] < minNum && array[i]!=-1) {
minNum = array[i];
}
}
return minNum;
}
}
You need to docouple part of code that responsible for reading user input from code that compute statistics. And for remove -1 from resulting array you need simple don't put this value to result. When user input random number first check if it is not -1, and after that put it in result. Something like that:
import java.util.Scanner;
public class Average {
public static void main(String[]args) { //creating public static main
double[] numbers = readInputNumbers();
System.out.println("Average is: " + average(numbers));
System.out.println("Max: " + max(numbers));
System.out.println("Min: " + min(numbers));
}
public double[] readInputNumbers() {
Scanner input = new Scanner(System.in); //creating scanner input to grab user input
System.out.println("Please enter a list of numbers, entering -1 to end the list: ");
double[] numbers = new double[20];
final int endInput = -1;
for(int i = 0; i < numbers.length; i++) {
System.out.print("Enter a number: ");
double nextNumber = input.nextDouble();
if(nextNumber == endInput) {
break;
} else {
numbers[i] = nextNumber;
}
}
return numbers;
}
public static double max(double[] array) {
double maxNum = array[0];
for(int i = 1; i<array.length; i++) {
if(array[i] > maxNum) {
maxNum = array[i];
}
}
return maxNum;
}
public static double min(double[] array) {
double minNum = array[0];
for(int i = 1; i<array.length; i++) {
if(array[i] < minNum && array[i]!=-1) {
minNum = array[i];
}
}
return minNum;
}
public static double average(double[] numbers) {
double sum = 0;
for(int i = 0; i < numbers.length; i++) {
sum = sum + numbers[i];
}
return sum / numbers.length;
}
}
In jdk since 8 version your could be simplify this task like this:
import java.util.Scanner;
import java.util.stream.*;
public class Average {
public static void main(String[]args) { //creating public static main
double[] numbers = readInputNumbers();
DoubleSummaryStatistics statistics = DoubleStream.of(numbers).summaryStatistics();
System.out.println("Average is: " + statistics.getAverage()));
System.out.println("Max: " + statistics.getMax());
System.out.println("Min: " + statistics.getMin());
}
public double[] readInputNumbers() {
Scanner input = new Scanner(System.in); //creating scanner input to grab user input
System.out.println("Please enter a list of numbers, entering -1 to end the list: ");
double[] numbers = new double[20];
final int endInput = -1;
for(int i = 0; i < numbers.length; i++) {
System.out.print("Enter a number: ");
double nextNumber = input.nextDouble();
if(nextNumber == endInput) {
break;
} else {
numbers[i] = nextNumber;
}
}
return numbers;
}
}
You could take the input into a temp variables and store it in the array only if it isn't the end flag (-1). E.g.:
for(int i = 0; i<numbers.length; i++) {
System.out.print("Enter a number: ");
double temp = input.nextDouble();
if(temp == end) {
break;
}
numbers[i] = temp;
sum += numbers[i];
count++;
}
I am a beginner coder, and I am trying to find the largest value of n, but I am having trouble. I have tried to use a for loop to search each element of the array I created, but the code returns 0 every time. Is this method correct? I have tried entering the values of n into an array, but I am not sure if this is the correct method to go about solving this goal.
import java.util.*;
public class CollatzConjecture {
private static int max;
public CollatzConjecture(int maximum){
int max=maximum;
}
public static void main(String[] args) {
ArrayList<Integer> arr = new ArrayList<Integer>();
Scanner scan = new Scanner(System.in);
System.out.print("Type an integer: ");
int n = scan.nextInt();
int count = 0;
while(n>1)
{
if(n%2 == 0)
{n = n/2;}
else
{n = 3*n + 1;}
System.out.println(n + " ");
count++;
arr.add(n);
arr.get(n);
}
for(int i = 0; i<arr.size()-1; i++)
{
if(arr.get(i) > max)
{
int max = arr.get(i);
}
}
System.out.println(arr);
System.out.println("Terminated after " + count + " steps");
}
}
Made some changes, but here you go:
public class CollatzConjecture {
private int max;
public CollatzConjecture() {
ArrayList<Integer> arr = new ArrayList<Integer>();
Scanner scan = new Scanner(System.in);
System.out.print("Type an integer: ");
int n = scan.nextInt();
int count = 0;
while (n > 1) {
if (n % 2 == 0) {
n = n / 2;
} else {
n = 3 * n + 1;
}
System.out.println(n);
count++;
arr.add(n);
}
for (int i = 0; i < arr.size(); i++) {
if (arr.get(i) > max) {
this.max = arr.get(i);
}
}
System.out.println(arr);
System.out.println("Largest value of n: " + this.max);
System.out.println("Terminated after " + count + " steps");
scan.close();
}
public static void main(String[] args) {
new CollatzConjecture();
}
}
So if I understand your question correctly, you are just trying to find the maximum value in an array? If so:
int max = arr.stream().max(Integer::compare).get();
or
int max = arr.get(0);
for (int i = 1; i < arr.size(); i++)
max = Integer.max(max, arr.get(i));
I know that this question has been asked before, but not in the the format that I'm writing my code.. Just started taking java classes so I am not familiar with any complex java.. the code below consists of basically all the java I know. Please help! Thanks in advance.
import java.util.Scanner;
public class problem2try {
public static void main(String[] args) {
//declarations
Scanner keyboard = new Scanner (System.in);
int [] inputList = new int [10];
int [] distinctArray = new int [10];
int num;
int counter = 0;
//input
System.out.print("Please enter in 10 integers: ");
for (int i = 0; i < inputList.length; i++)
{
num = keyboard.nextInt();
inputList[i] = num;
}
//processing
distinctArray[0] = inputList[0];
for (int i = 1; i < inputList.length; i++)
{
for (int j = 0; j < inputList.length; j++)
{
if (inputList[i] == inputList[j])
{
counter++;
continue;
}
else
{
distinctArray[i] = inputList[i];
}
}
}
//output
System.out.println("The number of distinct numbers is " + counter);
System.out.print("The distict numbers are: ");
for (int x=0; x<distinctArray.length; x++)
{
if (distinctArray[x] != 0)
System.out.print(distinctArray[x] + " ");
}
}
}
Your logic in the "processing" block seemed off. I modified it to check the current number (outer loop) to all of the known numbers (inner loop). If no match was found, it is appended to the list of known numbers and the count is incremented.
I also modified the "output" code to print the first counter numbers from the list of known numbers. Values past that index are uninitialized.
import java.util.Scanner;
public class problem2try {
public static void main(String[] args) {
//declarations
Scanner keyboard = new Scanner (System.in);
int [] inputList = new int [10];
int [] distinctArray = new int [10];
int num;
int counter = 0;
//input
System.out.print("Please enter in 10 integers: ");
for (int i = 0; i < inputList.length; i++)
{
num = keyboard.nextInt();
inputList[i] = num;
}
//processing
for (int i = 0; i < inputList.length; i++)
{
boolean found = false;
for (int j = 0; j < counter; j++)
{
if (inputList[i] == distinctArray[j])
{
found = true;
break;
}
}
if (!found)
{
distinctArray[counter++] = inputList[i];
}
}
//output
System.out.println("The number of distinct numbers is " + counter);
System.out.print("The distict numbers are: ");
for (int x=0; x<counter; x++)
{
System.out.print(distinctArray[x] + " ");
}
}
}
import java.util.Scanner;
public class Fibonacci
{
public static void main(String[] args)
{
int count;
Scanner in = new Scanner(System.in);
System.out.println("Please enter number");
count = in.nextInt();
int[] fib = new int [count];
fib[0] = 1;
fib[1] = 1;
for (int i=2; i<count; i++)
{
fib[i] = fib[i-1] + fib[i-2];
}
for(int i=0; i<count; i++)
{
System.out.print(fib[i] + " ");
}
}
}
This is my very simple Fib program, what i cant figure out is why it always stops one number short. For example:
run: Please enter number 6 1 1 2 3 5 8 BUILD SUCCESSFUL (total time: 5
seconds)
run: Please enter number 7 1 1 2 3 5 8 13 BUILD SUCCESSFUL (total
time: 5 seconds)
I thought in my FOR loops it should be "(int i=2; i <= count;"
but when i put in greater than or equal to in both, or either FOR loop it gives me an error
Any suggestions? i know its something easy i'm overlooking
Your code is giving correct output. but still if you need one more element try to initialize array with count + 1 and then have your loop running for i <= count
public static void main(String[] args) {
int count;
Scanner in = new Scanner(System.in);
System.out.println("Please enter number");
count = in.nextInt();
int[] fib = new int [count+1];
fib[0] = 1;
fib[1] = 1;
for (int i=2; i <= count; i++){
fib[i] = fib[i-1] + fib[i-2];
}
for(int i=0; i <= count; i++){
System.out.print(fib[i] + " ");
}
}
}
Arrays are zero-based. This means, that (assuming count = 5) if you have the following array:
int[] fib = new int[5];
then you can access fib[0], fib[1], fib[2], fib[3] and fib[4]. So
for (int i = 0; i < 5; i++) {
System.out.print(fib[i] + " ");
}
would be fine. As it would access everything in fib, starting with index 0, and stopping with the last index smaller than 5, which is 4. However, if you do:
for (int i = 0; i <= 5; i++) {
System.out.print(fib[i] + " ");
}
then you will access the last index smaller than OR EQUAL TO 5, which is 5. But, as stated before, fib[5] is invalid. That's what gives you your error.
A simpler solution is to avoid needing an array in the first place and you don't need to get the size right.
public static void main(String[] args) {
System.out.println("Please enter a number");
Scanner in = new Scanner(System.in);
int count = in.nextInt();
long a = 1, b = 1;
for(int i = 0; i < count; i++) {
System.out.print(a + " ");
long c = a + b;
a = b;
b = c;
}
System.out.println();
}
There should be one more array element space for int fib[], thus the fib[count] could be stored.
import java.util.Scanner;
public class Fibonacci
{
public static void main(String[] args)
{
int count;
Scanner in = new Scanner(System.in);
System.out.println("Please enter number");
count = in.nextInt();
int[] fib = new int [count + 1];
fib[0] = 1;
fib[1] = 1;
for (int i=2; i <= count; i++)
{
fib[i] = fib[i-1] + fib[i-2];
}
for(int i = 0; i<= count; i++)
{
System.out.print(fib[i] + " ");
}
}
}
public class Fibonacci
{
private int [] fibArray;
public Fibonacci()
{
}
public void Fibonacci()
{
fibArray = new int[0];
}
public void setFibonnaci(int size)
{
fibArray = new int[size];
if(fibArray.length == 1)
{
fibArray [0] = 0;
}
else if(fibArray.length == 2)
{
fibArray[0] = 0;
fibArray[1] = 1;
fibArray[2] = 2;
}
else
{
fibArray[1] = 1;
fibArray[0] = 0;
for(int x = 2; x < fibArray.length; x++)
{
fibArray [x] = fibArray[x-1] + fibArray[x-2];
}
}
}
public int getSequence(int number)
{
if(number -1 < fibArray.length)
{
return fibArray[number - 1];
}
return -1;
}
//check the test case for getFibo
public String toString()
{
String output = "";
for (int x = 0; x < fibArray.length; x++)
{
output += x + " - " + fibArray[x];
}
return output;
}
}
Late response but new to site and just trying to help. This fib class works 100%