I need some help with my homework, so basically we need to create a code in which we input 10 numbers in an array, then search the array if my inputted number is there, most of the code is done. I just need to method the loop for searching if the inputted number is in the array Thanks for the help!!!
public static void main(String[] args) {
int n, x, flag = 0, i = 0;
Scanner s = new Scanner(System.in);
int a[] = new int[10];
System.out.println("Enter all the values:");
for(i = 0; i < 10; i++)
{
System.out.print("Value "+(i+1)+": ");
a[i] = s.nextInt();
}
System.out.print("Enter the value you want to find: ");
x = s.nextInt();
for(i = 0; i < 10; i++)
{
if(a[i] == x)
{
flag = 1;
break;
}
else
{
flag = 0;
}
}
if(flag == 1)
{
System.out.println("The value "+x+" is found at index "+(i+1));
}
else
{
System.out.println("The value "+x+" is found at index "+(-1));
}
}
public static void main(String[] args) {
int n, x, flag = 0, i = 0;
Scanner s = new Scanner(System.in);
int a[] = new int[10];
System.out.println("Enter all the values:");
for(i = 0; i < 10; i++)
{
System.out.print("Value "+(i+1)+": ");
a[i] = s.nextInt();
}
System.out.print("Enter the value you want to find: ");
x = s.nextInt();
i = find(a, 10, x);
if(i != -1)
{
System.out.println("The value "+x+" is found at index "+(i+1));
}
else
{
System.out.println("The value "+x+" is found at index "+(-1));
}
}
private static int find(int a[],int n, int x) {
int i, flag = 0;
for(i = 0; i < n; i++)
{
if(a[i] == x)
{
flag = 1;
break;
}
else
{
flag = 0;
}
}
if(flag == 1) {
return i;
} else {
return -1;
}
}
public class Main {
public static int findIndexOfNumber(int numberToSearch, int[] numbers) {
for(int i=0; i<numbers.length; i++) {
if(numbers[i]==numberToSearch) {
return i;
}
}
return -1;
}
public static void main(String[] args) {
int n, x, flag = 0, i = 0;
Scanner s = new Scanner(System.in);
int a[] = new int[10];
System.out.println("Enter all the values:");
for(i = 0; i < 10; i++) {
System.out.print("Value "+(i+1)+": ");
a[i] = s.nextInt();
}
System.out.print("Enter the value you want to find: ");
x = s.nextInt();
flag = findIndexOfNumber(x, a);
System.out.println("The value "+x+" is found at index "+flag);
}
}
You can try this also
Related
I created a while loop calculate the area and compare the price of that area with the given price and if the given price is lower then our result is the calculated area. I need to print all the result in the end when the while loop break. Therefore I am storing the result in an array to print it when the while loop breaks but the for at the end is not executing.
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
String[] result = new String[t];
while (t != 0) {
int j = 0;
int n = sc.nextInt();
int b = sc.nextInt();
int w[] = new int[n];
int h[] = new int[n];
int p[] = new int[n];
int area[] = new int[n];
for (int i = 0; i < n; i++) {
w[i] = sc.nextInt();
h[i] = sc.nextInt();
p[i] = sc.nextInt();
}
for (int i = 0; i < n; i++) {
area[i] = w[i] * h[i];
System.out.println("Area: " + area[i]);
}
int count = 0;
for (int i = 0; i < n; i++) {
if (b >= p[i]) {
count++;
}
}
System.out.println("count: " + count);
if (count == 0) {
result[j] = "no tablet";
} else {
int check[] = new int[count];
for (int i = 0; i < count; i++) {
if (b >= p[i]) {
check[i] = area[i];
}
}
Arrays.sort(check);
result[j] = "" + check[count - 1];
}
j++;
t--;
}
for (int i = 0; i < t; i++) {
System.out.println("Result: " + result[i]);
}
Here is the correct code. I have removed the error and put some prompt for user to enter values. your last for loop was not running because in while loop your value of 't' becomes 0, and it the end you were using that t in the for loop condition, that's why it was not running. I have used another variable for that. so Your problem is resolved now. Here is the complete correct code.
Scanner sc = new Scanner(System.in);
int t=sc.nextInt();
String[] result=new String[t];
int x = t;
while(t!=0) {
int j=0;
int n=sc.nextInt();
int b=sc.nextInt();
int w[]=new int[n];
int h[]=new int[n];
int p[]=new int[n];
int area[]=new int[n];
for(int i=0;i<n;i++) {
System.out.println("Enter Width for w["+i+"]: ");
w[i]=sc.nextInt();
System.out.println("Enter Height for h["+i+"]: ");
h[i]=sc.nextInt();
System.out.println("Enter Price for w["+i+"]: ");
p[i]=sc.nextInt();
}
for(int i=0;i<n;i++) {
area[i]=w[i]*h[i];
System.out.println("Area A["+i+"]: " +area[i]);
}
int count=0;
for(int i=0;i<n;i++) {
System.out.println("b = "+b+" and p["+i+"] = "+p[i]);
if(b>=p[i]) {
count++;
}
}
System.out.println("count: "+count);
if(count==0) {
result[j]="no tablet";
}else {
int check[]=new int[count];
for(int i=0;i<count;i++) {
if(b>=p[i]) {
check[i]=area[i];
}
}
Arrays.sort(check);
result[j]=""+check[count-1];
}
j++;
t--;
}
for(int i=0;i<x;i++) {
System.out.println("Result: "+result[i]);
}
you must check your list grater than notation
like that
while(t>0)
and area you must declaration outside while loop
i think like that
Scanner sc = new Scanner(System.in);
int t=sc.nextInt();
String[] result=new String[t];
List area=new List<int>();
while(t>0) {
int j=0;
int n=sc.nextInt();
int b=sc.nextInt();
int w[]=new int[n];
int h[]=new int[n];
int p[]=new int[n];
for(int i=0;i<n;i++) {
w[i]=sc.nextInt();
h[i]=sc.nextInt();
p[i]=sc.nextInt();
}
for(int i=0;i<n;i++) {
area.Add(w[i]*h[i]);
System.out.println("Area: "+area[i]);
}
int count=0;
for(int i=0;i<n;i++) {
if(b>=p[i]) {
count++;
}
}
System.out.println("count: "+count);
if(count==0) {
result[j]="no tablet";
}else {
int check[]=new int[count];
for(int i=0;i<count;i++) {
if(b>=p[i]) {
check[i]=area[i];
}
}
Arrays.sort(check);
result[j]=""+check[count-1];
}
j++;
t--;
}
for(int i=0;i<t;i++) {
System.out.println("Result: "+result[i]);
}
}
}
I want my code to loop, but reinitialize the variable back to 0. Every time I input a number, it add it to the previous result, but I want it to reset. I attached two images below. One is the actual output and the other is the expected output.
import java.util.Scanner;
public class AddOrMultiplyNNumbers {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String am;
int sum = 0;
int total = 1;
int n = 0;
while (true) {
System.out.print("enter an integer number: ");
n = input.nextInt();
if(n == 0) {
break;
}
System.out.print("enter either 'a' or 'm': ");
input.nextLine();
am = input.nextLine();
if (am.equals("a")) {
for (int y = 1; y <= n; y++) {
sum = sum + y;
}
System.out.println(sum);
} else if (am.equals("m")) {
for (int x = 1; x <= n; x++) {
total = total * x;
}
System.out.println(total);
}
}
}
}
Actual Output
Desired Output
You can use continue
if(n == 0) {
sum = 0;
total = 1;
continue;
}
You can initialize the variables inside the while loop
public class AddOrMultiplyNNumbers {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String am;
while (true) {
int sum = 0;
int total = 1;
int n = 0;
System.out.print("enter an integer number: ");
n = input.nextInt();
if(n == 0) {
break;
}
System.out.print("enter either 'a' or 'm': ");
input.nextLine();
am = input.nextLine();
if (am.equals("a")) {
for (int y = 1; y <= n; y++) {
sum = sum + y;
}
System.out.println(sum);
} else if (am.equals("m")) {
for (int x = 1; x <= n; x++) {
total = total * x;
}
System.out.println(total);
}
}
}
}
To zero a variable, simply assign 0 at the appropriate point.
sum = 0;
An appropriate place to insert this statement for your desired output is immediately before the first for loop. Likewise, reset total before the second for.
However, a much better way to write this is to declare the variable where it is needed, as you have done for x and y. This applies to am, sum, total and n
Scanner input = new Scanner(System.in);
while (true) {
System.out.print("enter an integer number: ");
int n = input.nextInt();
if (n == 0) {
break;
}
System.out.print("enter either 'a' or 'm': ");
input.nextLine();
String am = input.nextLine();
if (am.equals("a")) {
int sum = 0;
for (int y = 1; y <= n; y++) {
sum = sum + y;
}
System.out.println(sum);
} else if (am.equals("m")) {
int total = 1;
for (int x = 1; x <= n; x++) {
total = total * x;
}
System.out.println(total);
}
}
I don't know if I fully understand your question, but just do sum=0; and total=1; after you print out the final result. You should also consider doing a try/catch statement for robustness on the nextInt so that characters and strings don't break your program...
try {
n = input.nextInt();
}
catch (Exception e) {
System.out.println("Not a Number");
}
I am going to include just the necessary code here. I have indicated the problem area, about 8 lines in. I am wanting to use the containSameElements method with these inputs, k and n. I know that the problem is that it is not in the right data type (array) but i'm not sure where to change it/ what to change. I've been messing with this for some time now and I just can't seem to figure it out
import java.util.Scanner;
class Lottery
{
public static double jackpotChance(int k, int n, int m)
{
double jackpotChance = 0;
System.out.println(factorial(n)); //factorial
return jackpotChance;
}
public static double factorial(int n)
{
double result = 1;
for (int i = 1; i <= n; i++) //counter i
{
result *= i;
}
return result;
}
public static int[] enterNumbers(int k, int n)
{
System.out.println();
Scanner s = new Scanner(System.in);
System.out.println("Enter k.");
k = s.nextInt();
System.out.println("Enter n.");
n = s.nextInt();
final int SIZE = k;
int enterNumbers[]= new int[SIZE];
System.out.println("Enter " + k + " integers between 1 and " + n + ".");
int i=SIZE;
for (i = 0; i < enterNumbers.length; i++) //counter i
{
System.out.println("Enter the next number");
Scanner ss = new Scanner(System.in);
int p = ss.nextInt();
if (p >= 1 && p <= n)
{
enterNumbers[i] = p;
}
else
{
System.out.println("Invalid input, please try again.");
i--;
}
}
System.out.println();
System.out.println("Your chosen numbers are: ");
for (i = 0; i < enterNumbers.length; i++)
{
System.out.print(enterNumbers[i] + " ");
}
System.out.println();
System.out.println("Enter m.");
int m = s.nextInt();
jackpotChance(k,n,m);//jackpot
drawNumbers(k,n);
return enterNumbers;
}
public static int[] drawNumbers(int k, int n)
{
int drawNumbers[]= new int[k];
int randNumber;
int i=k;
for (i = 0; i < drawNumbers.length; i++)
{
randNumber = (int) (Math.random()*n + 1); // random draw number
drawNumbers[i] = randNumber; }
System.out.println();
System.out.println("Your drawn numbers are: ");
for (i = 0; i < drawNumbers.length; i++) //counter i
{
System.out.print(drawNumbers[i] + " ");
}
return drawNumbers;
}
public static void main (String[] args)
{
System.out.println("Welcome to the Tennessee Lottery");
System.out.println("----------------------------");
int k = 0;
int n = 0;
enterNumbers(k,n);
if(containSameElements(a,b)==true)
System.out.println("Winner!");
else
System.out.println("Loser.");
}
public static boolean containSameElements(int[] a, int[] b)
{
int len1 = a.length;
int len2 = b.length;
if(len1!=len2)
return false;
else
{
int flag = 0;
for(int i=0;i<len1;i++)
{
for(int j=0;j<len2;j++)
{
if(a[i]==b[j])
{
flag = 1;
break;
}
}
if(flag==0)
return false;
else
flag = 0;
}
}
return true;
}
}
Simplify your testing code.
public class ArrayOps {
static private final int SIZE = 10;
public static void main(final String[] args) {
System.out.println("Welcome to the Tennessee Lottery");
System.out.println("----------------------------");
final int[] k = new int[SIZE];
final int[] n = new int[SIZE];
enterNumbers(k, n);
if (containSameElements(k, n) == true) //PROBLEM AREA
System.out.println("Winner!");
else System.out.println("Loser.");
}
private static void enterNumbers(final int[] pK, final int[] pN) {
for (int i = 0; i < SIZE; i++) {
pK[i] = (int) (Math.random() * SIZE);
pN[i] = (int) (Math.random() * SIZE);
}
}
public static boolean containSameElements(final int[] pK, final int[] pN) {
if (pK.length != pN.length) return false;
// mandatory check
for (final int k : pK) {
if (!arrayContains(pN, k)) return false;
}
// optional check, only if arrays have to contain EXACTLY the same elements
for (final int n : pN) {
if (!arrayContains(pK, n)) return false;
}
return true;
}
static private boolean arrayContains(final int[] pArray, final int pLookForNumber) {
for (final int i : pArray) {
if (i == pLookForNumber) return true;
}
return false;
}
public static int[] drawNumbers(final int k, final int n) {
final int drawNumbers[] = new int[k];
int randNumber;
int i = k;
for (i = 0; i < drawNumbers.length; i++) {
randNumber = (int) (Math.random() * n + 1); // random draw number
drawNumbers[i] = randNumber;
}
System.out.println();
System.out.println("Your drawn numbers are: ");
for (i = 0; i < drawNumbers.length; i++) //counter i
{
System.out.print(drawNumbers[i] + " ");
}
return drawNumbers;
}
}
I am trying to write a program that does the following.
1) Prompts user for a integer and stores it.
2) Uses the users input to calculate the
*Arithmetic Mean
*Geometric Mean
*Min and Max of the number that they just entered.
I've done most of it and from what I see, I asked the User for a input and stored it under the variable userInput in
the first method.
I am not sure on how to use the userInput for Arithmetic Mean, Geometric Mean, and Min and Max.
public class SimpleStatistics {
public static double[] getUserInput() {
// Returns a string of doubles
Scanner sc = new Scanner(System.in);
// Create list
List<Double> inputList = new ArrayList<Double>();
// Getting input
System.out.println("Please enter number");
double userInput = sc.nextDouble();
// See our new list
System.out.println(inputList);
double arr[] = new double[inputList.size()];
System.out.println(inputList.size());
return arr;
}
public static double arithmeticMean(double[] nums) {
double mean = 0;
double sum = 0;
for (int i = 0; i < nums.length; i++) {
sum = sum + nums[i];
}
mean = sum / nums.length;
return mean;
}
public static double geometricMean(double[] nums) {
double gm = 1.0;
for (int i = 0; i < nums.length; i++) {
gm *= nums[i];
}
gm = Math.pow(gm, 1.0 / (double) nums.length);
return gm;
}
public static double[] minAndmax(double[] nums) {
double min = nums[0];
double max = nums[0];
for (int i = 1; i < nums.length; i++) {
if (nums[i] < min) {
min = nums[i];
} else if (nums[i] > max) {
max = nums[i];
} else {
}
}
double[] minAndmax = { min, max };
return minAndmax;
}
public static double[] scaleUp(double[] nums, int factor) {
for (int i = 0; i < nums.length; i++) {
nums[i] *= factor;
}
return nums;
}
public static double[] scaleDown(double[] nums, int factor) {
for (int i = 0; i < nums.length; i++) {
nums[i] /= factor;
}
return nums;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double[] input = { 1, 2.8, 5.3, 100, -5, -6.5 };
System.out.println("Choose a option 1-6");
boolean exit = false;
while (!exit) {
System.out.println();
System.out
.println("1) Arithmetic mean, 2) Geometric mean, 3) minAndmax, 4) Scale Up, 5) Scale Down, 6) Quit");
System.out.print("Input -> ");
int choice = sc.nextInt();
System.out.println();
switch (choice) {
case 1: {
// Arithmetic mean
System.out.println("Arithmetic mean");
System.out.println(arithmeticMean(input));
break;
}
case 2: {
// Geometric mean
System.out.println("Geometric mean");
System.out.println(arithmeticMean(input));
break;
}
case 3: {
// Min and max
System.out.println("Min and Max");
for (double i : minAndmax(input)) {
System.out.print(i + ", ");
}
break;
}
case 4: {
// Scale Up
System.out.println("Scale Up");
System.out
.print("Please enter factor by which you want to scale -> ");
int factor = sc.nextInt();
for (double i : scaleUp(input, factor)) {
System.out.print(i + ", ");
}
break;
}
case 5: {
// Scale Down
System.out.println("Scale Down");
System.out
.print("Please enter factor by which you want to scale -> ");
int factor = sc.nextInt();
for (double i : scaleDown(input, factor)) {
System.out.print(i + ", ");
}
break;
}
case 6: {
exit = true;
break;
}
}
}
}
}
You are not actually adding your number to your double array. Change your getUserInput() function to the following:
public static double[] getUserInput() {
Scanner sc = new Scanner(System.in);
System.out.println("How many numbers are you entering?");
double[] arr = new double[sc.nextInt()];
for (int i = 0; i < arr.length; i++) {
System.out.println("Please enter your number");
arr[i] = sc.nextDouble();
}
sc.close();
return arr;
}
Change the getUserInput method to this:
public static double[] getUserInput() {
Scanner sc = new Scanner(System.in);
List<Double> inputList = new ArrayList<Double>();
System.out.println("Please enter how many numbers you will be inputing");
int numberOfInputs = sc.nextInt();
for (int i = 0; i < numberOfInputs; i++) {
System.out.println("Please enter a number");
double userInput = sc.nextDouble();
inputList.add(userInput);
}
sc.close();
double[] arr = new double[inputList.size()];
for (int i = 0; i < arr.length; i++) {
arr[i] = inputList.get(i);
}
return arr;
}
Then, in your main method, use the input by calling the method. E.g.
// Arithmetic mean
System.out.println("Arithmetic mean");
System.out.println(arithmeticMean(getUserInput()));
break;
I'm always happy to help, please ask if there is anything else.
This program asks for the user to input 10 numbers and is converted into an int array. If the array is lucky (contains the numbers 7, 13, or 18) then it prints out the sum of all the numbers in the array. If it does not contain those then it is false and it only prints the sum of all the even numbers.
How do I correctly ask for this input? How do I get the sum of the even numbers in the array? Is any of the other code incorrect?
import java.util.Scanner;
public class FunArrays {
public static void main(String[] args) {
// until you do user input, you should test your methods using "test" as the input.
int[] test = {1,2,3,4,5,6,7};
luckyNumber1 = {7};
luckyNumber2 = {13};
luckyNumber3 = {18};
int[] a=new int[9];
Scanner sc=new Scanner(System.in);
System.out.println("Please enter numbers...");
for(int j=0;j==9;j++)
a[j]=sc.nextInt();
}
public static int sum(int [ ] value) {
int i, total = 0;
for(i=0; i<10; i++)
{
total = total + value[ i ];
}
return (total);
}
public static int sumOfEvens (
public static boolean isLucky (int[] array) {
if ( (int == luckyNumber1) || (int == luckyNumber2) || (int == luckyNumber3 )
return true;
else
return false
}
// write the static methods isLucky, sum, and sumOfEvens
}
You have an array of size 9. Instead it should be of size 10. So, Change the initialization to
int[] a=new int[10];
Use modulo operator % or remainder operator in Java to find out even or odd numbers.
int evenSum = 0;
for(int j=0;j<a.length;j++){
if(a[j]%2 == 0){
//even numbers
evenSum = evenSum + a[j];
}else{
//odd numbers
}
}
return evenSum;
int[] a=new int[9];
Scanner sc=new Scanner(System.in);
System.out.println("Please enter numbers...");
for(int j=0;j==9;j++)
a[j]=sc.nextInt();
}
There's something wrong with your loop, it should be
for (int j = 0; j < 9; j++)
With this fix it should correctly prompt the users for 9 numbers. Change to 10 for the array and the loop it would takes in 10 number.
Sum of evens
static int sumOfEvens(int array[]) {
int sum = 0;
for(int i = 0; i < array.length; i++>) {
if(array[i] % 2 == 0)
sum += array[i];
}
return sum;
}
Input
for(int j = 0; j < a.length; j++)
a[j] = sc.nextInt();
import java.util.Scanner;
public class MyMain1 {
public static void main(String[] args) {
// until you do user input, you should test your methods using "test" as
// the input.
int[] luckyNumbers = { 7, 13, 18 };
int[] a = new int[10];
Scanner sc = new Scanner(System.in);
System.out.println("Please enter numbers...");
for (int j = 0; j <= 9; j++) {
a[j] = sc.nextInt();
}
sc.close();
boolean sumAll = false;
for (int i : a) {
for (int j : luckyNumbers) {
if (i == j) {
sumAll = true;
break;
}
}
if(sumAll) {
break;
}
}
if (sumAll) {
System.out.println("Summing all : " + sumAll(a));
} else {
System.out.println("Summing Only Even : " + sumEven(a));
}
}
public static int sumAll(int[] value) {
int total = 0;
for (int j : value) {
total = total + j;
}
return total;
}
public static int sumEven(int[] value) {
int total = 0;
for (int j : value) {
if (j % 2 == 0) {
total = total + j;
}
}
return total;
}
}