Checking if a math function is valid - java

I am given the function {1,2,3,4,5}. I have to receive user input on how many ordered pairs he wants, then verify if the function is valid (values for the x-coordinate have to be between 1 and 5, and an x-coordinate CAN'T be repeated). I know how to loop for and check if the value of X is between 1 and 5, however, I am having trouble checking the string for repeating elements. I wrote the conditional expression for x less than 1 and bigger than 5, but I am stumped on how to write an expression that checks for repeating elements. Can somebody help me with that please? This is what I have so far:
import java.util.Scanner;
public class Functions
{
public static void main (String args [])
{
Scanner in = new Scanner (System.in);
int []domain = new int [5];
int [] range = new int [5];
int orderedPairs = 0;
System.out.println ("Enter the number of ordered pairs please: ");
orderedPairs = in.nextInt();
while (orderedPairs < 0 || orderedPairs > 5)
{
System.out.println ("This input is invalid. Enter a number between 0 and 5 and try again:");
orderedPairs = in.nextInt ();
}
for (int i = 0; i < orderedPairs; i++)
{
System.out.println ("Enter the x-coordinate please: ");
domain [i][0] = in.nextInt();
System.out.println ("Enter the y-coordinate please: ");
range [i][0] = in.nextInt();
}
for (int i = 0; i < orderedPairs; i++)
{
System.out.println ("f(" + domain [i][0] + "): " + range [i][0]);
}
for (int i = 0; i < orderedPairs;i++)
{
if (domain [i][0] > 5 || domain [i][0] < 1)
{
function = false;
}
for (int n = i + 1; n < orderedPairs; n++)
{
if (domain[i] == domain [n] && range [n] != range [i])
{
function = false;
}
}
}
}
}
Edit :
That is all it took, apparently! :)

The simplest way to do it is this:
1) Loop over all the domains.
2) For each domain, retrieve its value. Then loop over the domains counting the number of domains whose value equals the retrieved value.
3) If that value is anything other than 1 for each domain, report an error.

Related

A program that rejects certain numbers

I need to create a program that prints 6 numbers between 1 and 42 at random where no 2 numbers are the same. The user must also insert 6 numbers. If any number is the same as the one randomly selected by the computer, the computer must print it. If not, the computer prints you are such a loser. Now, the problem is I'm not sure about how to make sure that no 2 randomly selected numbers are the same. The program should also ask for a different number if a number less than 1, greater than 42, or equal to a previous number inserted, and scan it which I am also not able to do. (user cannot enter 2 identical numbers)
import java.util.Scanner;
import java.util.Random;
public class LotoMachine {
public static void main(String[] args) {
System.out.println("Please enter 6 numbers between 1 and 42.");
Scanner scan = new Scanner(System.in);
int[] marks = new int[6];
Random ran = new Random();
int[] x = new int[6];
boolean winner = false;
for (int i = 0; i < 6; i++) {
marks[i] = scan.nextInt();
while (marks[i] > 42) {
System.out.println(marks[i] + " is out of range. Please pick a number that is less than 43.");
marks[i] = scan.nextInt();
i=0;
}
while (marks[i] < 1) {
System.out.println(marks[i] + " is out of range. Please pick a number that is greater than 0.");
marks[i] = scan.nextInt();
i=0;
}
while (marks[i] == marks[i] - 1) {
System.out.println("You have already chosen " + marks[i] + "Please pick a different number.");
marks[i] = scan.nextInt();
i=0;
}
}
for (int j = 0; j < 6; j++) {
x[j] = ran.nextInt(42) + 1;
for (int y = 0; y < j; y++) {
if (x[j] == x[y]) {
x[j] = ran.nextInt(42) + 1;
j = 0;
}
}
}
System.out.print("You chose");
for (int m = 0; m < 6; m++) {
System.out.print(" " + marks[m]);
}
System.out.println(" ");
System.out.print("The random numbers are");
for (int m = 0; m < 6; m++) {
System.out.print(" " + x[m]);
}
System.out.println(" ");
System.out.print("The number(s) that matched are");
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 6; j++) {
if (marks[i] == x[j]) {
winner = true;
System.out.print(" " + marks[i]);
}
}
}
if (winner != true) {
System.out.println("You are such a loser");
}
}
}
You can use a Set to store the values and ask for the size after the addition. Whenever you want to deal with collections of objects which should not be repeated, a Set is a good way to go, since it allows no duplication.
Something like this:
Set<Integer> numbers = new HashSet<Integer>();
random code goes here...
int size = numbers.size();
numbers.add(newValue);
if(numbers.size() == size){
number needs to be created again...
}
Basically, there are two ways to draw 6 from 42.
The first is to draw continuously until you have 6 unique numbers. Each draw has the same probabilty (1/42) to draw a particular number. Although the likelyhood of the case that you always draw the same number is low, it is not 0. So from a statistical point of view, this is not correct. In Java you could do this is
Random rand = new Random();
List<Integer> randomNumbers = Stream.generate(() -> rand.nextInt(42))
.distinct()
.limit(6)
.collect(toList());
What you actually want to have, is to draw 1 of 42, 1 of 41, 1 of 40 ... One approach to do this is to generate a list of all possible number (1..42), draw one, remove it from the list, draw another etc. In Java that would be
final List<Integer> numbers = IntStream.rangeClosed(1, 42)
.boxed()
.collect(toList());
final List<Integer> randomNumbers2 = Stream.generate(() -> rand.nextInt(numbers.size()))
.limit(6)
.map(i -> numbers.remove((int)i))
.collect(toList());
Finally reading input until you have a valid number is easily done with a do-while loop
Scanner scanner = new Scanner(System.in);
int number;
do{
number = scanner.nextInt();
} while(number < 0 && number > 42);
if(randomNumbers2.contains(number)){
System.out.println("Winner");
} else {
System.out.println("Looser");
}

Array that takes user input to fill but does not allow duplicate elements

I'm trying to write a part of a program that I have for an assignment. This part of the program should take 8 user inputed integers to fill however if the user inputs a digit that has already been inputed an error is displayed and the user is asked to input a different number. As of yet I haven't written the error code and second attempt part of the code because I am having issues with the checking for duplicates part. At present the out put is True no matter what I put in.
int maxNum = 8;
int[] arrayIn = new int[maxNum];
boolean duplicates = false;
// Run while not true
while (!duplicates) {
// For loop for input into array
for (int j = 0; j < maxNum; j++) {
System.out.println("Enter digit " + digCounter + ":");
arrayIn[j] = in1.nextInt();
digCounter++;
// Check for duplicates
for (int a = 0; a < maxNum; a++) {
for (int k = a + 1; k < maxNum; k++) {
if (k != a && arrayIn[k] == arrayIn[a]) {
// Quit loop if duplicate found
duplicates = true;
}
}
}
}
System.out.println(duplicates);
}
You should look into a collection called Set. There is a pretty handy function Set.contains that will return true or false depending if a number is already in the Set or not. Something like this would do the trick:
Scanner scanner = new Scanner(System.in);
int maxNum = 8;
Set<Integer> numbers = new HashSet<>();
int digCounter = 1;
//Run while we need numbers
while (digCounter <= maxNum) {
System.out.println("Enter digit " + digCounter + ":");
int tempNumber = scanner.nextInt();
if (numbers.contains(tempNumber)) { //If number is already chosen
System.out.println("Sorry that number has already been added");
} else { //If new number
digCounter++;
numbers.add(tempNumber);
}
}
System.out.println(numbers);
Or if you HAVE to use only arrays you can do something like this:
Scanner scanner = new Scanner(System.in);
int maxNum = 8;
int[] arrayIn = new int[maxNum];
boolean duplicate;
int digCounter = 1;
// Run while we need numbers
while (digCounter <= maxNum) {
//reset duplicate
duplicate = false;
//Get user input
System.out.println("Enter digit " + digCounter + ":");
int temp = scanner.nextInt();
for (int i = 0; i <= digCounter - 2; i++) { //Loop through accepted numbers
if (temp == arrayIn[i]) { //We have found a match
duplicate = true;
break;
}
}
//Check if duplicate
if (duplicate) {
System.out.println("Sorry that number has already been added");
} else {
arrayIn[digCounter - 1] = temp;
digCounter++;
}
}
System.out.println(Arrays.toString(arrayIn));
Hope this helps!
This code will also work if you don't want to use set.
// creating the array
int[] array = new int[10];
// Taking the first number
System.out.println("Please enter your numbers: ");
array[0] = input.nextInt();
// taking other inputs
int count;
for (count = 1; count < array.length; count++) {
int num = input.nextInt();
// Scanning the array for the number
int n;
for (n = 0; n < count; n++) {
while (array[n] == num) { // This will also work if the user
// wants to give duplicate after
// duplicate
System.out.println("You have entered this number before! Add another..");
num = input.nextInt();
n = 0;
}
}
array[count] = num;
}

Using loop counter to print out pattern using 2 variables

Basically I'm trying to make a program to accept an integer between 1 and 10 and also an alphabetic character. It then outputs an appropriate pattern based on this value as a maximum width
For example a user enters an integer of 5 and a letter X the program prints out:
x
xx
xxx
xxxx
xxxxx
I can't seem to get it to print out anything, below is what I've got so far.. any tips are extremely appreciated!
import java.util.*;
public class pattern {
public static void main(String[] args) {
int New1 = 1, Linecounter = 1;
Scanner sc = new Scanner(System.in);
int Number = sc.nextInt();
if (Number >= 1 && Number <= 10) {
Number = New1;
}
else{
System.out.println("Error: Enter a number between 1 and 10");
}
Scanner keyboard = new Scanner(System.in);
char letter = keyboard.next().charAt(0);
for (New1 = 1; New1 <= 10; New1++) {
for (letter = (char) Linecounter; letter <= 10; letter++) {
System.out.print("" +letter+ "");
}
System.out.println();
}}}
First off:
if (Number >= 1 && Number <= 10) {
Number = New1;
}
Sets Number = 1. After this code executes, both Number and New1 are equal to 1. You want something where Number is set to the input. Now the loops need work. You should have something like this:
for (int i = 1; i <= Number; i++) { //1 through Number
for (int j = 1; j <= i; j++) {
System.out.print(letter); //Print letter i times
}
System.out.print("\n"); //New line
}
Is it something like this, you're searching for?
int x = 5;
char letter = 'x';
for (int i = 0; i <= x; i++)
{
for (int j = 0; j < i; j++)
{
System.out.print(letter);
}
System.out.println();
}
The above outputs
x
xx
xxx
xxxx
xxxxx
This seems like homework, so I'll just bring you pseudo code. The idea is to do something like this:
for i in 1..x do
for j in 1..i do
print ('*')
end
println (''
end
(in fact, if you change the println for puts this becomes a valid Ruby script).
Anyway, the key here is: you need as many asterisk as lines entered by the user. As long as you print an asterisk in the inner loop without printing a newline, and call println in your outer loop, you are ok to go.
It is also important that you iterate up to the wanted value in the outer loop, but only up to the New1 variable in the inner loop.
Try this:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Integer: ");
int userInt = scan.nextInt();
System.out.print("Letter: ");
String userLetter = scan.next();
String letter = "";
for (int i = 0; i <= userInt; i++) {
System.out.println(letter);
letter += userLetter;
}
}
This doesn't limit the input to be between 1-10, you can add a little if statement for that.

Sum of all integers defined by user that are divisible by 5

What is not working is the sum part. Its not equaling the right number. Ex: user puts in 25 so the sum should be 75, but the program prints out 50.
My code:
import java.util.Scanner;
public class SumH4
{
public static void main(String[] args)
{
//define data
int x;
int sum;
//scanner is needed
Scanner sc = new Scanner(System.in);
//get user data and initialize variables
System.out.println("Please input a positive whole number.");
x = sc.nextInt();
sc.nextLine();
sc.close();
System.out.println();
sum = 0;
//do computation
for(int a = 0; a < x; a = a + 1)
{
if(a%5==0)
{
sum = sum + a;
}
}
//print results
System.out.println("Sum = " + sum);
}
}
You're not including the number itself that is input by the user. Simply change the for loop to the below so that the input x gets added:
for (int a = 0; a <= x; a = a + 1) {
Change
for(int a = 0; a < x; a = a + 1)
to
for(int a = 0; a <= x; a = a + 1)
At the moment you're not including 25, that only goes upto 24 i.e. a < x means "while a is less than x", then you want "while a is less than OR EQUAL TO x".
Your loop test should be <= (not <), also I suggest you define variables when you need them. Finally, you shouldn't close() a Scanner on System.in because that closes System.in and if you refactor your code you may cause yourself a lot of pain with that. So, I would change your method like
Scanner sc = new Scanner(System.in);
System.out.println("Please input a positive whole number.");
int x = sc.nextInt();
int sum = 0;
for (int a = 0; a <= x; a++) {
if (a % 5 == 0) {
sum += a;
}
}
// print results
System.out.println("Sum = " + sum);

input real numbers in two dimensional array with search for equals and output them

I am a new to Java programing and I want some help please.
This is my question: we input random real numbers and want to record them in the matrix (array of for example [100][100]), with the numbers we input we want to find if there are such numbers entered before successively and if that is so , we output them and the next one at the sceen. Only if the numbers are successively entered before.
Here is my code but most probably is not correct
import java.util.Scanner;
class AddAMatrix {
public static void main(String args[]) {
int m, n, c, i;
Scanner in = new Scanner(System.in);
//input the size of the matrix
System.out.println("Enter the number of rows and columns of matrix");
m = in.nextInt();
n = in.nextInt();
int array[][] = new int[m][n];
System.out.println("Enter number");
//we input random numbers and want to record them in the matrix, with that numbers we input we want to fing if there are
//such a numbers entered before successively and if that is so , we output them and the next one at the sceen . only if the
//numbers are successively entered before.
for (c = in.nextin(); c < m; c++)
if (array[c][].equals(c))
System.out.println("number is repeated" + c);
else System.out.println("enter another number");
for (d = in.nextin(); d < n ;d++ )
array[c][d] = in.nextInt();
if (array[c][].equals(c))
System.out.println("number is repeated" + c);
else System.out.println("enter another number");
if (array[c][d].equals(c, d));
System.out.println("next number of entered matrix is" + array[c][d]);
}
}
Thanks alot . This is working , but it displayed the last number that is input twice. My task is we input lots of numbers for example 300 or 400 numbers and than we input one for example 23 , we take that number and go around in the hall matrix and find equally and than we output it (23) and the previous number if it is in sequence entered and the next one of the matrix only. For example :2,5,7,9,23,32,13,15,19,39,36,.........3,4,9,23 output 9,23,32 This is the catch here. I hope you gonna give me direction that i should work. Thank you in advance .!!!
Try this code:
public static void main(String[] args) {
int m, n, c;
Scanner in= new Scanner(System.in);
//input the size of the matrix
System.out.println("Enter the number of rows and columns of matrix");
m= in.nextInt();
n= in.nextInt();
int array[][]= new int[m][n];
for (c= 0; c < m; c++) {
for (int d= 0; d < n; d++) {
array[c][d]= in.nextInt();
}
}
System.out.println("Enter a number to search for:");
int queryNum= in.nextInt();
//search for it
for (c= 0; c < m; c++) {
for (int d= 0; d < n; d++) {
if (array[c][d] == queryNum) {
if (d == 0) {
if (c - 1 >= 0) {
System.out.println(array[c-1][n-1]);
}
} else {
System.out.println(array[c][d+1]);
}
System.out.println(array[c][d]);
if (d + 1 >= n) {
if (c+1 < n) {
System.out.println(array[c+1][0]);
}
} else {
System.out.println(array[c][d+1]);
}
}
}
}
in.close();
}
Couple of remarks:
in for loops, iterate from 0 index to the length of the array:
for (c= 0; c < m; c++) { and for (int d= 0; d < n; d++) {
you must always close the stream you are using (Scanner in) as I did in the last line

Categories

Resources