In my program, I'm asking the user to input multiple integers to represent the inclusion of chapters in a book like "1 0 1 0 0 1" to represent read chapters 1, 3, 6 or "1 1 1 0 1" to represent 1-3, 5. I' not sure how to process that kind of input into a boolean array and then print the statement.
This is the code I have so far:
import java.util.Scanner;
public class WhichChaptersToRead {
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
int chapters = -1;
String chapterOut = " ";
boolean[] chpSelect = new boolean[15];
boolean rightInput = false;
System.out.println("Enter the chapters to read: ");
while(!rightInput){
if(keyboard.hasNextInt()){
chapters = keyboard.nextInt();
if(chapters > 1 || chapters < 0){
System.out.println("Out of scope of the inclusion or exclusion of chapters");
System.out.println("Enter either 0 or 1");
}else{
chapterOut = formatChapter(chapters, chpSelect);
}
}else{
System.out.println("Wrong type of input.");
System.out.println("Enter integers 0 or 1");
}
}
}
public static String formatChapter(int chapters, boolean[] chpSelect){
}
}
Thanks for all the help.
I reimplemented your logic. Sorry, I couldn't think of an easier way to do it. There are of course, multiple ways to solve this problem.
Step one, ask for the chapters to read.
Step two replace everything that is not zero or one with nothing (that is only allow 0 and 1 - don't validate).
Step three create a boolean[] to store the zero and one values into boolean[] (which is what you asked for).
Step four keep count of how many chapters were assigned so we can use the correct plural for output.
Step five, use a StringJoiner to build the list of output chapters.
Like,
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the chapters to read: ");
String line = keyboard.nextLine();
line = line.replaceAll("[^01]", "");
int selectedCount = 0;
boolean[] selected = new boolean[line.length()];
for (int i = 0; i < line.length(); i++) {
selected[i] = line.charAt(i) == '1';
if (selected[i]) {
selectedCount++;
}
}
if (selectedCount == 0) {
System.out.println("There are no assigned chapters.");
return;
} else if (selectedCount == 1) {
System.out.print("Read chapter ");
} else {
System.out.print("Read chapters ");
}
StringJoiner sj = new StringJoiner(", ");
for (int i = 0; i < selected.length; i++) {
if (selected[i]) {
sj.add(String.valueOf(i + 1));
}
}
System.out.println(sj);
Related
The CEMC is organizing a workshop with an activity involving pairs of students. They decided to assign
partners ahead of time. You need to determine if they did this consistently. That is, whenever A is a partner
of B, then B is also a partner of A, and no one is a partner of themselves.
Input
The input consists of three lines. The first line consists of an integer N (1 < N ≤ 30), which is the number of
students in the class. The second line contains the first names of the N students separated by single
spaces. (Names contain only uppercase or lowercase letters, and no two students have the same first
name). The third line contains the same N names in some order, separated by single spaces.
The positions of the names in the last two lines indicate the assignment of partners: the i-th name on the
second line is the assigned partner of the i-th name on the third line.
Output
The output will be good if the two lists of names are arranged consistently, and bad if the arrangement of
partners is not consistent.
Sample Input 1
4
Ada Alan Grace John
John Grace Alan Ada
Sample Output 1
good
Explanation for Sample 1
Ada and John are partners, and Alan and Grace are partners. This arrangement is consistent.
Sample Input 2
7
Rich Graeme Michelle Sandy Vlado Ron Jacob
Ron Vlado Sandy Michelle Rich Graeme Jacob
Sample Output 2
bad
Explanation for Sample 1
Graeme is partnered with Vlado, but Vlado is partnered with Rich. This is not consistent. It is also
inconsistent because Jacob is partnered with himself.
Here is my work, I wonder why it doesn't work???
import java.util.Scanner;
public class CCCHW4 {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int n = reader.nextInt(); //how many names
String [][] combo = new String [2][n];
double value = 0;
combo [0] [0] = reader.nextLine();
for (int i = 0; i < n; i++) { //input the names
combo [0] [i] = reader.nextLine();
}
combo [1] [0] = reader.nextLine();
for (int j = 0; j < 4; ++j) { //input the names
combo [1] [j] = reader.nextLine();
}
for (int i = 0; i < n++; ++i) {
if ((combo [0][i]).equals(combo [1][i])) { //check if partner with himself/herself
System.out.println(" same " + combo [0][i] + combo [1][i]);
System.exit(0);
}
}
for (int i = 0; i < n; ++i) { //each combo
for (int j = 0; j < n; ++j) { // each column
int determineValue = 0; //determine if any guy partnered with more than one person
if ((combo [0] [i]+combo [1] [i]).equals(combo [0] [j]+combo [1] [j]) || //check, if partner with two person
(combo [0] [i]+combo [1] [i]).equals(combo [1] [j]+combo [0] [j])) {
determineValue += 1;
}
if (determineValue != 2) { //same combo one time, reversed combo one time, so two.
value += 1;
System.out.println("yes2");
}
}
}
if (value == 0) {
System.out.print("good");
} else {
System.out.print("bad");}
}
}
Below is my solution to your homework exercise.
I first ran a few tests by hand and realized that the program output can never be GOOD if there are an odd number of students, so I added a condition that the entered number of students must be an even number.
My algorithm is to use two, separate, one dimensional arrays rather a single, two dimensional array. I loop through the second array (partners in the below code) and for each "partner", I search the first array (students in the code below) for that "partner". If I find the "partner" in the students array then I check whether the pairs are the same. As soon as I fail to find a matching pair, I exit the loop and the program prints BAD.
Note that I only need to search half of the partners array since if I find matches for all the students in the first half of the array, then the second half must all have matches also.
Also note that I added a lot of checks for valid input, including ensuring that the entered number of students is a positive integer, i.e. not a number with a decimal point or a minus sign. I also check that the correct number of names are entered and that each list of names contains only unique names, i.e. the same name cannot appear more than once in a list. The user is asked to re-enter invalid data, repeatedly, until [s]he enters valid data, i.e. a correct number of students and correct lists of names.
Lastly note that I check the validity of the parameters in methods getNames() and getNumberOfStudents(). I feel it is important since I always remind myself that the Ariane 5 rocket failed because the software did not check the validity of method parameters.
import java.util.HashSet;
import java.util.Objects;
import java.util.Scanner;
import java.util.Set;
public class Pairings {
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
int numberOfStudents = getNumberOfStudents(stdin);
String[] students = getNames(stdin, numberOfStudents);
String[] partners = getNames(stdin, numberOfStudents);
int limit = numberOfStudents / 2;
boolean bad = false;
for (int i = 0; i < limit; i++) {
boolean found = false;
for (int j = 0; j < numberOfStudents; j++) {
if (i != j) {
if (students[j].equals(partners[i])) {
if (partners[j].equals(students[i])) {
found = true;
break;
}
}
}
}
if (!found) {
bad = true;
break;
}
}
if (bad) {
System.out.println("BAD");
}
else {
System.out.println("GOOD");
}
}
private static String[] getNames(Scanner stdin, int number) {
if (number <= 0) {
throw new IllegalArgumentException("Not positive: " + number);
}
Objects.requireNonNull(stdin, "Null scanner.");
String[] names = new String[0];
int count = 0;
do {
System.out.printf("Enter %d unique names (separated by single space)%n", number);
String str = stdin.nextLine();
names = str.split("\\s+");
count = names.length;
if (count != number) {
System.out.printf("You entered %d names and not %d%n", count, number);
}
else {
Set<String> nameSet = new HashSet<String>(number);
for (String name : names) {
if (nameSet.contains(name)) {
System.out.printf("%s appears more than once%n", name);
count = 0;
break;
}
else {
nameSet.add(name);
}
}
}
} while (count != number);
return names;
}
private static int getNumberOfStudents(Scanner stdin) {
Objects.requireNonNull(stdin, "Null scanner.");
String str;
int numberOfStudents;
do {
System.out.print("Enter number of students (even number between 2 & 30): ");
str = stdin.nextLine();
try {
numberOfStudents = Integer.parseInt(str);
if (numberOfStudents < 0) {
System.out.printf("%d is a negative number%n", numberOfStudents);
}
else if (numberOfStudents % 2 == 1) {
System.out.printf("%d is not an event number%n", numberOfStudents);
}
}
catch (NumberFormatException xNumFmt) {
System.out.printf("%s is not a whole number%n", str);
numberOfStudents = 1;
}
} while (numberOfStudents % 2 == 1);
return numberOfStudents;
}
}
I have written a program to check if a number is an Unique number.
[A Unique number is a number with no repeating digits and no leading zeros.]
I have written the following code:
Scanner sc=new Scanner(System.in)
System.out.println("Enter the number to be checked: ");
String num=sc.nextLine();
if(num.charAt(0)!='0')
{
Outer:
for(int i=0;i<num.length();i++)
{
for(int j=0;j<num.length();j++)
{
if(num.charAt(i)==num.charAt(j))
{
System.out.println("No, "+num+" is not a Unique number.");
break Outer;
}
}
if(i==num.length()-1)
{
System.out.println("Yes, "+num+" is a Unique number.");
}
}
}
else
System.out.println("No, "+num+" is not a Unique number as it has leading zeros.");
The problem is that is shows any number as NOT Unique, even 12345.
I would like to know where I have gone wrong.
Your code will always find "duplicate" characters when i == j.
You should change the indices of the loop in order not to compare a character to itself:
for(int i=0;i<num.length();i++) {
for(int j=i+1;j<num.length();j++) {
if(num.charAt(i)==num.charAt(j))
...
Besides, you should only output the "...is a Unique number." message after you are done with the outer loop.
Lets assume , length of input number to be 10 and "i" has reached the value of 5 in the for loop.
Now "j" will have the values 0 to 9.
So when "j" is equal to 5 , the if condition becomes true as you are comparing the digit at 5th position with itself (which is always true).
If you add i != j condition , it will fix the issue :-
if(num.charAt(i)==num.charAt(j) and i != j)
Alternatively, you can modify the loop for j to start from i + 1 so
that there are no overlaps.
for(int j=i+1;j<num.length();j++)
The second option is much better as it will reduce the number of comparisons from (n*n)
to (n * (n - 1))/2) , where n is the number of digits in the input number.
A possible solution is to use Stream to convert your String in a Set of char, then if the size of the set is the same as the length of your string, it is unique:
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number to be checked: ");
String num = sc.nextLine();
boolean unique = Stream.of(num.split(""))
.map(s -> new String(s))
.collect(Collectors.toSet()).size() == num.length();
// With "1234" -> print true
// With "12342" -> print false
System.out.println(unique);
You can use below short and handy approach:
String a = "123452";
String[] split = a.split("");
List<String> list = Arrays.asList(a.split(""));
Set<String> set = new HashSet<>(list);
System.out.println("Unique: " + (list.size() == set.size()));
import java.util.*;
public class spnum
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number: ");
String num = sc.next();
int ctr = 0;
boolean isNumUnique = true;
for(int i = 0; i < num.length(); i++)
{
for(int j = 0; j < num.length(); j++)
{
if(num.charAt(i) == num.charAt(j))
{
ctr++;
}
}
if(ctr > 1)
{
isNumUnique = false;
}
ctr = 0;
}
if(isNumUnique == true)
{
System.out.println("Number is a unique number");
}
else
{
System.out.println("Number is not a unique number");
}
}
}
this code would give the right answer
I am writing a game where a user has to input 5 numbers ranging from 1 to 50. These numbers are being saved in the array intPlayersNumbers. If the conditions are not met the user has to enter the numbers again. Why is the array intPlayersNumbers not being overwritten? It is saving only the numbers that were entered for the 1st time.
public class Game {
int chosenNumbers = 5;
int chosenNumber;
String numbers;
int[] raffleArray = new int[chosenNumbers];
public void askForNumbers(){
Scanner in = new Scanner(System.in);
numbers = in.nextLine();
String[] playersNumbers = (numbers.split(" "));
int[] intPlayersNumbers = new int[playersNumbers.length];
for(int a =0; a<playersNumbers.length; a++ ){
intPlayersNumbers[a] = Integer.parseInt(playersNumbers[a]);
}
//checking the numbers
checkTheNumbers(intPlayersNumbers);
}
public int[] checkTheNumbers(int[] intPlayersNumbers){
//if there is 5 numbers
if(intPlayersNumbers.length==5){
//if the numbers are form 1 to 50
for(int i = 0; i<intPlayersNumbers.length; i++){
if(intPlayersNumbers[i]<50 && intPlayersNumbers[i]>0){
continue;
}else{
System.out.println("Please enter 5 nums from 1 to 50.");
askForNumbers();
}
}
}
else{
System.out.println("Please enter 5 numbers");
askForNumbers();
}
return intPlayersNumbers;
}
I think a do-while makes more sense here. Additionally, I think it makes more sense that checkTheNumbers returns a boolean as it performs a validation. The solution below will continuously ask for numbers until checkTheNumbers returns true.
public int[] askForNumbers(){
int[] intPlayersNumbers;
Scanner in = new Scanner(System.in);
do {
System.out.println("Please enter 5 nums from 1 to 50.");
numbers = in.nextLine();
String[] playersNumbers = (numbers.split(" "));
intPlayersNumbers = new int[playersNumbers.length];
for(int a =0; a<playersNumbers.length; a++ ){
intPlayersNumbers[a] = Integer.parseInt(playersNumbers[a]);
}
} while (!checkTheNumbers(intPlayersNumbers));
return intPlayersNumbers;
}
public boolean checkTheNumbers(int[] intPlayersNumbers) {
if(intPlayersNumbers.length==5) {
for(int i = 0; i < intPlayersNumbers.length; i++) {
if (intPlayersNumbers[i] > 50 || intPlayersNumbers[i] <= 0) {
System.out.println("Please enter 5 nums from 1 to 50.");
return false;
}
}
} else{
System.out.println("Please enter 5 numbers");
return false;
}
return true;
}
I think you can easily solve this using recursion. Since the context of your question is not completely clear i did one or two assumptions. If you want a slightly different solution you can use the comments as hints.
public void askForNumbers() {
Scanner in = new Scanner(System.in);
// use the sout before the system.in waits for you first input
System.out.println("Please enter 5 nums from 1 to 50.");
numbers = in.nextLine();
String[] playersNumbers = (numbers.split(" "));
int[] intPlayersNumbers = new int[playersNumbers.length];
// check if the array has lenght 5 directly after the split.
if (intPlayersNumbers.length != 5) { // if the split.length != 5 start over
askForNumbers();
}
else {
for (int a = 0; a < playersNumbers.length; a++) {
int i = Integer.parseInt(playersNumbers[a]); //beware this can cause a numberFormatException !!!
if (i > 0 && i < 51) { // if one of the number is not in range start over.
intPlayersNumbers[a] = i;
}
else {
System.out.printf("%d was not between 0 and 50", i); // print which integer was the culprit
askForNumbers();
return; //return so this method ends here;
}
}
raffleArray = intPlayersNumbers; // or return intPlayersNumbers , you will have to change the return type of the method as well
}
}
I you have any questions about this solution, just leave a comment.
Java code (not Java script). I was asked to create a new integer array with 16 elements.
Only integers between 1 and 7 are to be entered in the array from user (scanner)input.
Only valid user input should be permitted, and any integers entered outside the bounds (i.e. < 1 or > 7 should be excluded and a warning message displayed.
Design a program that will sort the array.
The program should display the contents of the sorted array.
The program should then display the numbers of occurrences of each number chosen by user input
however i have been trying to complete this code step by step and used my knowledge to help me but need help my current code is under I would appreciate if some one is able to edit my code into the above wants.I know it needs to enter the array by user input store and reuse the code to sort the numbers into sort the array.
The result should print out something like this like this
“The numbers entered into the array are:” 1, 2,4,5,7
“The number you chose to search for is” 7
“This occurs” 3 “times in the array”
import java.util.Scanner;
public class test20 {
public static void main (String[] args){
Scanner userInput = new Scanner (System.in);
int [] nums = {1,2,3,4,5,6,7,6,6,2,7,7,1,4,5,6};
int count = 0;
int input = 0;
boolean isNumber = false;
do {
System.out.println ("Enter a number to check in the array");
if (userInput.hasNextInt()){
input = userInput.nextInt();
System.out.println ("The number you chose to search for is " + input);
isNumber = true;
}else {
System.out.println ("Not a proper number");
}
for (int i = 0; i< nums.length; i++){
if (nums [i]==input){
count ++;
}
}
System.out.println("This occurs " + count + " times in the array");
}
while (!(isNumber));
}
private static String count(String string) {
return null;
}
}
import java.util.Scanner;
import java.util.Arrays;
public class test20 {
private static int readNumber(Scanner userInput) {
int nbr;
while (true) {
while(!userInput.hasNextInt()) {
System.out.println("Enter valid integer!");
userInput.next();
}
nbr = userInput.nextInt();
if (nbr >= 1 && nbr <= 7) {
return nbr;
} else {
System.out.println("Enter number in range 1 to 7!");
}
}
}
private static int count(int input, int[] nums) {
int count = 0;
for (int i = 0; i < nums.length; i++){
if (nums[i] == input){
count++;
} else if (nums[i] > input) {
break;
}
}
return count;
}
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
int[] nums = new int[16];
for (int i = 0; i < nums.length; i++) {
nums[i] = readNumber(userInput);
}
Arrays.sort(nums);
System.out.println ("Sorted numbers: " + Arrays.toString(nums));
int input = 0;
while(true) {
System.out.println("Search for a number in array");
input = readNumber(userInput);
System.out.println("The number you chose to search for is " + input);
System.out.println("This occurs " +
count(input, nums) + " times in the array");
}
}
}
Because the array is sorted, I break the loop if an element larger than the one we're looking for is found; if we encounter a larger one then no other matches can be found in the rest of the array.
I have a task with checking ID number and I must check if this ID has 11 characters, if those characters are digits and I must check control number. Number is correct when this equation is correct:
ID = abcdefghijk
(1*a+3*b+7*c+9*d+1*e+3*f+7*g+9*h+1*i+3*j+1*k) % 10 = 0
Sample correct ID is: 49040501580
And here is my program. I don't know how to check if ID is digit and why it isn't correct. Anyone help? XD
Thank you in advance :3
import java.util.*;
public class wat {
public static void main(String[] args) {
char[] weights = {1, 3, 7, 9, 1, 3, 7, 9, 1, 3, 1};
System.out.print("Enter next digits your ID number: ");
Scanner keyboard = new Scanner(System.in);
String number = keyboard.nextLine();
char[] ofm = number.toCharArray();
Character[] id = new Character[ofm.length];
for (int i = 0; i < ofm.length; i++) {
id[i] = ofm[i];
System.out.print(id[i] + " ");
int length = id.length;
if (length == 11) {
System.out.println("This ID number has 11 digits");
System.out.println("Checking of the control number");
int amount = 0;
amount = id[i] * weights[i];
System.out.println(amount);
int result = 0;
result = amount % 10;
if (result == 0) {
System.out.println("ID number is correct");
} else {
System.out.println("ID number is not correct");
break;
}
} else {
System.out.print("This ID number hasn't 11 digits.");
break;
}
}
}
}
Sample output
With a minimal number of changes to your original code, I believe this is what you need.
import java.util.*;
public class wat {
public static void main(String[] args) {
char[] weights = {1,3,7,9,1,3,7,9,1,3,1};
System.out.print("Enter next digits your ID number: ");
Scanner keyboard = new Scanner(System.in);
String number = keyboard.nextLine();
char[] ofm=number.toCharArray();
Character[] id=new Character[ofm.length];
if (ofm.length == 11) {
System.out.println("This ID number has 11 characters");
int amount = 0;
for (int i = 0; i < ofm.length; i++) {
id[i]=ofm[i];
System.out.print(id[i]+" ");
int length = id.length;
if (isDigit(id[i])) {
amount = id[i]*weights[i];
} else {
System.out.println("character is not a digit");
break;
}
}
} else {
System.out.print("This ID number hasn't 11 digits.");
return;
}
System.out.println("Checking of the control number");
System.out.println(amount);
int result =0;
result = amount % 10;
if (result == 0) {
System.out.println("ID number is correct");
} else {
System.out.println("ID number is not correct");
}
}
}
As you can see, we're now verifying the string length before the loop starts.
Then we're checking each character is a digit one by one and quitting with a new error message if one of them is not. You'll need to provide the isDigit function yourself (plenty to choose from on StackOverflow!).
We're accumulating the digit values multiplied by the weight into the amount variable, with a new value being added each time the loop iterates.
Finally we verify the result is correct after the loop has finished and all 11 characters have been processed.
NOTE: I don't normally work in Java so I'm not entirely sure if you can get the digit value out of a Character type object (to multiply it with the weight) like this. You might find that you are getting ASCII code values, or something else entirely. If this happens, you'll need to convert 'weights' into an array of integers, and extract the actual numeric value from the Character before multiplying them together.