Top Banner
Neural Language Models are Effective Plagiarists Stella Biderman 1,2 and Edward Raff 1 1 Booz Allen Hamilton 2 EleutherAI {last first}@bah.com Abstract As artificial intelligence (AI) technologies become increasingly powerful and prominent in society, their misuse is a growing concern. In educational settings, AI technologies could be used by students to cheat on assignments and exams. In this paper we explore whether transformers can be used to solve introductory level programming assignments while bypassing commonly used AI tools to de- tect plagiarism. We find that a student using GPT-J [Wang and Komatsuzaki, 2021] can complete in- troductory level programming assignments without triggering suspicion from MOSS [Aiken, 2000], a widely used plagiarism detection tool. This holds despite the fact that GPT-J was not trained on the problems in question and is not provided with any examples to work from. We further find that the code written by GPT-J is diverse in structure, lack- ing any particular tells that future plagiarism detec- tion techniques may use to try to identify algorith- mically generated code. We conclude with a dis- cussion of the ethical and educational implications of large language models and directions for future research. 1 Introduction The COVID-19 pandemic has lead to a boom in online edu- cation [Affouneh et al., 2020] due to the health risks of in- person teaching [Juliana et al., 2020]. This has in turn lead to a growing market for tools that claim to ensure academic integrity in online courses [Yasid et al., 2020]. With the in- creased attention to and wider use of these tools, it becomes even more important to have thorough understanding of if, and how, such tools may be subverted by students. While there is a substantial literature on plagiarism techniques and detection strategies, this literature has not yet engaged with the recent breakthroughs in transformers research. Recent work in the transformers literature has investigated the ability of large language models to solve college-level homework assignments in a variety of domains including cal- culus [Drori et al., 2021], linear algebra [Drori and Verma, 2021], astronomy [Shporer et al., 2021], machine learning [Tran et al., 2021] but has not engaged with the issues and implications of real-world application of their results. In this paper we carry out the first investigation of the ability of a transformer-based language model to gener- ate de novo completions of homework assignments in a college-level course while bypassing plagiarism detection techniques. For our investigation we choose to use Measure of Software Similarity (MOSS) [Aiken, 2000], a popular tool used to monitor academic integrity in universities worldwide [Bowyer and Hall, 1999; Lancaster and Culwin, 2004; Luke et al., 2014; Sheahen and Joyner, 2016], to identify likely pla- giarisms. We choose to study MOSS because it is an open- source model representing the state-of-the-art for plagiarism detection and its design has been widely copied by commer- cial tools [Devore-McDonald and Berger, 2020]. We note the licensing of commercial tools prevent us from studying them directly. We find that the GPT-J model [Wang and Ko- matsuzaki, 2021] is capable of fooling MOSS [Aiken, 2000] with a high degree of reliability, that little human editing is re- quired to produce assignments that would receive full marks in a course, and that GPT-J solutions have sufficient diversity to avoid easy detection. Our study raises serious questions about the efficacy and ethicality of using MOSS-based tools as a sole or primary identifier of academic plagiarism 1 . The rest of our paper is organized as follows. First we will review the related work, and how prior language models have not provided satisfying answers to the plagiarism risk of lan- guage models in section 2. Next we will review our method- ology in section 3, where we provide a realistic approach to how a student may use GPT-J to plagiarize an assignment, and what (simple) prompt engineering is required to produce the results. section 4 performs a detailed analysis of the re- sults, cataloging the types of errors made by GPT-J, measures the similarity and detection risk of multiple plagiarism strate- gies, and shows how GPT-J is challenging to detect. Further detailed analysis of individual assignments is in the appendix. Due to the nature of this work, we discuss the ethics and why we believe the benefits outweigh their risks in section 5, not- ing that the limits of GPT-J’s abilities prevent it from allow- ing a student to proceed through an entire degree, and other 1 We note that this work is investigating an aspect that none of these tools have never been designed for, and should not be seen as a failure in design due to the novelty of the issue. arXiv:2201.07406v1 [cs.CL] 19 Jan 2022
94

arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

Mar 15, 2023

Download

Documents

Khang Minh
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

Neural Language Models are Effective Plagiarists

Stella Biderman1,2 and Edward Raff11Booz Allen Hamilton

2EleutherAI{last first}@bah.com

Abstract

As artificial intelligence (AI) technologies becomeincreasingly powerful and prominent in society,their misuse is a growing concern. In educationalsettings, AI technologies could be used by studentsto cheat on assignments and exams. In this paperwe explore whether transformers can be used tosolve introductory level programming assignmentswhile bypassing commonly used AI tools to de-tect plagiarism. We find that a student using GPT-J[Wang and Komatsuzaki, 2021] can complete in-troductory level programming assignments withouttriggering suspicion from MOSS [Aiken, 2000], awidely used plagiarism detection tool. This holdsdespite the fact that GPT-J was not trained on theproblems in question and is not provided with anyexamples to work from. We further find that thecode written by GPT-J is diverse in structure, lack-ing any particular tells that future plagiarism detec-tion techniques may use to try to identify algorith-mically generated code. We conclude with a dis-cussion of the ethical and educational implicationsof large language models and directions for futureresearch.

1 IntroductionThe COVID-19 pandemic has lead to a boom in online edu-cation [Affouneh et al., 2020] due to the health risks of in-person teaching [Juliana et al., 2020]. This has in turn leadto a growing market for tools that claim to ensure academicintegrity in online courses [Yasid et al., 2020]. With the in-creased attention to and wider use of these tools, it becomeseven more important to have thorough understanding of if,and how, such tools may be subverted by students. Whilethere is a substantial literature on plagiarism techniques anddetection strategies, this literature has not yet engaged withthe recent breakthroughs in transformers research.

Recent work in the transformers literature has investigatedthe ability of large language models to solve college-levelhomework assignments in a variety of domains including cal-culus [Drori et al., 2021], linear algebra [Drori and Verma,2021], astronomy [Shporer et al., 2021], machine learning

[Tran et al., 2021] but has not engaged with the issues andimplications of real-world application of their results.

In this paper we carry out the first investigation of theability of a transformer-based language model to gener-ate de novo completions of homework assignments in acollege-level course while bypassing plagiarism detectiontechniques. For our investigation we choose to use Measureof Software Similarity (MOSS) [Aiken, 2000], a popular toolused to monitor academic integrity in universities worldwide[Bowyer and Hall, 1999; Lancaster and Culwin, 2004; Lukeet al., 2014; Sheahen and Joyner, 2016], to identify likely pla-giarisms. We choose to study MOSS because it is an open-source model representing the state-of-the-art for plagiarismdetection and its design has been widely copied by commer-cial tools [Devore-McDonald and Berger, 2020]. We notethe licensing of commercial tools prevent us from studyingthem directly. We find that the GPT-J model [Wang and Ko-matsuzaki, 2021] is capable of fooling MOSS [Aiken, 2000]with a high degree of reliability, that little human editing is re-quired to produce assignments that would receive full marksin a course, and that GPT-J solutions have sufficient diversityto avoid easy detection. Our study raises serious questionsabout the efficacy and ethicality of using MOSS-based toolsas a sole or primary identifier of academic plagiarism1.

The rest of our paper is organized as follows. First we willreview the related work, and how prior language models havenot provided satisfying answers to the plagiarism risk of lan-guage models in section 2. Next we will review our method-ology in section 3, where we provide a realistic approach tohow a student may use GPT-J to plagiarize an assignment,and what (simple) prompt engineering is required to producethe results. section 4 performs a detailed analysis of the re-sults, cataloging the types of errors made by GPT-J, measuresthe similarity and detection risk of multiple plagiarism strate-gies, and shows how GPT-J is challenging to detect. Furtherdetailed analysis of individual assignments is in the appendix.Due to the nature of this work, we discuss the ethics and whywe believe the benefits outweigh their risks in section 5, not-ing that the limits of GPT-J’s abilities prevent it from allow-ing a student to proceed through an entire degree, and other

1We note that this work is investigating an aspect that none ofthese tools have never been designed for, and should not be seen asa failure in design due to the novelty of the issue.

arX

iv:2

201.

0740

6v1

[cs

.CL

] 1

9 Ja

n 20

22

Page 2: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

teaching touch points like exams and quizzes provide a reme-diation for the informed instructor. Finally we conclude witha discussion and related Human-Computer Interaction (HCI)problems in section 6.

2 Related Work

Very recent concurrent works have looked at college assign-ment generation [Drori et al., 2021; Shporer et al., 2021; Tranet al., 2021] as a means of understanding what language mod-els like GPT-3 [Brown et al., 2020] and Codex [Chen et al.,2021a] learn. Not only are these models an order of magni-tude larger than GPT-J, the study setups do not evaluate a real-istic scenario for plagiarism. Significant coding, prompt engi-neering, and infrastructure is required for the experiments thata novice student would not have or be able to replicate (indeedif they could, there is no question they could complete theseintroductory assignments without assistance). Additionally ,Our work instead focus on a realistic threat model to deter-mine that there is a real risk that needs further study, thoughwe suspect many of the best solutions would be non-technical(See section 5).

Previous research has used language models to detect tex-tual plagiarism with modest success in a laboratory setting[Chong et al., 2010; Foltynek et al., 2020]. While we wereunable to find papers that explicitly seek to use language mod-els for plagiarism, there is a wealth of research both on para-phrasing [Narayan et al., 2018; Liu and Lapata, 2019; Li etal., 2020] and on adversarial examples against textual models[Krishna et al., 2020; He et al., 2021; Darmetko, 2021], bothof which can easily be applied to plagiarism even if the pa-pers do not say so explicitly. A key difference in these priorworks is that they all require an initial valid solution that be-comes plagiarized, i.e., modified to avoid detection. In ourstudy we show that a modern neural language models canproduce valid, or valid with little additional work, solutionsto novel questions that have no given solution. The user isthen plagiarizing the model itself, rather than a human being.To the best of our knowledge this is the first demonstration ofsuch an ability, and poses new concerns on how to avoid suchpotential plagiarism.

There is comparatively less research on AI-based code pla-giarism, likely because AI techniques for generating codehave only recently become prominent [Wang and Komat-suzaki, 2021; Hendrycks et al., 2021; Chen et al., 2021a;Austin et al., 2021; Mukherjee et al., 2021]. Dawson et al.[2020] is the most relevant that we are aware of, who use ma-chine learning to compare solutions of prior submissions ofa student to detect “contract” plagiarism, where assignmentsare outsourced to third parties, which results in inconsistentcoding style of the student’s submissions. While Dawson etal. [2020] found promising evidence of machine learning be-ing helpful in this case, there is also risk of neural style trans-fer [Hu et al., 2020] being leveraged to combat this. Theresulting adversarial game is beyond the scope of this work,but the need for greater study is reinforced by our findings.

3 MethodologyTo evaluate the ability of GPT-J to fool MOSS, we comparehow MOSS views code generated by GPT-J with a dataset ofplagiarized introductory coding assignments created by Kar-nalim et al. [2019]. The dataset contains seven programmingexercises suitable for an introduction to programming coursewith accompanying solutions written in Java. For each solu-tion (henceforth referred to as “original solution”), TeachingAssistants (TAs) who have experience in introductory com-puter science courses composed independent solutions to theexercise (henceforth “non-plagiarisms”). These representstwo distinct sources of valid solutions to the exercise, withone that may be ’altered’ to produce plagiarisms, and theother that can be used to measure similarity (i.e., similaritybetween source and plagiarized variant, and between plagia-rized variant and an independent solution).

Around fifty plagiarisms of the original solutions are made,designed using techniques from and classified according to,the taxonomy presented in Faidhi and Robinson [1987]. Fol-lowing [Karnalim et al., 2019], we refer to these plagia-rism categories as “levels” with “level 1” being the simplestand “level 6” being the most sophisticated form of plagia-rism. While the exact number of plagiarized solutions variesslightly, every exercise has between seven and nine examplesof plagiarisms per category and examples of plagiarisms fromall seven categories in the taxonomy. In total, each program-ming exercise is paired with 15 non-plagiarisms and between49 and 54 plagiarisms of varying types.

A comparison of MOSS scores by plagiarism level isshown in Figure 1, with a higher similarity score indicatingthat an assignment is more likely to be plagiarized. Faidhiand Robinson [1987] and Karnalim et al. [2019] find thatlevel 1 through 3 plagiarisms can be easily detected by humangraders, that level 3 plagiarisms are borderline, and that level6 plagiarisms can consistently fool human graders. Theseclaims are consistent with the fact that level 4, level 5, andlevel 6 plagiarisms obtain similar MOSS scores to the gen-uinely not-plagiarized solutions.

We prompt GPT-J with the descriptions of the exercisesprovided in [Karnalim et al., 2019] and attempt to use it toproduce code that compiles and correctly solves the problem.To evaluate our success, we have three major criteria:

1. We wish to obtain code that correctly solves the exercise.2. We wish to obtain code that is not flagged by MOSS as

suspiciously similar to the original code.3. We wish to minimize the amount of human modification

necessary to obtain code from raw GPT-J output.As we will show later in section 4, these desiderata can be

obtained with relative ease despite GPT-J not knowing aboutMOSS, and can generally be completed with just a queryingGPT-J multiple times.

3.1 Coding Exercises and PreprocessingThe problems that we use to prompt GPT-J are shown below,organized loosely in increasing order of difficulty. These de-scriptions are taken verbatim from [Karnalim et al., 2019],and reflect the formatting and stylistic choices made by theauthors.

Page 2

Page 3: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

Figure 1: A breakdown of MOSS scores for completions of exercisesfrom Karnalim et al. [2019] by how they were generated. “Original”denotes the original solutions, “LN” denotes Level N plagiarism,and “non” denotes non-plagiarisms.

1. Write a program that prints “Welcome to Java” fivetimes.

2. Write a program that accepts the radius & length of acylinder and prints the area & volume of that cylinder.All inputs and outputs are real numbers.

3. Write a program that accepts the weight (as a real num-ber representing pound) and height (as two real num-bers representing feet and inches respectively) of a per-son. Upon accepting input, the program will show thatperson’s BMI (real number) and a piece of informationstating whether the BMI is categorised as underweight,normal, overweight, or obese.A person is underweight if BMI < 18.5; normal if18.5 ≤ BMI < 25; overweight if 25 ≤ BMI < 35; orobese if BMI ≥ 35.Height = feet ∗ 12 + inchesBMI = weight ∗ 0.45359237/(height ∗ 0.0254)2

4. Write a program that shows a conversion table frommiles to kilometers where one mile is equivalent to 1.609kilometers. The table should display the first ten posi-tive numbers as miles and pair them with their respectivekilometer representation.

5. Write a program that accepts an integer and displays thatinteger with its digits shown in reverse. You should cre-ate and use a method void reverse(int number) whichwill show the reversed-digit form of the parameterisednumber.

6. Write a program that accepts 10 integers and shows themin reversed order.

7. Write a program that accepts a 4×4 matrix of real num-bers and prints the total of all numbers placed on theleading diagonal of the matrix. You should create anduse a method double sumMajorDiagonal(double[][] m)which will return the total of all numbers placed on theleading diagonal of the parameterised matrix.

As GPT-J was trained on mathematics and computer sci-ence text that is written in LATEX [Gao et al., 2020], we chooseto provide the model with an input prompt written in LATEX.This has the notable advantage of allowing us to provide aprompt that is identical to what is presented in Karnalim etal. [2019], and is hopefully reflective of how a real studentmight opt to type a homework assignment into a languagemodel.

There is a substantial literature on “prompt programming,”or crafting inputs to language models in ways that help themodel perform better at downstream tasks [Reynolds and Mc-Donell, 2021; Li and Liang, 2021; Chen et al., 2021b] (for asurvey, see [Liu et al., 2021]). Although we expect studentsto try varying phrasing and framing to elicit improved results,we leave the impact of this to future work that delves into animportant computer-human interaction problem beyond thescope of this article. The only adjustment that we make to theexercises presented in Karnalim et al. [2019] is that we addthe word “Java,” to make each exercise begin “Write a Javaprogram...” A cursory exploration of GPT-J without this mod-ification shows that it is not inclined to write in Java withoutspecific prompting, often giving results in Python and C in-stead. Once the prompts are modified to include the word“Java,” all responses are either natural text, LATEX, or Java ex-cept for some of the responses to exercise 4 which were inC.

Prompt Not code C Java Python

“Wrote a program that. . . ” 25 6 4 0“Write a C program that. . . ” 22 12 1 0“Write a Java program that. . . ” 19 3 13 0“Write a Python program that. . . ” 22 1 0 12

Figure 2: Natural language prompts are pretty hit-or-miss when itcomes to getting GPT-J to produce an actual program, but it is re-sponsive to naming specific programming languages. Table showsthe results of 5 generations for each of the 7 programming tasks

3.2 GenerationWe use the free GPT-J API offered by EleutherAI2. The APIoffers two options for tuning generations called “top-p” and“temperature.” For the purposes of this paper we stick withthe default values of 0.9 and 0.8 respectively, and leave ex-ploring the influence of these parameters for future work. TheAPI also provides a “send results as prompt” button, whichconcatenates the prompt with the generated response and re-submits the combined string as a new prompt and allows themodel to continue from where it left off. This is especiallyhelpful for circumstances where the model generation haltsbefore completing a piece of code. Although autoregressivelanguage models can generate indefinitely, for cost reasonsthe online demo has a limited number of tokens that it willreturn. For this paper, we resend the results as a prompt for anew generation until we appear to reach a complete programor until five consecutive generations yield no code, whicheverhappens first.

2https://6b.eleuther.ai/

Page 3

Page 4: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

3.3 Post-Processing and Human EditingOne particularly noteworthy aspect of generating code is thata student using GPT-J to cheat most likely is able to testwhether or not the resulting code solves the problem, evenat low skill levels, since compiling and running a programare first steps in curricula. Additionally, they are able to re-ceive hints as to why their code doesn’t work by running itand examining the errors that are printed out. The nature of aconcrete and objective output allows unambiguous feedbackto the student before receiving a grade.

In this context, to produce a more realistic threat model, weallow the human using the AI to cheat to modify the outputslightly. Specifically, we add whatever imports are necessary3

and lightly edit the code by correcting simple syntax errors,off-by-one errors, and removing “obvious” mistakes. Fixingthese types of errors is likely to occur due to the objectivenature of grading and assignment completion, and in doingso we document and categorize the types of errors we observeacross our results.

While what is considered obvious varies from person toperson, we have sought to take a very conservative approachin the hopes of understating GPT-J’s capabilities and repre-senting a realistic use-case by a minimally knowledgeablestudent. All generated text and human-edited final solutionscan be found in the supplemental materials.

We note that this is in contrast to using GPT-J to cheat ona creative writing assignment, write mathematics proofs, orsolve science homework assignments where a students’ abil-ity to evaluate and improve the quality of the generated writ-ing is connected to their subjective ability to complete thehomework assignment without assistance, and to understandthe preferred or desired intent and style of the instructor. Thefeedback on correctness does not occur until after it is too lateto “refine” the plagiarism. For this reason we do not explorethis more subjective-to-evaluate area of plagiarism.

4 ResultsIn this section we give a high level overview of the results ofour experiments.

GPT-J generates correct solutions with minimal interven-tion For six of the seven programming exercises, GPT-J canproduce a complete solution that requires no editing. In mostcases GPT-J makes minor mistakes that need correction by ahuman, but which overwhelmingly do not require any knowl-edge of computer programming besides the ability to run codeand search the internet for the error code reported by the com-piler.

Memorization does not explain GPT-J’s performanceTransformers, like all neural networks, exhibit a behaviorcommonly referred to as “memorization” where long pas-sages of the training data are regurgitated word-for-word[Carlini et al., 2019; Feldman, 2020; Carlini et al., 2021].We explore the possibility that the exercises and their solu-tions are memorized by searching through the training datain GPT-J for exact matches of 20 tokens or more. We find

3missing imports are reported by the Java compiler and can beeasily found via searching the web

Problem Number

Errors 1 2 3 4 5 6 7 Tot.

No Errors 2 0 2 0 1 4 2 11Syntax Error 1 6 3 0 0 0 0 10Off by One Error 0 0 0 0 0 1 0 1Misc. 5 0 3 0 0 3 1 12Total Correct 8 6 5 0 1 8 3 31

Table 1: Minor errors made by GPT-J in problems that were ulti-mately judged to be “correct.” Note that the columns do not add upto “Total Correct” because some solutions have multiple errors.

Problem Number

Correctness 1 2 3 4 5 6 7 Tot.

Correct 8 6 5 0 1 8 3 31Partial Completion 1 1 0 1 0 2 0 5Wrong 0 0 1 1 4 3 0 9Actually in C 0 0 0 2 1 1 0 4Not Code 6 8 9 11 9 1 12 56

Table 2: Breakdown of the correctness of GPT-J’s completions. Asolution is judged as “Partially Correct” if it misses a significantcomponent of the problem, but the parts of the problem that it doessolve are solved correctly. These are likely suitable to earn partialcredit on an assignment.

that neither the exercises from Karnalim et al. [2019] northe code produced by GPT-J in response to the prompts canbe found in the training data. While GPT-J was trained onarXiv preprints [Gao et al., 2020], it appears that Karnalimet al. [2019] avoids being in the training data by having theirpreprint posted on the University of Warwick website ratherthan arXiv. Crucially, this means that generating novel ques-tions is not an effective way for professors to prevent theirstudents from using GPT-J to cheat.

GPT-J does not register as plagiarizing by MOSS Out ofthe correct completions, none of the code generated by GPT-Jstood out as potential plagiarisms according to MOSS. GPT-J’s exercise completions rated similarly to the non-plagiarismand to the plagiarisms created using the most advanced tech-niques in our dataset, as shown in Table 3 and Figure 3.

Ex. Original L1 L2 L3 L4 L5 L6 Non GPT-J

1 1.0 1.000 1.000 0.926 0.664 0.427 0.357 0.512 0.6912 1.0 0.995 0.836 0.832 0.605 0.657 0.652 0.811 0.4923 1.0 0.996 0.874 0.874 0.768 0.748 0.653 0.872 0.5734 1.0 0.975 0.917 0.839 0.746 0.728 0.689 0.439 —5 1.0 0.964 0.588 0.635 0.602 0.519 0.459 0.440 0.4406 1.0 0.930 0.890 0.807 0.650 0.562 0.462 0.644 0.2667 1.0 0.977 0.881 0.838 0.811 0.746 0.726 0.798 0.669

Table 3: MOSS scores for completions of exercises by how theywere generated and by exercise. The lowest score for each exercise,and all scores within 10% of that score, are bolded.

There is no easy way to detect GPT-J’s output AlthoughMOSS is unable to detect GPT-J’s plagiarisms when they are

Page 4

Page 5: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

Figure 3: A breakdown of MOSS scores for completions of exercisesby how they were generated. This plot is the same as Figure 1,except it adds an “AI” column denoting GPT-J’s code. A higherscore indicates more code similarity with the reference solution.

mixed in with genuine solutions, one might think that havingexamples of GPT-J’s solutions would allow an instructor todetect other outputs from GPT-J. We find that this is not thecase in two senses: MOSS does not judge GPT-J’s solutionsto be notably similar to each other, and a clustering algorithmtrained to distinguish between GPT-J’s solutions and thosein the dataset fails to do so. While this does not rule outthe possibility of more advanced techniques detecting GPT-J’s fingerprints, the techniques currently used for plagiarismdetection in practice fail to do so.

To further demonstrate the syntactic diversity of the GPT-Jsolutions, we perform 2D embeddings of the MOSS scoresusing the Isomap algorithm. Isomap is preferred in this in-stance because it: 1) Embeds the data based on a geodesicassumption of the manifold that we know to be true due tothe multiple submissions per homework and nature of sourceto plagiarized copy. 2) Preserves global and local relation-ships in the embedding, which we care about to understandthe degree of separation between solutions (as measured byMOSS). Other popular approaches such as t-SNE and UMAPlack this second property that we desire, and make interpre-tation of the results difficult.

The Isoamp results are found in Figure 4, where we see theGPT-J solutions exist predominantly in their own indepen-dent area, or near other original solutions (green). Each shapeindicates a different homework question the solution is de-signed for, and the overall distribution reinforces the geodesicassumption (same assignment solutions cluster, plagiarismscluster near their source (black), and better plagiarisms (yel-low) are further away than ineffective ones (red)4.

We note that the disperse of the GPT-J solutions in “theirown space” does not imply that they would be easy to detect.

4Yellow plagiarisms are “level 6” in the taxonomy of Faidhi andRobinson [1987]. Both our experiments and those of Faidhi andRobinson [1987] indicate that level 6 plagiarisms are effectively in-distinguishable from non-plagiarized assignment completions.

(a) Isomap with n = 10 neighbors

(b) Isomap with n = 100 neighbors

Figure 4: Isomap embedding of the original solutions (black), pla-giarized variants (red and yellow, where yellow are sophisticatedones that evade MOSS), along with GPT-J produced solutions (blue)and independent implementations (green). The blue data points be-ing interspersed with yellow, green, and far-away spaces shows thatGPT-J is not easily detected by MOSS.

The green independent solutions are not a complete samplingof the space, and often exist in similar areas, so the validity ofa model built from this data, which represents one course, isunlikely to generalize due to strong violation of I.I.D. natureof the data (e.g., everyone had the same professor, TAs, studygroups, etc.). We are aware of no longitudinal data of plagia-rized and independent assignments, but our results suffice toshow that this is a novel problem with no trivial solutions.

5 Ethics and Broader ImpactsThis paper details a free and easily accessible way to carryout academic misconduct without being detected using com-mon approaches. While we anticipate that the results of thispaper will be concerning to many, it is important to recog-nize that these flaws and risks exist. In particular, we do not

Page 5

Page 6: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

have evidence that GPT-J is sufficient for prolonged plagia-rism into more advanced courses, which limits the degree ofimpact (students who reach such courses are likely to fail outor revert to some other form of cheating), and provides nomeans for students to circumvent in-person quizzes, exams,and other assignments that may be used to determine possiblecheaters (e.g., in our experience we follow up and carefullyreview students who have high grades in one aspect of thecourse and low in the other. Both to identify potential mis-conduct, but also students who may have special needs thathave not been satisfied).

We believe these additional factors modulate the risk ofpublishing this research, and the value in studying it is ul-timately beneficial. Indeed the use of the publicly availableand inspectable GPT-J was a requirement for us to confirmthat the generated solutions are novel and not memorized con-tent regurgitated. Further remediation of risk may indeed bepossible by incorporating GPT-J into a modernized curricu-lum. For example, one could envision a course assignmentto generate multiple solutions using GPT-J and have studentsrank them based on code readability, identify / describe typesof errors produced, and other code review/debugging tasks.This would enable growth in skill, and can be used to estab-lish boundaries of when and how GPT-J (or future variants)should be used in an academic context. Ultimately this is asignificant item for future work.

6 Discussion & ConclusionWhile our results present a promising (from a research per-spective, see aforementioned ethics section) analysis of theuse of GPT-J to plagiarize coding assignments, there are stillsignificant limitations and important avenues for future work.Importantly many aspects of our work’s success pose longterm challenges and new research questions.

6.1 What Does it Mean for MOSS to “Work”?In this paper we speak of MOSS as a tool for detecting pla-giarism because our focus is on the use of text similarity anal-ysis to detect cheating in academic environments. However,while this is the intended use of MOSS, it is not the only one.As noted previously there are many tools that appear to besuitable for use to detect plagiarism but which are primarilymarketed for other purposes. In future work we intended toexamine how the intended application is explicitly and im-plicitly embedded in the functionality of document similaritydetectors [Johnson, 2022; Birhane et al., 2021], and incorpo-rate analysis of what it means for such a device to be judgedas “working” in its planned application context.

6.2 Plagiarism in Human-AI SystemsIn this paper we consider the example of a student with mini-mal knowledge of computer programming. We allow them tomake minimal edits, but the user is not modeled as perform-ing significant intellectual work. Recent research on human-AI co-creative systems has shown that a human working to-gether with an AI can solve problems that neither can solveindividually.

6.3 Technical LimitationsOur study has several technical limitations, most notably asmall number of GPT-J generations and a lack of experimen-tation with prompt programming. Future more extensive ex-periments with GPT-J may reveal a more complete picturethan what we find.

Despite their popularity in Natural Language Processing,there has been very little work on transformers from a human-computer interaction point of view. In particular we wereunable to identify any literature investigating how people goabout using and interacting with language models, and con-sequentially need to base some of our experimental method-ology on conjecture and common sense. We hope that re-search into how people use transformers will empower fu-ture researchers to iterate upon our experimental design withmore realistic assumptions about student behavior and modelusage.

AcknowledgmentsWe would like to thank Leo Gao, Maya Fuches, and LariaReynolds for their feedback on the paper.

ReferencesSaida Affouneh, Soheil Salha, and Zuheir N Khlaif. Design-

ing quality e-learning environments for emergency remoteteaching in coronavirus crisis. Interdisciplinary Journalof Virtual Learning in Medical Sciences, 11(2):135–137,2020.

Alex Aiken. Moss (measure of software similarity) plagia-rism detection system. http://www. cs. berkeley. edu/moss/,2000.

Jacob Austin, Augustus Odena, Maxwell Nye, MaartenBosma, Henryk Michalewski, David Dohan, Ellen Jiang,Carrie Cai, Michael Terry, Quoc V. Le, and Charles Sut-ton. Program synthesis with large language models. arXivpreprint arXiv:2108.07732, 2021.

Abeba Birhane, Pratyusha Kalluri, Dallas Card, WilliamAgnew, Ravit Dotan, and Michelle Bao. The valuesencoded in machine learning research. arXiv preprintarXiv:2106.15590, 2021.

Kevin W Bowyer and Lawrence O Hall. Experience usingMOSS to detect cheating on programming assignments.In FIE’99 Frontiers in Education. 29th Annual Frontiersin Education Conference. Designing the Future of Sci-ence and Engineering Education. Conference Proceedings(IEEE Cat. No. 99CH37011, volume 3, pages 13B3–18.IEEE, 1999.

Tom Brown, Benjamin Mann, Nick Ryder, Melanie Sub-biah, Jared D Kaplan, Prafulla Dhariwal, Arvind Neelakan-tan, Pranav Shyam, Girish Sastry, Amanda Askell, Sand-hini Agarwal, Ariel Herbert-Voss, Gretchen Krueger, TomHenighan, Rewon Child, Aditya Ramesh, Daniel Ziegler,Jeffrey Wu, Clemens Winter, Chris Hesse, Mark Chen,Eric Sigler, Mateusz Litwin, Scott Gray, Benjamin Chess,Jack Clark, Christopher Berner, Sam McCandlish, AlecRadford, Ilya Sutskever, and Dario Amodei. Language

Page 6

Page 7: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

models are few-shot learners. In H. Larochelle, M. Ran-zato, R. Hadsell, M. F. Balcan, and H. Lin, editors, Ad-vances in Neural Information Processing Systems, vol-ume 33, pages 1877–1901. Curran Associates, Inc., 2020.

Nicholas Carlini, Chang Liu, Ulfar Erlingsson, Jernej Kos,and Dawn Song. The secret sharer: Evaluating and test-ing unintended memorization in neural networks. In 28th{USENIX} Security Symposium ({USENIX} Security 19),pages 267–284, 2019.

Nicholas Carlini, Florian Tramer, Eric Wallace, MatthewJagielski, Ariel Herbert-Voss, Katherine Lee, AdamRoberts, Tom Brown, Dawn Song, Ulfar Erlingsson, AlinaOprea, and Colin Raffel. Extracting training data fromlarge language models. In 30th {USENIX} Security Sym-posium ({USENIX} Security 21), pages 2633–2650, 2021.

Mark Chen, Jerry Tworek, Heewoo Jun, Qiming Yuan, Hen-rique Ponde, Jared Kaplan, Harrison Edwards, Yura Burda,Nicholas Joseph, Greg Brockman, Alex Ray, Raul Puri,Gretchen Krueger, Michael Petrov, Heidy Khlaaf, GirishSastry, Pamela Mishkin, Brooke Chan, Scott Gray, NickRyder, Mikhail Pavlov, Alethea. Power, Lukasz Kaiser,Mohammad Bavarian, Clemens Winter, Philippe Tillet, Fe-lipe Petroski Such, David W. Cummings, Matthias Plap-pert, Fotios Chantzis, Elizabeth Barnes, Ariel Herbert-Voss, William H. Guss, Alex Nichol, Igor Babuschkin,S. Arun Balaji, Shantanu Jain, Andrew Carr, Jan Leike,Joshua Achiam, Vedant Misra, Evan Morikawa, Alec Rad-ford, Matthew M. Knight, Miles Brundage, Mira Murati,Katie Mayer, Peter Welinder, Bob McGrew, Dario Amodei,Sam McCandlish, Ilya Sutskever, and Wojciech Zaremba.Evaluating large language models trained on code. arXivpreprint arXiv:2107.03374, 2021.

Xiang Chen, Xin Xie, Ningyu Zhang, Jiahuan Yan, ShuminDeng, Chuanqi Tan, Fei Huang, Luo Si, and Huajun Chen.Adaprompt: Adaptive prompt-based finetuning for relationextraction. arXiv preprint arXiv:2104.07650, 2021.

Miranda Chong, Lucia Specia, and Ruslan Mitkov. Using nat-ural language processing for automatic detection of plagia-rism. In Proceedings of the 4th International PlagiarismConference (IPC-2010), 2010.

Tomasz Darmetko. Fake or not? Generating adversarial ex-amples from language models. Doctoral thesis submittedto Maastricht University, 2021.

Phillip Dawson, Wendy Sutherland-Smith, and Mark Rick-sen. Can software improve marker accuracy at detectingcontract cheating? a pilot study of the Turnitin authorshipinvestigate alpha. Assessment & Evaluation in higher edu-cation, 45(4):473–482, 2020.

Breanna Devore-McDonald and Emery D Berger. Mossad:defeating software plagiarism detection. Proceedings ofthe ACM on Programming Languages, 4(OOPSLA):1–28,2020.

Iddo Drori and Nakul Verma. Solving linear algebra by pro-gram synthesis. arXiv preprint arXiv:2111.08171, 2021.

Iddo Drori, Sunny Tran, Roman Wang, Newman Cheng,Kevin Liu, Leonard Tang, Elizabeth Ke, Nikhil Singh, Tay-lor L Patti, Jayson Lynch, et al. A neural network solvesand generates mathematics problems by program synthe-sis: Calculus, differential equations, linear algebra, andmore. arXiv preprint arXiv:2112.15594, 2021.

Jinan AW Faidhi and Stuart K Robinson. An empiricalapproach for detecting program similarity and plagiarismwithin a university programming environment. Computers& Education, 11(1):11–19, 1987.

Vitaly Feldman. Does learning require memorization? a shorttale about a long tail. In Proceedings of the 52nd AnnualACM SIGACT Symposium on Theory of Computing, pages954–959, 2020.

Tomas Foltynek, Terry Ruas, Philipp Scharpf, NormanMeuschke, Moritz Schubotz, William Grosky, and BelaGipp. Detecting machine-obfuscated plagiarism. In In-ternational Conference on Information, pages 816–827.Springer, 2020.

Leo Gao, Stella Biderman, Sid Black, Laurence Golding,Travis Hoppe, Charles Foster, Jason Phang, Horace He,Anish Thite, Noa Nabeshima, Shawn Presser, and Con-nor Leahy. The Pile: An 800GB Dataset of Diverse Textfor Language Modeling. arXiv preprint arXiv:2101.00027,2020.

Xuanli He, Lingjuan Lyu, Lichao Sun, and Qiongkai Xu.Model extraction and adversarial transferability, yourBERT is vulnerable! In Proceedings of the 2021 Confer-ence of the North American Chapter of the Association forComputational Linguistics: Human Language Technolo-gies, pages 2006–2012, 2021.

Dan Hendrycks, Steven Basart, Saurav Kadavath, MantasMazeika, Akul Arora, Ethan Guo, Collin Burns, Samir Pu-ranik, Horace He, Dawn Song, and Jacob Steinhardt. Mea-suring coding challenge competence with APPS. In Thirty-fifth Conference on Neural Information Processing SystemsDatasets and Benchmarks Track, 2021.

Zhiqiang Hu, Roy Ka-Wei Lee, Charu C Aggarwal, and As-ton Zhang. Text style transfer: A review and experimentalevaluation. arXiv preprint arXiv:2010.12742, 2020.

Gabbrielle Johnson. Are algorithms value-free? feminist the-oretical virtues in machine learning. Journal of Moral Phi-losophy, special issue on ”Justice, Power, and the Ethics ofAlgorithmic Decision-Making”, 2022.

Juliana, Rudy Pramono, Rizaldi Parani, and Arifin Djakasa-putra. Transformation of learning for early childhood edu-cation through parent assistance in the pandemic covid-19.Transformation Of Learning For Early Childhood Educa-tion Through Parent Assistance In The Pandemic Covid-19,20(XX):1–14, 2020.

Oscar Karnalim, Setia Budi, Hapnes Toba, and Mike Joy.Source code plagiarism detection in academia with infor-mation retrieval: Dataset and the observatjion. Informaticsin Education, 18(2):321–344, 2019.

Page 7

Page 8: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

Kalpesh Krishna, Gaurav Singh Tomar, Ankur P. Parikh,Nicolas Papernot, and Mohit Iyyer. Thieves on SesameStreet! Model Extraction of BERT-based APIs. In Interna-tional Conference on Learning Representations, 2020.

Thomas Lancaster and Fintan Culwin. A comparison ofsource code plagiarism detection engines. Computer Sci-ence Education, 14(2):101–112, 2004.

Xiang Lisa Li and Percy Liang. Prefix-tuning: Optimiz-ing continuous prompts for generation. arXiv preprintarXiv:2101.00190, 2021.

Wei Li, Xinyan Xiao, Jiachen Liu, Hua Wu, Haifeng Wang,and Junping Du. Leveraging graph to improve abstractivemulti-document summarization. In Proceedings of the 58thAnnual Meeting of the Association for Computational Lin-guistics, pages 6232–6243, 2020.

Yang Liu and Mirella Lapata. Text summarization with pre-trained encoders. In Proceedings of the 2019 Conferenceon Empirical Methods in Natural Language Processingand the 9th International Joint Conference on Natural Lan-guage Processing (EMNLP-IJCNLP), pages 3730–3740,2019.

Pengfei Liu, Weizhe Yuan, Jinlan Fu, Zhengbao Jiang, Hi-roaki Hayashi, and Graham Neubig. Pre-train, prompt,and predict: A systematic survey of prompting meth-ods in natural language processing. arXiv preprintarXiv:2107.13586, 2021.

Divya Luke, PS Divya, Sony L Johnson, S Sreeprabha,and Elizabeth B Varghese. Software plagiarism detectiontechniques: A comparative study. In 2018 5th Interna-tional Symposium on Emerging Trends and Technologiesin Libraries and Information Services (ETTLIS). Citeseer,2014.

Rohan Mukherjee, Yeming Wen, Dipak Chaudhari, ThomasReps, Swarat Chaudhuri, and Chris Jermaine. Neural pro-gram generation modulo static analysis. In Thirty-FifthConference on Neural Information Processing Systems,2021.

Shashi Narayan, Shay B Cohen, and Mirella Lapata. Rank-ing sentences for extractive summarization with reinforce-ment learning. In Proceedings of the 2018 Conference ofthe North American Chapter of the Association for Compu-tational Linguistics: Human Language Technologies, Vol-ume 1 (Long Papers), pages 1747–1759, 2018.

Laria Reynolds and Kyle McDonell. Prompt programmingfor large language models: Beyond the few-shot paradigm.In Extended Abstracts of the 2021 CHI Conference on Hu-man Factors in Computing Systems, pages 1–7, 2021.

Dana Sheahen and David Joyner. TAPS: a MOSS extensionfor detecting software plagiarism at scale. In Proceedingsof the Third (2016) ACM Conference on Learning@ Scale,pages 285–288, 2016.

Avi Shporer, Sunny Tran, Nikhil Singh, Brandon Kates,Jayson Lynch, and Iddo Drori. Learning methods for solv-ing astronomy course problems. preprint, 2021.

Sunny Tran, Pranav Krishna, Ishan Pakuwal, PrabhakarKafle, Nikhil Singh, Jayson Lynch, and Iddo Drori. Solv-ing machine learning problems. In Asian Conference onMachine Learning, pages 470–485. PMLR, 2021.

Ben Wang and Aran Komatsuzaki. GPT-J-6B: a 6 billion pa-rameter autoregressive language model, 2021.

Muhammad Yasid, Gomgom T.P. Siregar, and Muham-mad Ansori Lubis. The policy of credit payment relaxationin overcoming the impact of Covid-19 spread to the eco-nomic society in Indonesia. Journal of Advanced Researchin Dynamical and Control Systems, 2020.

Page 8

Page 9: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

GPT-J was trained using a mix of raw text, source code, and formatted text. This gives it a tendency to use line-breaks incon-sistently, sometimes using single-spacing, sometimes using double spacing, and sometimes typing out the newline charactern. Similar phenomena happen with tabs and indentation.

Model generated text in this appendix has had its indentation and line breaks adjusted for consistency, space concerns, andimproved human readability. Although this would have an impact on proper code execution in some languages, all line breaksand indentations in Java are ornamental. Other than these readability fixes, all text presented in teletype is a verbatim quoteof the model output. By contrast, code presented in colorized codeblocks have been lightly edited as discussed in section 3.3.

A Example SolutionsWe begin by presenting representative solutions to each exercise. For complete model outputs on all generations, see Ap-pendix D.

Exercise 1: Write a program that prints “Welcome to Java” five times.

import java.io.*;

public class Java {public static void main(String args[]) {

System.out.println("Welcome to Java");System.out.println("Welcome to Java");System.out.println("Welcome to Java");System.out.println("Welcome to Java");System.out.println("Welcome to Java");

}}

Exercise 2: Write a program that accepts the radius & length of a cylinder and prints the area & volume of that cylinder. Allinputs and outputs are real numbers.

import java.util.Scanner;import java.lang.*;

public class Cylinder {public static void main(String args[]) {

Scanner sc = new Scanner(System.in);System.out.print("Input: radius & length of cylinder\n");double r = sc.nextDouble();double l = sc.nextDouble();double area = Cylinder.area(r, l);double volume = Cylinder.volume(r, l);System.out.println("\nThe area of cylinder is " + area);System.out.println("\nThe volume of cylinder is " + volume);

}static double area(double r, double l) {

double area = 2 * r * r * Math.PI + 2 * r * Math.PI * l;;return area;

}static double volume(double r, double l) {

double volume = l*Math.PI*Math.pow(r, 2);return volume;

}}

Exercise 3: Write a program that accepts the weight (as a real number representing pound) and height (as two real numbersrepresenting feet and inches respectively) of a person. Upon accepting input, the program will show that person’s BMI (realnumber) and a piece of information stating whether the BMI is categorised as underweight, normal, overweight, or obese.A person is underweight if BMI < 18.5; normal if 18.5 ≤ BMI < 25; overweight if 25 ≤ BMI < 35; or obese ifBMI ≥ 35.Height = feet ∗ 12 + inchesBMI = weight ∗ 0.45359237/(height ∗ 0.0254)2.

Page 9

Page 10: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

import java.util.Scanner;import java.lang.Math;

public class WeightBMI {public static void main(String[] args) {

Scanner scan = new Scanner(System.in);System.out.println("Enter weight in pounds");double weight = scan.nextDouble();System.out.println("Enter height in feet and inches");double feet = scan.nextDouble();double inch = scan.nextDouble();double height = feet * 12 + inch;

double bmi = weight * 0.45359237 / Math.pow(height * 0.0254, 2);System.out.println("BMI is: " + bmi);

if(bmi < 18.5) {System.out.println("Underweight");

} else if(18.5 <= bmi && bmi < 25) {System.out.println("Normal");

} else if(25 <= bmi && bmi < 35) {System.out.println("Overweight");

} else if(bmi >= 35) {System.out.println("Obese");

}}

}

Exercise 4: Write a program that shows a conversion table from miles to kilometers where one mile is equivalent to 1.609kilometers. The table should display the first ten positive numbers as miles and pair them with their respective kilometerrepresentation.

This task was not successfully completed by GPT-J in 15 trials. The closest it got was generating a conversion calculator, butwriting code that generates a table seems to have stymied it.

Exercise 5: Write a program that accepts an integer and displays that integer with its digits shown in reverse. You shouldcreate and use a method void reverse(int number) which will show the reversed-digit form of the parameterised number.

import java.util.Scanner;

public class Test {public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.println("Enter the number to reverse");int num = sc.nextInt();

while (num > 0) {System.out.print((num \% 10));num /= 10;

}}

}

Exercise 6: Write a program that accepts 10 integers and shows them in reversed order.

import java.util.Scanner;

public class Test {public static void main(String[] args) {

Scanner sc = new Scanner(System.in);int[] num = new int[10];

Page 10

Page 11: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

System.out.println("Enter the numbers to reverse");for (int i = 0; i < num.length; i++) {

num[i] = sc.nextInt();}

for (int i = num.length - 1; i >= 0; i--) {System.out.print(num[i] + " ");

}}

}

B Examples of Human InterventionAlthough GPT-J reliably constructs the general logic of an exercise, human intervention is often required to correct typos,amend the solution to the problem specification, or on rare occasions identify the correct solution from several options.

GPT-J was trained on Stack Overflow, and this is clearly reflected in some of its generations which directly mimic the styleof the Q&A site. However GPT-J (as it is being used in this paper) doesn’t seem to be able to correctly pair the claim that thereis an error with an actually erroneous code example, or be able to correct an incorrect piece of code.

In the following two examples, GPT-J gives a correct solution and then creates a response that represents it as being incorrect.The “correction” doesn’t actually change the code, and proposes swapping out a segment of the code for a functionally identicalsegment.

Write a Java program that accepts the weight (as a real number representing pound) and height(as two real numbers representing feet and inches respectively) of a person. Upon acceptinginput, the program will show that person’s BMI (real number) and a piece of information statingwhether the BMI is categorised as underweight, normal, overweight, or obese.\\A person isunderweight if $BMI < 18.5$; normal if $18.5 \leq BMI < 25$; overweight if $25 \leq BMI < 35$;or obese if $BMI \geq 35$.\\$Height = feet * 12 + inches$\\$BMI = weight * 0.45359237 / (height* 0.0254)ˆ2$

I tried to solve the problem but the program is not working. It shows only "Can't find variableweight"

This is the code I wrote:import java.util.*;public class Exercise1 {

public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.println("Enter weight");double weight = input.nextDouble();System.out.println("Enter height");double height = input.nextDouble();System.out.println("BMI is: " + getBMI(weight, height));

}

public static double getBMI(double weight, double height) {double weight_meters = weight * 0.45359237;double height_meters = height * 0.0254;double height_meters_squared = height_meters * height_meters;double bmi = weight_meters / (height_meters_squared);

return bmi;}

}

Can anyone help me please?

A:You are using Scanner, but you are not calling nextLine(). You should be using nextLine().

Page 11

Page 12: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

Scanner input = new Scanner(System.in);

System.out.println("Enter weight");double weight = input.nextDouble();System.out.println("Enter height");double height = input.nextDouble();

System.out.println("BMI is: " + getBMI(weight, height));

public static double getBMI(double weight, double height) {double weight_meters = weight * 0.45359237;double height_meters = height * 0.0254;double height_meters_squared = height_meters * height_meters;double bmi = weight_meters / (height_meters_squared);return bmi;

}

Write a Java program that accepts a $4\times 4$ matrix of real numbers and prints the total ofall numbers placed on the leading diagonal of the matrix. You should create and use a method\textit{double sumMajorDiagonal(double[][] m)} which will return the total of all numbers placedon the leading diagonal of the parameterised matrix. You should test your program with thefollowing input:

$\begin{bmatrix}1 & 2 & 3 & 4 \\5 & 6 & 7 & 8 \\9 & 10 & 11 & 12 \\13 & 14 & 15 & 16\end{bmatrix}$

Do not use arrays to store your data.

What is your solution? (you can use any method of your choice)

I have tried to solve this problem with a method but it is not giving the correct answer

My solution:import java.util.Scanner;public class FindSumOfMajorDiagonal {public static void main(String[] args) {

Scanner sc = new Scanner(System.in);double[][] array = new double[4][4];int i = 0;int j = 0;for(i = 0; i < array.length; i++)

for(j = 0; j < array[i].length; j++)array[i][j] = sc.nextDouble();

double total = 0;for(i = 0; i < array.length; i++)

total += array[i][i];System.out.println(total);}

}

A:

For loop is not necessary for this. You can use a single line method.double sumMajorDiagonal(double[][] m) {

Page 12

Page 13: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

double total = 0;for(int i = 0; i < m.length; i++)

total += m[i][i];return total;

}

And you can test it like this.public static void main(String[] args) {

double[][] matrix = {{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};double total = sumMajorDiagonal(matrix);System.out.println(total);

}

double total = sumMajorDiagonal(matrix);System.out.println(total);

double total = sumMajorDiagonal(matrix);System.out.println(total);

In this next example generation, GPT-J provides three candidate solutions but only one of them is correct. Fortunately, theuser can simply run the code to evaluate them without having to understand the problem’s specification. Note as well that in allthree examples GPT-J omits code for reading in the input and instead hard-codes the array to be reversed. As a result, we markthis generation as “partially correct.”Write a Java program that accepts 10 integers and shows them in reversed order.

for example:

10 2 3 4 5 6 7 8 9 1

A:This program will give the result in reverse orderpublic class Main {

public static void main(String[] args) {int[] a = new int[] {10, 2, 3, 4, 5, 6, 7, 8, 9, 1};int i = 0;while (i < a.length) {

System.out.print(a[i]);i++;

}System.out.println();

}}

A:

public class ReverseInts {public static void main(String[] args) {

int[] ints = { 10, 2, 3, 4, 5, 6, 7, 8, 9, 1 };int i = 0;while (i < ints.length) {

System.out.print(ints[i]);i++;

}}

}

A:

public static void main(String[] args) {

Page 13

Page 14: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

int[] a = new int[] {10, 2, 3, 4, 5, 6, 7, 8, 9, 1};

for(int i = a.length-1; i >= 0; i--) {System.out.print(a[i]);

}}

C Common MistakesThere are several recurring themes in the mistakes GPT-J makes. We document them here for completeness, and expect themto be of particular interest to HCI researchers in the future.

C.1 Mathematics ErrorsAlthough GPT-J generally has a high quality understanding of mathematics, it regularly makes mistakes in the geometricformula for the area and the volume of a cylinder in Exercise 2. The correct formulae are A = 2πr2 + 2πr` and V = πr2`.While these are not provided in the problem statement, they are readily avaliable on the internet so we assume a student is ableto correct them.

Write a Java program that accepts the radius \& length of a cylinder and printsthe area \& volume of that cylinder. All inputs and outputs are real numbers.The program is to be given as input and output and be stored in a file named"CylinderArea.java".

I have the following codepackage CylinderArea;

import java.io.*;

public class CylinderArea {

public static void main(String[] args) {Scanner sc = new Scanner(System.in);double radius, length;System.out.print("Enter radius: ");radius = sc.nextDouble();System.out.print("Enter length: ");length = sc.nextDouble();double area;area = Math.PI * radius * radius;double volume;volume = 2 * Math.PI * radius * length;System.out.println("The area of the cylinder is " + area + " and the volume is " +

volume + ".");}

}

Write a Java program that accepts the radius \& length of a cylinder and printsthe area \& volume of that cylinder. All inputs and outputs are real numbers.

A:

Try thisimport java.util.*;import java.lang.*;import java.io.*;

public class MyClass {

public static void main(String[] args) {

Page 14

Page 15: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

Scanner scan = new Scanner(System.in);int rad, len, area, volume;

System.out.println("Enter radius of the cylinder:");rad = scan.nextInt();System.out.println("Enter length of the cylinder:");len = scan.nextInt();

area = Math.pow(rad, 2) * len;volume = Math.pow(len, 3);

System.out.println("The area of the cylinder is : " + area);System.out.println("The volume of the cylinder is : " + volume);

scan.close();}

}

It will do the trick.

The other common mathematical mistake occurs in Exercise 3, computing BMI. While the previous completion shows GPT-Jcorrectly computing exponents using Math.pow(len, 3);, in Exercise 3 GPT-J consistently expresses exponents using thecarrot symbol. We hypothesize that this is caused by the use of LATEXto express the equations in the statement of Exercise 3,showing GPT-J the carrot symbol which it proceeds to copy despite seeming to know that that is incorrect syntax in Java.

public class WeightAndHeight {public static void main (String[] args) {

double height, weight, BMI; // input variables.Scanner in = new Scanner(System.in);System.out.println("Enter height: ");height = in.nextDouble(); // get user's height

System.out.println("Enter weight: ");weight = in.nextDouble(); // get user's weight

BMI = weight * 0.45359237 / (height * 0.0254)ˆ2; // calculate BMI

System.out.println("The person's BMI is: " + BMI);if (BMI < 18.5) {System.out.println("The person is underweight.");} else if (18.5 <= BMI && BMI < 25) {

System.out.println("The person is normal.");} else if (25 <= BMI && BMI < 35) {

System.out.println("The person is overweight.");} else if (BMI >= 35) {

System.out.println("The person is obese.");}

}}

C.2 Invented ConstraintsAnother common failure mode for GPT-J is inventing new problem constraints that do not actually exist in the problem. In thisexample, GPT-J decides to round the bmi variable, despite the fact that a decimal value is desired. Other errors also exist in thispiece of code, but they are easily fixed by rereading the problem specification and the overall logic is correct.

import java.util.Scanner;import java.lang.Math;

public class Main {public static void main(String[] args) {

Page 15

Page 16: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

Scanner input = new Scanner(System.in);System.out.print("Enter your weight in pounds:");double weight = input.nextDouble();

System.out.print("Enter your height in inches:");double height = input.nextDouble();double heightInches = height * 12;double heightPounds = heightInches * 0.45359237;

double weightInches = weight * 0.0254;double weightPounds = weightInches * 0.45359237;

double bmi = Math.round(weight * 0.45359237 / (height * 0.0254) * 100.0);System.out.println("BMI is " + bmi);

if (bmi < 18.5) {System.out.println("Person is underweight");

} else if (bmi < 25) {System.out.println("Person is normal");

} else if (bmi < 35) {System.out.println("Person is overweight");

} else {System.out.println("Person is obese");

}}

}

A related failure case occurs because our inputs do not clearly delineate where the question ends and where the answer begins.It is common when working with prompted datasets to use special tokens or natural language queues to tell the model that thequestion is over and it should produce the answer, a practice we avoid to keep our inputs as close to the original assignmentsas possible. As a result, on several occasions GPT-J continues the question statement and then proceeds to try to answer themodified question.

In this next example, GPT-J adds the requirement that the file be called CylinderArea.java. Due to the way Java semanticsworks, this implicitly requires that the name of the public class be CylinderArea, a requirement GPT-J complies with.

Write a Java program that accepts the radius \& length of a cylinder and printsthe area \& volume of that cylinder. All inputs and outputs are real numbers.The program is to be given as input and output and be stored in a file named"CylinderArea.java". The resulting generation is ultimately marked as correct, though it needsto have some import statements added and the mathematical formulae modified.

I have the following codepackage CylinderArea;

import java.io.*;

public class CylinderArea {

public static void main(String[] args) {Scanner sc = new Scanner(System.in);double radius, length;System.out.print("Enter radius: ");radius = sc.nextDouble();System.out.print("Enter length: ");length = sc.nextDouble();double area;area = Math.PI * radius * radius;double volume;volume = 2 * Math.PI * radius * length;System.out.println("The area of the cylinder is " + area + " and the volume is " +

Page 16

Page 17: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

volume + ".");}

}

We see the same situation play out in another Assignment 2 completion, where GPT-J specifies the order the inputs andoutputs should be presented in and then complies with its requirement.

Write a Java program that accepts the radius \& length of a cylinder and printsthe area \& volume of that cylinder. All inputs and outputs are real numbers. Inputand output are in the following order:

Input: radius \& length of cylinder

Output: area \& volume of cylinder

Replace this code with your own Java program.

public class Cylinder {public static void main(String args[]){

Scanner sc = new Scanner(System.in);System.out.print("Input: radius & length of cylinder\n");double r = sc.nextDouble();double l = sc.nextDouble();double area = Cylinder.area(r, l);double volume = Cylinder.volume(r, l);System.out.println("\nThe area of cylinder is " + area);System.out.println("\nThe volume of cylinder is " + volume);

}static double area(double r, double l){

double area = r*r*Math.PI;return area;

}static double volume(double r, double l){

double volume = l*Math.PI*Math.pow(r, 2);return volume;

}}

D Full Text of All GenerationsThe following are examples of correct solutions generated by GPT-J for each exercise.

D.1 Exercise 1:Write a program that prints “Welcome to Java” five times.

Generation 1-1: Not codeWrite a Java program that prints ``Welcome to Java'' five times.

Substitute the character in the message string for an integer, for example, ``Welcome toJava'', and substitute the integer for a character.↪→

The program should run until the user enters the character ``e'' to terminate the program.

When the user enters the character ``e'' the program should print the character ``e''.

The user should be able to enter the integer between 1 and 10.

Page 17

Page 18: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

The user should be able to enter the character between A and Z.

The user should be able to enter the character between 0 and 9.

The user should be able to

Generation 1-2: Not codeWrite a Java program that prints ``Welcome to Java'' five times.

Write a Java program that prints ``Welcome to Java'' five times.

-

'''Input'''

+

'''Input'''

-

* '''Java Program'''

+

* '''Java Program'''

-

* '''Output'''

+

* '''Output'''

-

* '''Run'''

+

* '''Run'''

-

* '''Restart'''

+

* '''Restart'''

Generation 1-3: Not codeWrite a Java program that prints ``Welcome to Java'' five times.

This is a Java homework question. If you want to help me with it, please vote this up. Thanks!

˜

Solution

Page 18

Page 19: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

Welcome to Java

Welcome to Java

Welcome to Java

Welcome to Java

Welcome to Java

˜

Hi, I'm here to help you.

Hi, I'm here to help you.

Hi, I'm here to help you.

Hi, I'm here to help you.

Hi, I'm here to help you.

˜

import java.util.Scanner;

import java.util.Scanner;

import java.util.Scanner;

import java.util.Scanner;

import java.util.Scanner;

˜

import java.util.Scanner;

import java.util.Scanner;

import java.util.Scanner;

˜

Generation 1-4: Partially correct (missing class structure)

Write a Java program that prints ``Welcome to Java'' five times.

for(int i=0;i<5;i++){System.out.print("Welcome to Java");}

for(int i=0;i<5;i++){System.out.print("Welcome to Java");}

Hi there,

Page 19

Page 20: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

Write a Java program that prints ``Welcome to Java'' five times.

for(int i=0;i<5;i++){System.out.print("Welcome to Java");}

Generation 1-5: Not codeWrite a Java program that prints ``Welcome to Java'' five times.

The program is required to be written with a single main method. The main method must be calledusing the following statement:↪→

``java Welcome5``

The program must be organized into three classes. The first class is the ``Welcome5`` class.The second class is the ``Program`` class. The third class is the ``HelloWorld`` class.↪→

``Welcome5`` class

The ``Welcome5`` class is a single file called ``Welcome5.java``. The ``Welcome5`` classimplements the ``Runnable`` interface.↪→

The ``Runnable`` interface has

Generation 1-6: No changesWrite a Java program that prints ``Welcome to Java'' five times.

Answer :

import java.io.*;class Java{public static void main(String args[]){System.out.println("Welcome to Java");System.out.println("Welcome to Java");System.out.println("Welcome to Java");System.out.println("Welcome to Java");System.out.println("Welcome to Java");}}

import java.io.*;

public class Java {public static void main(String args[]) {

System.out.println("Welcome to Java");System.out.println("Welcome to Java");System.out.println("Welcome to Java");System.out.println("Welcome to Java");System.out.println("Welcome to Java");

}}

Generation 1-7: Not codeWrite a Java program that prints ``Welcome to Java'' five times. The program should use a loop

to print the message.↪→

The following is a sample of the output from running the program:

Page 20

Page 21: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

Welcome to Java

Welcome to Java

Welcome to Java

Welcome to Java

Welcome to Java

### **What Is a Loop?**

The _loop_ is a section of a program that is repeated a certain number of times. When the loopis completed, the program continues to the next line of code and runs the same line of codeagain. A loop is considered to be part of the program's _control flow_ because it definesthe flow of execution

↪→

↪→

↪→

Send result as prompt

Generation 1-8: Not codeWrite a Java program that prints ``Welcome to Java'' five times.

Answers

I got this:

Welcome to JavaWelcome to JavaWelcome to JavaWelcome to JavaWelcome to Java

I know that this is not what you wanted, but I have no idea how you could make that happen. Ifyou give me a little more information, I can probably give you a better answer.↪→

For example, let's say you want the user to enter a name and then see the program print``Hello, your name is [name].'' Then you would do this:↪→

1

2

3

4

5

Generation 1-9: Syntax errorWrite a Java program that prints ``Welcome to Java'' five times.

This is a sample question from the JSP assignment.

Solution:

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

Page 21

Page 22: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

import java.io.PrintStream;

import java.util.Scanner;

public class JavaProgram {

public static void main(String[] args) {

System.out.println("Welcome to Java");

System.out.println("Java is an object-oriented programming language");

System.out.println("Java was invented

public class JavaProgram {

public static void main(String[] args) {

System.out.println("Welcome to Java");System.out.println("Welcome to Java");System.out.println("Welcome to Java");System.out.println("Welcome to Java");System.out.println("Welcome to Java");

}}

Generation 1-10: Misc. errorWrite a Java program that prints ``Welcome to Java'' five times.

Problem:

The main problem is the output of the program. The program must print out the string ``Welcometo Java'' five times.↪→

Answer:

Here is the program that prints the welcome message five times.

/** To change this license header, choose License Headers in Project Properties.* To change this template file, choose Tools | Templates* and open the template in the editor.*/

/**** @author amit*/

import java.util.Scanner;

public class JavaProgram {

public static void main(String[] args) {Scanner in = new Scanner(System.in);

System.out.println("Welcome to Java!");

for (int i = 0; i < 5; i++) {

Page 22

Page 23: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

System.out.println("Java is a great language!");}

}}

Output:

Welcome to Java!Java is a great language!Java is a great language!Java is a great language!Java is a great language!

/*

import java.util.Scanner;

public class JavaProgram {

public static void main(String[] args) {Scanner in = new Scanner(System.in);

for (int i = 0; i < 5; i++) {System.out.println("Welcome to Java!");

}}}

Generation 1-11: Syntax errorWrite a Java program that prints the string "Welcome to Java" five times. The text is displayed

on a single line and the text is centered in the line. The program uses the font CourierNew.

↪→

↪→

#

Solution

I used the text method of JOptionPane to print the string five times. The text is centered inthe line. The JOptionPane displays the string on a single line.↪→

import javax.swing.JOptionPane;

import java.awt.Font;

import java.util.Random;

public class Solution {

public static void main(String[] args) {

int i = 0;

Random r = new Random();

while (i < 5) {

JOptionPane.showMessageDialog(null,

"Welcome to Java", "Welcome to Java", JOptionPane.CENTER);

Page 23

Page 24: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

i++;

}

}

}

## Algorithms

This section discusses the algorithms that were used to create this problem and other problemsin this book.↪→

### Searching for an Element in a List

Searching for an element in a list is done with a method called indexOf. The method finds theindex of the↪→

import javax.swing.JOptionPane;import java.awt.Font;import java.util.Random;

public class Solution {

public static void main(String[] args) {

int i = 0;Random r = new Random();while (i < 5) {

JOptionPane.showMessageDialog(null, "Welcome to Java", "Welcome toJava", JOptionPane.ERROR_MESSAGE);↪→

i++;}

}}

Generation 1-12: Misc. errorWrite a Java program that prints the string "Welcome to Java" five times. It will be a good

exercise to learn how to format the text and the number of printouts.↪→

Print "Welcome to Java" five times using "\n" as the newline.

To get started, let's start with a simple class.

public class HelloWorld {

public static void main(String[] args) {

System.out.println("Welcome to Java");

}

}

Now, let's write a test case for the above program:

public class HelloWorldTest {

@Test

Page 24

Page 25: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

public void testHelloWorld() {

HelloWorld h = new HelloWorld();

h.main(new String[] {});

}

}

Now, we need to build the test class.

$ javac HelloWorldTest.java

Now, we will run the test case:

$ java -cp. HelloWorldTest

Welcome to Java

Welcome to Java

Welcome to Java

Welcome to Java

Welcome to Java

Welcome to Java

Welcome to Java

Welcome to Java

Note that the "\n" is not required in this case.

public class HelloWorld {

public static void main(String[] args) {

System.out.println("Welcome to Java");System.out.println("Welcome to Java");System.out.println("Welcome to Java");System.out.println("Welcome to Java");System.out.println("Welcome to Java");

}

}

Generation 1-13: No changesMy solution:public class HelloWorld {

public static void main(String[] args) {for (int i = 0; i < 5; i++) {

System.out.println("Welcome to Java");}

}}

Page 25

Page 26: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

The output of my program is:Welcome to JavaWelcome to JavaWelcome to JavaWelcome to JavaWelcome to Java

I am trying to understand why this happens.

A

public class HelloWorld {

public static void main(String[] args) {for (int i = 0; i < 5; i++) {

System.out.println("Welcome to Java");}

}}

Generation 1-14: Misc. errorWrite a Java program that prints the string "Welcome to Java" five times.

import java.util.Scanner;public class Practice {public static void main(String[] args) {// create a ScannerScanner sc = new Scanner(System.in);// read input from the userSystem.out.println("Enter your name");String name = sc.nextLine();// print welcome messageSystem.out.println("Welcome to Java, " + name + "!");// print welcome message againSystem.out.println("Welcome to Java, " + name + "!");// print welcome message againSystem.out.println("Welcome to Java, " + name + "!");// print welcome message againSystem.out.println("Welcome to Java, " + name + "!");// print welcome message againSystem.out.println("Welcome to Java, " + name + "!");// print welcome message againSystem.out.println("Welcome to Java, " + name + "!");// read input from the userSystem.out.println("Enter your age");int age = sc.nextInt();// print welcome messageSystem.out.println("Welcome to

import java.util.Scanner;

public class Practice {public static void main(String[] args) {

// create a ScannerScanner sc = new Scanner(System.in);

// print welcome messageSystem.out.println("Welcome to Java.");

Page 26

Page 27: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

// print welcome message againSystem.out.println("Welcome to Java.");// print welcome message againSystem.out.println("Welcome to Java.");// print welcome message againSystem.out.println("Welcome to Java.");// print welcome message againSystem.out.println("Welcome to Java.");}

}

Generation 1-15: Misc. error

Write a Java program that prints the string "Welcome to Java" five times.

Solution:

Here is the solution:

import java.util.Scanner;

public class JavaProgram {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a number: ");

int i = scanner.nextInt();

if(i==1) {

System.out.print("Welcome to Java");

for(int k=0; k<5; k++) {

System.out.print("\n");

}

}

}

}

Output:

Enter a number: 1

Welcome to Java

Welcome to Java

Welcome to Java

Welcome to Java

Welcome to Java

Page 27

Page 28: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

[end of input]

Here are some of the things that are happening:

In the for loop, k starts at zero. It is incremented by 1 each time, so the first time k = 0,the second time k = 1, the third time k = 2 and so on.↪→

When k = 0, the first print statement is executed. This

import java.util.Scanner;

public class JavaProgram {

public static void main(String[] args) {

for(int k=0; k<5; k++) {

System.out.print("Welcome to Java\n");

}

}}

D.2 Exercise 2:Write a program that accepts the radius & length of a cylinder and prints the area & volume of that cylinder. All inputs andoutputs are real numbers.Generation 2-1: Syntax error and misc. errorWrite a Java program that accepts the radius \& length of a cylinder and prints the area &

volume of that cylinder. All inputs and outputs are real numbers.↪→

I'm having trouble understanding how to calculate the area of a cylinder.Here's what I've come up with so far:import java.util.Scanner;

public class CylinderArea {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);System.out.println("Please enter the length of the cylinder: ");double cylinderLength = sc.nextDouble();System.out.println("Please enter the radius of the cylinder: ");double cylinderRadius = sc.nextDouble();

double area = (4*cylinderLength*cylinderRadius);

System.out.println("The area of this cylinder is " + area);

double volume = cylinderLength * cylinderRadius * cylinderLength;

System.out.println("The volume of this cylinder is " + volume);}

}

A:

Page 28

Page 29: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

If you have a cylinder of radius r and length L, the area is πr² + πrL. The volume is πr³/3.The formula for calculating the area of a cylinder is based on the area of a slice of the

cylinder. In your case, the area of a slice is πr² and the length of the slice is L - r.Therefore, the area of the cylinder is πr² + πr(L - r).

↪→

↪→

import java.util.Scanner;

public class CylinderArea {public static void main(String[] args) {

Scanner sc = new Scanner(System.in);System.out.println("Please enter the length of the cylinder: ");double cylinderLength = sc.nextDouble();System.out.println("Please enter the radius of the cylinder: ");double cylinderRadius = sc.nextDouble();double area = (2*cylinderLength*cylinderRadius);System.out.println("The area of this cylinder is " + area);double volume = cylinderLength * cylinderRadius * cylinderLength;System.out.println("The volume of this cylinder is " + volume);

}}

If you have trouble understanding how to calculate the area of a cylinder, here's a link thatshould help: http://en.wikipedia.org/wiki/Cylinder#Area_of_a_cylinder↪→

import java.lang.Math;import java.util.Scanner;

public class CylinderArea {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.println("Please enter the length of the cylinder: ");double cylinderLength = sc.nextDouble();

System.out.println("Please enter the radius of the cylinder: ");double cylinderRadius = sc.nextDouble();

double area = 2 * cylinderRadius * cylinderRadius * Math.PI + 2 * cylinderRadius *Math.PI * cylinderLength;↪→

System.out.println("The area of this cylinder is " + area);

double volume = Math.Pi * cylinderRadius * cylinderRadius * cylinderLength;System.out.println("The volume of this cylinder is " + volume);

}

}

Generation 2-2: Not codeWrite a Java program that accepts the radius \& length of a cylinder and prints the area &

volume of that cylinder. All inputs and outputs are real numbers.↪→

1.

Input

The radius of the cylinder is entered on the command line.

2.

Page 29

Page 30: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

Output

The area of the cylinder is printed to the command line and the volume of the cylinder isprinted to the command line.↪→

3.

Data Types

The radius is an integer and is stored in the variable radius and the length is an integer andis stored in the variable length.↪→

4.

Use of the Scanner Class

The Scanner class is used to read the input values.

5.

Use of the Math Class

The Math class is used to perform the calculations.

6.

Use of the System Class

The System class is used to perform the calculation.

7.

Program Output

You should have the following output when you run the program:

The area of the cylinder is 3.0. The volume of the cylinder is 12.0.

8.

Compile the code

Compile the code using the javac command.

javac Area.java

9.

Run the code

Run the code using the java command.

java Area

10.

Test the code

Your program should produce the following output when you run the program:

Page 30

Page 31: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

The area of the cylinder is 3.0. The volume of the cylinder is 12.0.

Tips

You should read the book, Java by Brian Kernighan and Dennis Ritchie. It is the best book onprogramming.↪→

You can use the if statement to check the input value.

You can use the switch statement to check the type of the input value.

You can use the double statement to check if the value is a real

Generation 2-3: Not codeWrite a Java program that accepts the radius \& length of a cylinder and prints the area &

volume of that cylinder. All inputs and outputs are real numbers.↪→

Area and Volume of a Cylinder

A cylinder is the three-dimensional shape formed by a circle lying on the XY plane and avertical line passing through the center of the circle. A cylinder is a solid object thatcan be sliced in two perpendicular planes. A cross-section of a cylinder looks like a rightcircular cylinder.

↪→

↪→

↪→

The cylinder is defined by a radius and a length. The radius of the cylinder is the distancefrom the center of the circle to the cylinder’s axis. The length of the cylinder is thedistance from the center of the circle to the vertical line passing through the center of

↪→

↪→

Generation 2-4: Not codeWrite a Java program that accepts the radius \& length of a cylinder and prints the area &

volume of that cylinder. All inputs and outputs are real numbers.↪→

Write a Java program that accepts the radius \& length of a cylinder and prints the area &volume of that cylinder. All inputs and outputs are real numbers.↪→

+

#Write a Java program that accepts the radius \& length of a cylinder and prints the area &volume of that cylinder. All inputs and outputs are real numbers.↪→

+

#Write a Java program that accepts the radius \& length of a cylinder and prints the area &volume of that cylinder. All inputs and outputs are real numbers.↪→

+

#Write a Java program that accepts the radius \& length of

Generation 2-5: Not codeWrite a Java program that accepts the radius \& length of a cylinder and prints the area &

volume of that cylinder. All inputs and outputs are real numbers.↪→

I have been reading and following tutorials for about a week now and I am stuck on a problem Idon't understand. I understand how to write the program but I don't understand how todefine the inputs and outputs. I think I have the general idea of what I need to do but Idon't understand what the input should be. I am new to Java and programming in general soplease excuse my ignorance.

↪→

↪→

↪→

↪→

Page 31

Page 32: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

The problem is as follows:

Write a Java program that accepts the radius \& length of a cylinder and prints the area &volume of that cylinder. All inputs and outputs are real numbers.↪→

The program should accept two inputs and print two outputs. The first input should be theradius of the cylinder and the second input should be the length of the cylinder.↪→

I have been reading and following tutorials for about a week now and I am stuck on a problem Idon't understand. I understand how to write the program but I don't understand how todefine the inputs and outputs. I think I have the general idea of what I need to do but Idon't understand what the input should be. I am new to Java and programming in general soplease excuse my ignorance.

↪→

↪→

↪→

↪→

Generation 2-6: Not codeWrite a Java program that accepts the radius \& length of a cylinder and prints the area \&

volume of that cylinder. All inputs and outputs are real numbers.↪→

Area Volume

Cylinder (r, h, d)

Area = pi * rˆ2

Volume = pi * r * h

Cylinder (r, h, d)

Area = pi * rˆ2

Volume = pi * r * h

Area = pi * rˆ2

Volume = pi * r * h

Cylinder (r, h, d)

Area = pi * rˆ2

Volume = pi * r * h

Area = pi * rˆ2

Volume = pi * r

Generation 2-7: Not codeWrite a Java program that accepts the radius \& length of a cylinder and prints the area \&

volume of that cylinder. All inputs and outputs are real numbers.↪→

We are given the radius and the length of the cylinder. To find the volume we use the formula\& area of a cylinder = r*l*h where \& r = radius, \& l = length, \& h = height.↪→

We are given the radius and the length of the cylinder. To find the area we use the formula \&area of a cylinder = r*l*h where \& r = radius, \& l = length, \& h = height.↪→

A cylinder is defined as a solid object having a circular base and a circular top and whoseheight is↪→

Generation 2-8: Syntax error and misc. error

Page 32

Page 33: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

Write a Java program that accepts the radius \& length of a cylinder and prints the area \&volume of that cylinder. All inputs and outputs are real numbers.↪→

\begin{minted}[linenos]{java}import java.util.Scanner;

public class CylinderAreaVol{

public static void main(String[] args){

double radius;double length;double area;double volume;double a;double v;

Scanner keyboard = new Scanner(System.in);

System.out.println("Enter the radius of the cylinder");radius = keyboard.nextDouble();

System.out.println("Enter the length of the cylinder");length = keyboard.nextDouble();

area = Math.PI * Math.pow(radius, 2) * length;volume = Math.PI * Math.pow(radius, 3) * length;

a = Math.pow(radius, 2);v = Math.pow(radius, 3);

}}\end{minted}

Inputs:

- $radius$: The radius of the cylinder- $length$: The length of the cylinder

Output:

- $area$: The area of the cylinder- $volume$: The volume of the cylinder

\begin{mint

import java.lang.Math;import java.util.Scanner;

public class CylinderAreaVol {public static void main(String[] args) {

double radius;double length;double a;double v;

Scanner keyboard = new Scanner(System.in);

Page 33

Page 34: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

System.out.println("Enter the radius of the cylinder");radius = keyboard.nextDouble();

System.out.println("Enter the length of the cylinder");length = keyboard.nextDouble();

a = 2 * Math.pow(rad, 2) * Math.PI + 2 * rad * Math.PI * len;v = Math.pow(radius, 2) * Math.PI * length;

System.out.println(a, v)}

}

Generation 2-9: Not codeWrite a Java program that accepts the radius \& length of a cylinder and prints the area \&

volume of that cylinder. All inputs and outputs are real numbers.↪→

A:

I have done this before, you just need to calculate the volume of the cylinder using thecylinder formula.↪→

Area = rˆ2 * hVolume = Area * h

Where r is the radius and h is the height.

A:

The area of a cylinder is the circumference of its base multiplied by its height. You have tokeep track of your coordinates for the circle. (e.g., (r*r - rˆ2)*pi/4 = rˆ2*pi/2, whichis the area of a circle)

↪→

↪→

You also need

Generation 2-11: Syntax error and misc. errorWrite a Java program that accepts the radius & length of a cylinder and prints

the area & volume of that cylinder. All inputs and outputs are real numbers.↪→

A:

Try thisimport java.util.*;import java.lang.*;import java.io.*;

public class MyClass {

public static void main(String[] args) {Scanner scan = new Scanner(System.in);int rad, len, area, volume;

System.out.println("Enter radius of the cylinder:");rad = scan.nextInt();System.out.println("Enter length of the cylinder:");len = scan.nextInt();

area = Math.pow(rad, 2) * len;volume = Math.pow(len, 3);

Page 34

Page 35: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

System.out.println("The area of the cylinder is : " + area);System.out.println("The volume of the cylinder is : " + volume);

scan.close();}

}

It will do the trick.

import java.util.*;import java.lang.*;import java.io.*;

public class MyClass {

public static void main(String[] args) {Scanner scan = new Scanner(System.in);double rad, len, area, volume;

System.out.println("Enter radius of the cylinder:");rad = scan.nextDouble();System.out.println("Enter length of the cylinder:");len = scan.nextDouble();

area = 2 * Math.pow(rad, 2) * Math.PI + 2 * rad * Math.PI * len;volume = Math.pow(rad, 2) * Math.PI * len;

System.out.println("The area of the cylinder is : " + area);System.out.println("The volume of the cylinder is : " + volume);

scan.close();}

}

Generation 2-12: Syntax error and misc. errorWrite a Java program that accepts the radius & length of a cylinder and prints

the area & volume of that cylinder. All inputs and outputs are real numbers.The program is to be given as input and output and be stored in a file named"CylinderArea.java".

↪→

↪→

↪→

I have the following codepackage CylinderArea;

import java.io.*;

public class CylinderArea {

public static void main(String[] args) {Scanner sc = new Scanner(System.in);double radius, length;System.out.print("Enter radius: ");radius = sc.nextDouble();System.out.print("Enter length: ");length = sc.nextDouble();double area;area = Math.PI * radius * radius;double volume;volume = 2 * Math.PI * radius * length;System.out.println("The area of the cylinder is " + area + " and the volume is " +

volume + ".");↪→

Page 35

Page 36: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

}}

import java.util.Scanner;import java.lang.*;import java.io.*;

public class CylinderArea {

public static void main(String[] args) {Scanner sc = new Scanner(System.in);double radius, length;System.out.print("Enter radius: ");radius = sc.nextDouble();System.out.print("Enter length: ");length = sc.nextDouble();double area;area = 2 * Math.pow(radius, 2) * Math.PI + 2 * rad * Math.PI * length;double volume;volume = Math.pow(radius, 2) * Math.PI * length;System.out.println("The area of the cylinder is " + area + " and the volume is " +

volume + ".");↪→

}}

Generation 2-13: Syntax error and misc. errorWrite a Java program that accepts the radius & length of a cylinder and prints

the area & volume of that cylinder. All inputs and outputs are real numbers.Input and output are in the following order:

↪→

↪→

Input: radius & length of cylinder

Output: area & volume of cylinder

Replace this code with your own Java program.

public class Cylinder {public static void main(String args[]){

Scanner sc = new Scanner(System.in);System.out.print("Input: radius & length of cylinder\n");double r = sc.nextDouble();double l = sc.nextDouble();double area = Cylinder.area(r, l);double volume = Cylinder.volume(r, l);System.out.println("\nThe area of cylinder is " + area);System.out.println("\nThe volume of cylinder is " + volume);

}static double area(double r, double l){

double area = r*r*Math.PI;return area;

}static double volume(double r, double l){

double volume = l*Math.PI*Math.pow(r, 2);return volume;

}

import java.util.Scanner;import java.lang.*;

Page 36

Page 37: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

public class Cylinder {public static void main(String args[]) {

Scanner sc = new Scanner(System.in);System.out.print("Input: radius & length of cylinder\n");double r = sc.nextDouble();double l = sc.nextDouble();double area = Cylinder.area(r, l);double volume = Cylinder.volume(r, l);System.out.println("\nThe area of cylinder is " + area);System.out.println("\nThe volume of cylinder is " + volume);

}

static double area(double r, double l) {double area = 2 * r * r * Math.PI + 2 * r * Math.PI * l;;return area;

}

static double volume(double r, double l) {double volume = l*Math.PI*Math.pow(r, 2);return volume;

}}

Generation 2-14: Not codeWrite a Java program that accepts the radius & length of a cylinder and prints

the area & volume of that cylinder. All inputs and outputs are real numbers.↪→

In this case, the cylinder is a circle. We can use the simple formulas:

The area of a circle is pi times the radius squared. So we can write:

But we can't use pi directly. We need to convert from a radian measure of angle to a degreemeasure of angle. The conversion factor is 2 pi divided by 360 degrees. So we have:↪→

The volume of a circle is pi times the radius cubed. So we can write:

But we need to convert from a radian measure of angle to a degree measure of angle. Theconversion factor is 2 pi divided by 360 degrees. So we have:↪→

Finally, we need to calculate the radius from the length. To do that, we use the formula forthe circumference of a circle:↪→

where _C_ is the circumference, _d_ is the radius, and _r_ is the length.

So we have:

# Chapter 6. Coordinate Geometry

Coordinate geometry is a collection of mathematical techniques for determining the position andorientation of an object with respect to a given coordinate system. It is used to figureout where objects are relative to each other, and to understand their relationships withrespect

↪→

↪→

↪→

Generation 2-15: Syntax error and misc. errorWrite a Java program that accepts the radius & length of a cylinder and prints

the area & volume of that cylinder. All inputs and outputs are real numbers.↪→

Here is my code:import java.util.Scanner;

Page 37

Page 38: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

public class JavaApplication1 {public static void main(String[] args) {

Scanner input = new Scanner(System.in);System.out.println("Enter Radius");int radius = input.nextInt();System.out.println("Enter Length");int length = input.nextInt();System.out.println(radius*length);

}}

The problem is that I am not getting the output for area and volume.

A:

The problem is in your code. The output is not printed because you have not set the output ofthe program. You need to use System.out.println.↪→

import java.util.Scanner;

public class JavaApplication1 {public static void main(String[] args) {

Scanner input = new Scanner(System.in);System.out.println("Enter Radius");int radius = input.nextInt();System.out.println("Enter Length");int length = input.nextInt();System.out.println(radius*length);System.out.println(radius*length);System.out.println(radius*length);

}}

Note the System.out.println() after the output.The output should beEnter Radius10Enter Length20

This is because the output of the first input is stored in the variable radius, and the outputof the second input is stored in length. When the program starts, length is initialized to0, so the second output is not printed.

↪→

↪→

import java.util.Scanner;

public class JavaApplication1 {public static void main(String[] args) {

Scanner input = new Scanner(System.in);System.out.println("Enter Radius");int radius = input.nextDouble();System.out.println("Enter Length");int length = input.nextDouble();System.out.println(2 * Math.pow(radius, 2) * Math.PI + 2 * radius * Math.PI * length);System.out.println(Math.pow(radius, 2) * Math.PI * length);

}}

D.3 Exercise 3:Write a program that accepts the weight (as a real number representing pound) and height (as two real numbers representingfeet and inches respectively) of a person. Upon accepting input, the program will show that person’s BMI (real number) and a

Page 38

Page 39: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

piece of information stating whether the BMI is categorised as underweight, normal, overweight, or obese.A person is underweight if BMI < 18.5; normal if 18.5 ≤ BMI < 25; overweight if 25 ≤ BMI < 35; or obese ifBMI ≥ 35.Height = feet ∗ 12 + inchesBMI = weight ∗ 0.45359237/(height ∗ 0.0254)2.

Generation 3-1: Not codeWrite a Java program that accepts the weight (as a real number representing pound) and height

(as two real numbers representing feet and inches respectively) of a person. Upon acceptinginput, the program will show that person’s BMI (real number) and a piece of informationstating whether the BMI is categorised as underweight, normal, overweight, or obese.\\Aperson is underweight if $BMI < 18.5$; normal if $18.5 \leq BMI < 25$; overweight if $25\leq BMI < 35$; or obese if $BMI \geq 35$.\\$Height = feet * 12 + inches$\\$BMI = weight *0.45359237 / (height * 0.0254)ˆ2$\\$0.0254 = 12 * 0.45359237 / (weight * heightˆ2)$\\

↪→

↪→

↪→

↪→

↪→

↪→

$0.0254 = 0.45359237$\\$0.45359237 = 12 * 0.0254$\\$BMI = weight * 0.45359237 / (height *12)ˆ2$\\$0.45359237 = weight * 0.45359237 / (height * feetˆ2)ˆ2$\\↪→

$0.45359237 = 0.0254 * weight$\\$0.0254 = 12 * 0.45359237 / (height * feetˆ2)$\\

$0.0254 = 12 * 0.45359237 / (height * feetˆ2)$\\$0.45359237 = 0.0254 * weight$\\

$BMI = weight * 0.0254 / (height * feetˆ2)$\\$0.0254 = 12 * 0.45359237 / (height * feetˆ2)$\\

$0.0254 = 12 * 0.45359237 / (height * feetˆ2)$\\$0.45359

Generation 3-2: Not codeWrite a Java program that accepts the weight (as a real number representing pound) and height

(as two real numbers representing feet and inches respectively) of a person. Upon acceptinginput, the program will show that person’s BMI (real number) and a piece of informationstating whether the BMI is categorised as underweight, normal, overweight, or obese.\\Aperson is underweight if $BMI < 18.5$; normal if $18.5 \leq BMI < 25$; overweight if $25\leq BMI < 35$; or obese if $BMI \geq 35$.\\$Height = feet * 12 + inches$\\$BMI = weight *0.45359237 / (height * 0.0254)ˆ2$\\If the person is obese, the program should also outputwhether that person is morbidly obese or not.\\

↪→

↪→

↪→

↪→

↪→

↪→

↪→

A:

One way to do it is to use the BMI formula (which is already correct), but also to include theheight and weight of the person.↪→

So the BMI formula becomes$$BMI = \frac{weight*0.45359237}{heightˆ2}$$And if you do the math, you get that $BMI = \frac{weight*0.45359237}{heightˆ2}$So the BMI formula is already correct. The problem

Generation 3-3: Not codeWrite a Java program that accepts the weight (as a real number representing pound) and height

(as two real numbers representing feet and inches respectively) of a person. Upon acceptinginput, the program will show that person’s BMI (real number) and a piece of informationstating whether the BMI is categorised as underweight, normal, overweight, or obese.\\Aperson is underweight if $BMI < 18.5$; normal if $18.5 \leq BMI < 25$; overweight if $25\leq BMI < 35$; or obese if $BMI \geq 35$.\\$Height = feet * 12 + inches$\\$BMI = weight *0.45359237 / (height * 0.0254)ˆ2$\\

↪→

↪→

↪→

↪→

↪→

↪→

Write a Java program that accepts the weight (as a real number representing pound) and height(as two real numbers representing feet and inches respectively) of a person. Upon acceptinginput, the program will show that person’s BMI (real number) and a piece of informationstating whether the BMI is categorised as underweight, normal, overweight, or obese.\\Aperson is underweight if $BMI < 18.5$; normal if $18.5 \leq BMI < 25$; overweight if $25\leq BMI < 35$; or obese if $BMI \geq

↪→

↪→

↪→

↪→

↪→

Page 39

Page 40: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

Generation 3-4: No changesWrite a Java program that accepts the weight (as a real number representing pound) and height

(as two real numbers representing feet and inches respectively) of a person. Upon acceptinginput, the program will show that person’s BMI (real number) and a piece of informationstating whether the BMI is categorised as underweight, normal, overweight, or obese.\\Aperson is underweight if $BMI < 18.5$; normal if $18.5 \leq BMI < 25$; overweight if $25\leq BMI < 35$; or obese if $BMI \geq 35$.\\$Height = feet * 12 + inches$\\$BMI = weight *0.45359237 / (height * 0.0254)ˆ2$

↪→

↪→

↪→

↪→

↪→

↪→

I tried to solve the problem but the program is not working. It shows only "Can't find variableweight"↪→

This is the code I wrote:

import java.util.*;

public class Exercise1

{

public static void main(String[] args)

{

Scanner input = new Scanner(System.in);

System.out.println("Enter weight");

double weight = input.nextDouble();

System.out.println("Enter height");

double height = input.nextDouble();

System.out.println("BMI is: " + getBMI(weight, height));

}

public static double getBMI(double weight, double height)

{

double weight_meters = weight * 0.45359237;

double height_meters = height * 0.0254;

double height_meters_squared = height_meters * height_meters;

double bmi = weight_meters / (height_meters_squared);

return bmi;

}

}

Can anyone help me please?

Page 40

Page 41: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

A:

You are using Scanner, but you are not calling nextLine(). You should be using nextLine().Scanner input = new Scanner(System.in);

System.out.println("Enter weight");double weight = input.nextDouble();System.out.println("Enter height");double height = input.nextDouble();

System.out.println("BMI is: " + getBMI(weight, height));

public static double getBMI(double weight, double height) {double weight_meters = weight * 0.45359237;double height_meters = height * 0.0254;double height_meters_squared = height_meters * height_meters;double bmi = weight_meters / (height_meters_squared);return bmi;}

There is no need for an extra method for this, you could just useSystem.out.println("BMI is: " + getBMI(weight

import java.util.*;

public class Exercise1 {public static void main(String[] args) {

Scanner input = new Scanner(System.in);System.out.println("Enter weight");double weight = input.nextDouble();System.out.println("Enter height");double height = input.nextDouble();

System.out.println("BMI is: " + getBMI(weight, height));

}

public static double getBMI(double weight, double height) {

double weight_meters = weight * 0.45359237;double height_meters = height * 0.0254;double height_meters_squared = height_meters * height_meters;double bmi = weight_meters / (height_meters_squared);return bmi;

}

}

Generation 3-5: Not code

Write a Java program that accepts the weight (as a real number representing pound) and height(as two real numbers representing feet and inches respectively) of a person. Upon acceptinginput, the program will show that person’s BMI (real number) and a piece of informationstating whether the BMI is categorised as underweight, normal, overweight, or obese.\\Aperson is underweight if $BMI < 18.5$; normal if $18.5 \leq BMI < 25$; overweight if $25\leq BMI < 35$; or obese if $BMI \geq 35$.\\$Height = feet * 12 + inches$\\$BMI = weight *0.45359237 / (height * 0.0254)ˆ2$

↪→

↪→

↪→

↪→

↪→

↪→

Page 41

Page 42: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

Re: Write a Java program that accepts the weight (as a real number representing pound) andheight (as two real numbers representing feet and inches respectively) of a person. Uponaccepting input, the program will show that person’s BMI (real number) and a piece ofinformation stating whether the BMI is categorised as underweight, normal, overweight, orobese.\\A person is underweight if $BMI < 18.5$; normal if $18.5 \leq BMI < 25$; overweightif $25 \leq BMI < 35$; or obese if $BMI \geq 35$.\\$Height = feet * 12 + inches$\\$BMI =weight * 0.45359237 / (height * 0.0254)ˆ2$

↪→

↪→

↪→

↪→

↪→

↪→

Re: Write a Java program that accepts the weight (as a real number representing pound) andheight (as two real numbers representing feet and inches respectively) of a person. Uponaccepting input, the program will show that person’s BMI (real number) and a piece ofinformation stating whether the BMI is categorised as underweight, normal, overweight, orobese.\\A person is underweight if $BMI < 18.

↪→

↪→

↪→

↪→

Generation 3-6: Not codeWrite a Java program that accepts the weight (as a real number representing pound) and height

(as two real numbers representing feet and inches respectively) of a person. Upon acceptinginput, the program will show that person’s BMI (real number) and a piece of informationstating whether the BMI is categorised as underweight, normal, overweight, or obese.\\Aperson is underweight if $BMI < 18.5$; normal if $18.5 \leq BMI < 25$; overweight if $25\leq BMI < 35$; or obese if $BMI \geq 35$.\\$Height = feet * 12 + inches$\\$BMI = weight *0.45359237 / (height * 0.0254)ˆ2$

↪→

↪→

↪→

↪→

↪→

↪→

]]>http://www.javapractices.com/input-output/what-is-a-bmi-how-to-get-it/feed/0How to Count theNumber of Letters in a Stringhttp://www.javapractices.com/input-output/how-to-count-the-num cber-of-letters-in-a-string/

↪→

↪→

http://www.javapractices.com/input-output/how-to-count-the-number-of-letters-in-a-string/#comme cntsMon, 16 Dec 2015 03:00:10 +0000http://www.javapractices.com/?p=5156How to Count theNumber of Letters in a String

↪→

↪→

Write a Java program that accepts the name of a person and returns the number of letters intheir name.↪→

An example of a valid name would be: \John".

An example of a valid input would be: \Seth".

An example of a valid output would be: \4".

]]>http://www.javapractices.com/input-output

Generation 3-7: Not codeWrite a Java program that accepts the weight (as a real number representing pound) and height

(as two real numbers representing feet and inches respectively) of a person. Upon acceptinginput, the program will show that person’s BMI (real number) and a piece of informationstating whether the BMI is categorised as underweight, normal, overweight, or obese.\\Aperson is underweight if $BMI < 18.5$; normal if $18.5 \leq BMI < 25$; overweight if $25\leq BMI < 35$; or obese if $BMI \geq 35$.\\$Height = feet * 12 + inches$\\$BMI = weight *0.45359237 / (height * 0.0254)ˆ2$

↪→

↪→

↪→

↪→

↪→

↪→

C:\>java BMI

Enter the weight and height of a person (in pounds and inches respectively)

Enter the weight and height of a person (in pounds and inches respectively)

1.

Enter the weight and height of a person (in pounds and inches respectively)

Page 42

Page 43: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

Weight :

4.25

Height :

6.0

Enter the weight and height of a person (in pounds and inches respectively)

Weight :

10.25

Height :

6.5

Enter the weight and height of a person (in pounds

Generation 3-8: Not code

Write a Java program that accepts the weight (as a real number representing pound) and height(as two real numbers representing feet and inches respectively) of a person. Upon acceptinginput, the program will show that person’s BMI (real number) and a piece of informationstating whether the BMI is categorised as underweight, normal, overweight, or obese.\\Aperson is underweight if $BMI < 18.5$; normal if $18.5 \leq BMI < 25$; overweight if $25\leq BMI < 35$; or obese if $BMI \geq 35$.\\$Height = feet * 12 + inches$\\$BMI = weight *0.45359237 / (height * 0.0254)ˆ2$\\$\#Hint:$ a good starting point is a BMIcalculator\\$\#Hint:$ \[\frac{height * 12 + inches}{heightˆ2 * 0.0254ˆ2} * (weight *0.45359237)\]ˆ1.2$\\$\#Hint:$ (weight * 0.45359237)ˆ1.2$

↪→

↪→

↪→

↪→

↪→

↪→

↪→

↪→

In this task, the user is given a string that represents a number. The program then has to findthe number represented by the string.\\$Input:$ String that represents a number$\\$Output:$Number represented by the string$\\$\#Hint:$ Start by converting the string into a numberusing a BigInteger constructor and then use BigDecimal methods to get the number'svalue\\$\#Hint:$\[\frac{BigInteger.valueOf(numberString)}{BigDecimal.valueOf(BigInteger.valueOf(10))} *10ˆ\frac{Integer.parseInt(numberString.substring(2)) -Integer.parseInt(numberString.substring(0,2))}{10ˆ1.2}\]

↪→

↪→

↪→

↪→

↪→

↪→

↪→

Generation 3-9: Not code

Write a Java program that accepts the weight (as a real number representing pound) and height(as two real numbers representing feet and inches respectively) of a person. Upon acceptinginput, the program will show that person’s BMI (real number) and a piece of informationstating whether the BMI is categorised as underweight, normal, overweight, or obese.\\Aperson is underweight if $BMI < 18.5$; normal if $18.5 \leq BMI < 25$; overweight if $25\leq BMI < 35$; or obese if $BMI \geq 35$.\\$Height = feet * 12 + inches$\\$BMI = weight *0.45359237 / (height * 0.0254)ˆ2$\\If $feet = 0$, $inches = 0$, $weight = 0$, or $height =0$, the program will display an error message.\\If the input is not valid, the program willdisplay an error message.

↪→

↪→

↪→

↪→

↪→

↪→

↪→

↪→

Exercise 1

Page 43

Page 44: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

Write a Java program that accepts the weight (as a real number representing pound) and height(as two real numbers representing feet and inches respectively) of a person. Upon acceptinginput, the program will show that person’s BMI (real number) and a piece of informationstating whether the BMI is categorised as underweight, normal, overweight, or obese.\\Aperson is underweight if $BMI < 18.5$; normal if $18.5 \leq BMI < 25$; overweight if $25\leq BMI < 35$; or obese if $BMI \geq 35$.\\$Height = feet * 12 + inches$\\$BMI = weight *0.45359237 / (height * 0.0254)ˆ2$\\If $feet = 0$, $inches = 0$, $weight = 0$, or $height =0$, the program will display an error message.\\If the input is not valid, the program

↪→

↪→

↪→

↪→

↪→

↪→

↪→

Generation 3-10: Misc. errorWrite a Java program that accepts the weight (as a real number representing pound) and height

(as two real numbers representing feet and inches respectively) of a person. Upon acceptinginput, the program will show that person’s BMI (real number) and a piece of informationstating whether the BMI is categorised as underweight, normal, overweight, or obese.\\Aperson is underweight if $BMI < 18.5$; normal if $18.5 \leq BMI < 25$; overweight if $25\leq BMI < 35$; or obese if $BMI \geq 35$.\\$Height = feet * 12 + inches$\\$BMI = weight *0.45359237 / (height * 0.0254)ˆ2$\\

↪→

↪→

↪→

↪→

↪→

↪→

``` {.java language="Java"}import java.util.Scanner;import java.lang.Math;

public class Main {

public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.print("Enter your weight in pounds:");double weight = input.nextDouble();

System.out.print("Enter your height in inches:");double height = input.nextDouble();double heightInches = height * 12;double heightPounds = heightInches * 0.45359237;

double weightInches = weight * 0.0254;double weightPounds = weightInches * 0.45359237;

double bmi = Math.round(weight * 0.45359237 / (height * 0.0254) * 100.0);System.out.println("BMI is " + bmi);

if (bmi < 18.5) {System.out.println("Person is underweight");

} else if (bmi < 25) {System.out.println("Person is normal");

} else if (bmi < 35) {System.out.println("Person is overweight");

} else {System.out.println("Person is obese");

}

}

}

```

import java.util.Scanner;import java.lang.Math;

public class Main {

Page 44

Page 45: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.print("Enter your weight in pounds:");double weight = input.nextDouble();

System.out.print("Enter your height in feet:");double height = input.nextDouble();double heightInches = height * 12;

double bmi = weight * 0.45359237 / Math.pow((height * 0.0254),2)System.out.println("BMI is " + bmi);

if (bmi < 18.5) {System.out.println("Person is underweight");

} else if (bmi < 25) {System.out.println("Person is normal");

} else if (bmi < 35) {System.out.println("Person is overweight");

} else {System.out.println("Person is obese");

}

}

}

Generation 3-11: Not codeWrite a Java program that accepts the weight (as a real number representing pound) and height

(as two real numbers representing feet and inches respectively) of a person. Upon acceptinginput, the program will show that person’s BMI (real number) and a piece of informationstating whether the BMI is categorised as underweight, normal, overweight, or obese.\\Aperson is underweight if $BMI < 18.5$; normal if $18.5 \leq BMI < 25$; overweight if $25\leq BMI < 35$; or obese if $BMI \geq 35$.\\$Height = feet * 12 + inches$\\$BMI = weight *0.45359237 / (height * 0.0254)ˆ2$

↪→

↪→

↪→

↪→

↪→

↪→

Write a Java program that accepts the weight (as a real number representing pound) and height(as two real numbers representing feet and inches respectively) of a person. Upon acceptinginput, the program will show that person’s BMI (real number) and a piece of informationstating whether the BMI is categorised as underweight, normal, overweight, or obese.\\Aperson is underweight if $BMI < 18.5$; normal if $18.5 \leq BMI < 25$; overweight if $25\leq BMI < 35$; or obese if $BMI \geq 35$.\\$Height = feet * 12 + inches$\\$BMI = weight *0.45359237 / (height * 0.0254)ˆ2$

↪→

↪→

↪→

↪→

↪→

↪→

Write a Java program that accepts the weight (as a real number representing pound) and height(as two real numbers representing feet and inches respectively) of a person. Upon acceptinginput, the program will show that person’s BMI (real number) and a piece of informationstating whether the BMI is categorised as underweight, normal, overweight, or obese.\\Aperson is underweight if $BMI < 18.5$; normal

↪→

↪→

↪→

↪→

Generation 3-12: No changesWrite a Java program that accepts the weight (as a real number representing pound) and height

(as two real numbers representing feet and inches respectively) of a person. Upon acceptinginput, the program will show that person’s BMI (real number) and a piece of informationstating whether the BMI is categorised as underweight, normal, overweight, or obese.\\Aperson is underweight if $BMI < 18.5$; normal if $18.5 \leq BMI < 25$; overweight if $25\leq BMI < 35$; or obese if $BMI \geq 35$.\\$Height = feet * 12 + inches$\\$BMI = weight *0.45359237 / (height * 0.0254)ˆ2$

↪→

↪→

↪→

↪→

↪→

↪→

Page 45

Page 46: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

import java.util.Scanner;import java.lang.Math;

public class WeightBMI {

public static void main(String[] args) {

Scanner scan = new Scanner(System.in);System.out.println("Enter weight in pounds");double weight = scan.nextDouble();System.out.println("Enter height in feet and inches");double feet = scan.nextDouble();double inch = scan.nextDouble();double height = feet * 12 + inch;

double bmi = weight * 0.45359237 / Math.pow(height * 0.0254, 2);System.out.println("BMI is: " + bmi);

if(bmi < 18.5) {System.out.println("Underweight");

} else if(18.5 <= bmi && bmi < 25) {System.out.println("Normal");

} else if(25 <= bmi && bmi < 35) {System.out.println("Overweight");

} else if(bmi >= 35) {System.out.println("Obese");

}}

}

import java.util.Scanner;import java.lang.Math;

public class WeightBMI {

public static void main(String[] args) {

Scanner scan = new Scanner(System.in);System.out.println("Enter weight in pounds");double weight = scan.nextDouble();System.out.println("Enter height in feet and inches");double feet = scan.nextDouble();double inch = scan.nextDouble();double height = feet * 12 + inch;

double bmi = weight * 0.45359237 / Math.pow(height * 0.0254, 2);System.out.println("BMI is: " + bmi);

if(bmi < 18.5) {System.out.println("Underweight");

} else if(18.5 <= bmi && bmi < 25) {System.out.println("Normal");

} else if(25 <= bmi && bmi < 35) {System.out.println("Overweight");

} else if(bmi >= 35) {System.out.println("Obese");

}}

}

Page 46

Page 47: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

import java.util.Scanner;import java.lang.Math;

public class WeightBMI {

public static void main(String[] args) {

Scanner scan = new Scanner(System.in);System.out.println("Enter weight in pounds");double weight = scan.nextDouble();System.out.println("Enter height in feet and inches");double feet = scan.nextDouble();double inch = scan.nextDouble();double height = feet * 12 + inch;

double bmi = weight * 0.45359237 / Math.pow(height * 0.0254, 2);System.out.println("BMI is: " + bmi);

if(bmi < 18.5) {System.out.println("Underweight");

} else if(18.5 <= bmi && bmi < 25) {System.out.println("Normal");

} else if(25 <= bmi && bmi < 35) {System.out.println("Overweight");

} else if(bmi >= 35) {System.out.println("Obese");

}}

}

Generation 3-13: Misc. error

Write a Java program that accepts the weight (as a real number representing pound) and height(as two real numbers representing feet and inches respectively) of a person. Upon acceptinginput, the program will show that person’s BMI (real number) and a piece of informationstating whether the BMI is categorised as underweight, normal, overweight, or obese.\\Aperson is underweight if $BMI < 18.5$; normal if $18.5 \leq BMI < 25$; overweight if $25\leq BMI < 35$; or obese if $BMI \geq 35$.\\$Height = feet * 12 + inches$\\$BMI = weight *0.45359237 / (height * 0.0254)ˆ2$

↪→

↪→

↪→

↪→

↪→

↪→

import java.util.Scanner;

public class WeightBMI {

public static void main(String[] args) {

Scanner scan = new Scanner(System.in);System.out.println("Enter weight in pounds");double weight = scan.nextDouble();System.out.println("Enter height in feet and inches");double height = scan.nextDouble();double bmi = weight * 0.45359237 / (height * 0.0254) * 100;System.out.println("BMI is: " + bmi);

double underWeight = bmi * 100 / 18.5;double normal = bmi * 100 / 25;double overweight = bmi * 100 / 30;double obese = bmi * 100 / 40;

Page 47

Page 48: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

if(bmi < 18.5) {System.out.println("Underweight");

} else if(18.5 <= bmi && bmi < 25) {System.out.println("Normal");

} else if(25 <= bmi && bmi < 35) {System.out.println("Overweight");

} else if(bmi > 35) {System.out.println("Obese");

}}

}

import java.util.Scanner;import java.lang.Math;

public class WeightBMI {

public static void main(String[] args) {

Scanner scan = new Scanner(System.in);System.out.println("Enter weight in pounds");double weight = scan.nextDouble();System.out.println("Enter height in feet and inches");double feet = scan.nextDouble();double inch = scan.nextDouble();double height = feet * 12 + inch;

double bmi = weight * 0.45359237 / Math.pow(height * 0.0254, 2);System.out.println("BMI is: " + bmi);

if(bmi < 18.5) {System.out.println("Underweight");

} else if(18.5 <= bmi && bmi < 25) {System.out.println("Normal");

} else if(25 <= bmi && bmi < 35) {System.out.println("Overweight");

} else if(bmi >= 35) {System.out.println("Obese");

}}

}

Generation 3-14: Misc. error

Write a Java program that accepts the weight (as a real number representing pound) and height(as two real numbers representing feet and inches respectively) of a person. Upon acceptinginput, the program will show that person’s BMI (real number) and a piece of informationstating whether the BMI is categorised as underweight, normal, overweight, or obese.\\Aperson is underweight if $BMI < 18.5$; normal if $18.5 \leq BMI < 25$; overweight if $25\leq BMI < 35$; or obese if $BMI \geq 35$.\\$Height = feet * 12 + inches$\\$BMI = weight *0.45359237 / (height * 0.0254)ˆ2$

↪→

↪→

↪→

↪→

↪→

↪→

Note: This is an online coding challenge, and the submission will be saved in the publicrepository on this website.↪→

Step 1

Create a file with the following contents:

Page 48

Page 49: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

public class WeightAndHeight { public static void main (String[] args) { double height, weight,BMI; // input variables. Scanner in = new Scanner(System.in); System.out.println("Enterheight: "); height = in.nextDouble(); // get user's height System.out.println("Enterweight: "); weight = in.nextDouble(); // get user's weight BMI = weight * 0.45359237 /(height * 0.0254)ˆ2; // calculate BMI System.out.println("The person's BMI is: " + BMI); if(BMI < 18.5) { System.out.println("The person is underweight."); } else if (18.5 <= BMI &&BMI < 25) { System.out.println("The person is normal."); } else if (25 <= BMI && BMI < 35){ System.out.println("The person is overweight."); } else if (BMI >= 35) {System.out.println("The person is obese."); } } }

↪→

↪→

↪→

↪→

↪→

↪→

↪→

↪→

Step 2

Make sure that you have followed the instructions in the first step properly. You should havecreated a new class with the given name.↪→

Step 3

Open the command prompt and execute the following command:

javac WeightAndHeight.java

Step 4

Open the command prompt and execute the following command:

java WeightAndHeight

You should get the following output:

Enter height: 10 Enter weight: 2.4 Enter the person's BMI is: 18.4 The person is normal.

import java.io.*;import java.util.Scanner;import java.lang.Math;

public class WeightAndHeight {public static void main (String[] args) {

double height, weight, BMI;

// input variables.Scanner in = new Scanner(System.in);System.out.println("Enter height: ");height = in.nextDouble(); // get user's height

System.out.println("Enter weight: ");weight = in.nextDouble(); // get user's weight

BMI = weight * 0.45359237 / Math.pow(height * 0.0254, 2); // calculate BMI

System.out.println("The person's BMI is: " + BMI);

if (BMI < 18.5) {System.out.println("The person is underweight.");

} else if (18.5 <= BMI && BMI < 25) {System.out.println("The person is normal.");

} else if (25 <= BMI && BMI < 35) {System.out.println("The person is overweight.");

} else if (BMI >= 35) {

Page 49

Page 50: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

System.out.println("The person is obese.");}

}}

Generation 3-15: Incorrect

Write a Java program that accepts the weight (as a real number representing pound) and height(as two real numbers representing feet and inches respectively) of a person. Upon acceptinginput, the program will show that person’s BMI (real number) and a piece of informationstating whether the BMI is categorised as underweight, normal, overweight, or obese.\\Aperson is underweight if $BMI < 18.5$; normal if $18.5 \leq BMI < 25$; overweight if $25\leq BMI < 35$; or obese if $BMI \geq 35$.\\$Height = feet * 12 + inches$\\$BMI = weight *0.45359237 / (height * 0.0254)ˆ2$\\This program is written to be done in an interactiveenvironment (using command line). The program will not terminate unless the user inputs aquit command. The program should print the information and ask for a new input if the userinputs something other than an integer.\\The user should be prompted for input in thefollowing order:\\‘Enter the weight of the person (in pounds):’\\‘Enter the height of theperson (in feet):’\\‘Enter the BMI (in real numbers):’\\‘Enter quit or not?’\\The usershould be prompted for the following input:\\‘Enter a real number representing the weightof the person:’\\‘Enter two real numbers representing the height of the person:’\\‘Enter areal number representing the BMI of the person:’\\‘Enter quit or not?’\\

↪→

↪→

↪→

↪→

↪→

↪→

↪→

↪→

↪→

↪→

↪→

↪→

↪→

↪→

A:

BMI (Body Mass Index) is a mathematical representation of weight and height.To find your BMI, first convert your weight in pounds to kilograms.Then, convert your height in inches to centimetres.Now, you can calculate your BMI using the formula.This is the general formula to calculate BMI:$$BMI = \frac{Weight \times 0.454}{Heightˆ2}$$Now, here is a sample program that calculates the BMI:public class BMI {

public static void main(String[] args) {// TODO Auto-generated method stubScanner keyboard = new Scanner(System.in);System.out.println("Enter the weight (in pounds) and height (in inches) of a person:");double weight = keyboard.nextDouble();double height = keyboard.nextDouble();

double kilos = weight / 2.20462262;double centimeters = height / 12.0;

System.out.println(kilos + " : " + centimeters);

System.out.println("BMI is : " + (kilos * 0.454) + "/(cmˆ2)");

keyboard.close();

}

}

A:

I suggest a more programmatic approach.

Page 50

Page 51: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

Make a method that converts

D.4 Exercise 4:Write a program that shows a conversion table from miles to kilometers where one mile is equivalent to 1.609 kilometers. Thetable should display the first ten positive numbers as miles and pair them with their respective kilometer representation.

Generation 4-1: Not codeWrite a Java program that shows a conversion table from miles to kilometers where one mile is

equivalent to $1.609$ kilometers. The table should display the first ten positive numbersas miles and pair them with their respective kilometer representation.

↪→

↪→

Write a Java program that shows a conversion table from miles to kilometers where one mile isequivalent to $1.609$ kilometers. The table should display the first ten positive numbersas miles and pair them with their respective kilometer representation.

↪→

↪→

-

The table should look like this:

+

The table should look like this:

-

+

-

|<span class="colorgreen">Miles</span>|<span class="colorgreen">Kilometers</span>|

+

-

+

-

|<span class="colorgreen">3.036</span>|<span class="colorgreen">1.609</span>|

+

-

+

-

|<span class="colorgreen">4.677</span>|<span class="colorgreen">2.353</span>|

+

-

+

-

Page 51

Page 52: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

|<span class="colorgreen">7.123</span>|<span class="colorgreen">3.576</span>|

Generation 4-2: Not codeWrite a Java program that shows a conversion table from miles to kilometers where one mile is

equivalent to $1.609$ kilometers. The table should display the first ten positive numbersas miles and pair them with their respective kilometer representation.

↪→

↪→

Write a Java program that shows a conversion table from miles to kilometers where one mile isequivalent to $1.609$ kilometers. The table should display the first ten positive numbersas miles and pair them with their respective kilometer representation.

↪→

↪→

Solution Summary

The solution demonstrates how to write a Java program that shows a conversion table from milesto kilometers where one mile is equivalent to $1.609$ kilometers. The table should displaythe first ten positive numbers as miles and pair them with their respective kilometerrepresentation.

↪→

↪→

↪→

Tags

The answer given to the problem is correct and valid.

Introduction

Generation 4-3: Not codeWrite a Java program that shows a conversion table from miles to kilometers where one mile is

equivalent to $1.609$ kilometers. The table should display the first ten positive numbersas miles and pair them with their respective kilometer representation.

↪→

↪→

Solution

This problem is easier to understand if we divide the conversion table into smaller parts. Thefirst part is an array of all the kilometers and the second part is an array of all themiles. Let’s call them kilometers[] and miles[].

↪→

↪→

Miles[]

Kilometers[]

2

2

4

2

8

2

16

2

32

2

64

Page 52

Page 53: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

2

128

2

256

2

512

2

1024

2

Generation 4-4: Partially correct (Converts but doesn’t make table)

Write a Java program that shows a conversion table from miles to kilometers where one mile isequivalent to $1.609$ kilometers. The table should display the first ten positive numbersas miles and pair them with their respective kilometer representation.

↪→

↪→

The program is as follows. It is a very simple program. It displays a conversion table.

import java.util.Scanner;

public class MilesToKm {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.println("Enter the number of miles you want to convert: ");

int miles = sc.nextInt();

int km = (int)(2.23456 * miles);

System.out.println(km);

}

}

Generation 4-5: Not code

Write a Java program that shows a conversion table from miles to kilometers where one mile isequivalent to $1.609$ kilometers. The table should display the first ten positive numbersas miles and pair them with their respective kilometer representation.

↪→

↪→

The program should not prompt the user for the number of kilometers to convert. The programshould convert the specified number of miles to kilometers and output the converted numberof kilometers to the console.

↪→

↪→

The number of kilometers to convert is to be provided as an input to the program.

Below is the program which I have written. However, it gives me an error.

Page 53

Page 54: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

"Exception in thread "main" java.lang.NumberFormatException: For input string:"2.8571428571428572" atjava.lang.NumberFormatException.forInputString(NumberFormatException.java:48) atjava.lang.Integer.parseInt(Integer.java:449) atjava.lang.Integer.parseInt(Integer.java:499) at Program5.main(Program5.java:25)

↪→

↪→

↪→

↪→

"

I do not know what is the problem with the code. Can anyone please help me with this?

Note that the program should not prompt the user for the number of kilometers to convert.

You cannot post new topics in this forum.You cannot reply to topics in this forum.You cannot delete your posts in this forum.You cannot edit your

Generation 4-6: Not code

Write a Java program that shows a conversion table from miles to kilometers where one mile isequivalent to $1.609$ kilometers. The table should display the first ten positive numbersas miles and pair them with their respective kilometer representation.

↪→

↪→

I've seen this problem asked in the past and I think I got the answer right, but I don't reallyunderstand the point of the exercise. I know the conversion is $1 \frac{miles}{km} = 1.609\frac{km}{miles}$, but how does that help? Why are there ten values, how does the problemrelate to miles to kilometers?

↪→

↪→

↪→

Any help would be appreciated.

20 Answers20

The exercise is simply to check your knowledge of the conversion between miles and kilometers.This is a little bit more subtle than it seems.↪→

Let us denote the number of kilometers by $n$. Then,\begin{align}1 \cdot \frac{miles}{km} &= 1 \cdot \frac{miles}{\frac{miles}{km} \cdot km} \\&= 1 \cdot \frac{miles}{(1 \cdot km) \cdot km} \\&= 1 \cdot \frac{miles}{1 \cdot kmˆ2} \\&= \frac{miles}{kmˆ2} \\&= \frac{miles}{

Generation 4-7: Not code

Write a Java program that shows a conversion table from miles to kilometers where one mile isequivalent to $1.609$ kilometers. The table should display the first ten positive numbersas miles and pair them with their respective kilometer representation.

↪→

↪→

Write a Java program that shows a conversion table from miles to kilometers where one mile isequivalent to $1.609$ kilometers. The table should display the first ten positive numbersas miles and pair them with their respective kilometer representation.

↪→

↪→

So basically I just need to loop through the numbers and add the conversion, but I'm unsure howto loop through them.↪→

Write a Java program that shows a conversion table from miles to kilometers where one mile isequivalent to $1.609$ kilometers. The table should display the first ten positive numbersas miles and pair them with their respective kilometer representation.

↪→

↪→

Page 54

Page 55: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

So basically I just need to loop through the numbers and add the conversion, but I'm unsure howto loop through them.↪→

We use a loop to iterate through each item in an array or collection. We can use a for loop,while loop, do-while loop, or an enhanced for loop.↪→

Write a Java program that shows a conversion table from miles to kilometers where one mile isequivalent to $1.609$ kilometers. The table should display the first ten positive numbersas miles and pair them with their respective kilometer representation.

↪→

↪→

So basically I just need to loop through the numbers and add the conversion

Generation 4-8: Not codeWrite a Java program that shows a conversion table from miles to kilometers where one mile is

equivalent to $1.609$ kilometers. The table should display the first ten positive numbersas miles and pair them with their respective kilometer representation.

↪→

↪→

I have been programming for a while now and I have learned a lot of new stuff. I decided toshare some of my knowledge with you.↪→

1. What is a computer language?

A computer language is a human language used to communicate with a computer. The computer doesnot understand the human language. A human language is a set of symbols that has rules andregulations. A computer language is the set of symbols that a computer understands. Acomputer language is a set of symbols, such as words, sentences, mathematical formulas, andothers that a computer understands and can use to communicate with a human.

↪→

↪→

↪→

↪→

Generation 4-9: Not codeWrite a Java program that shows a conversion table from miles to kilometers where one mile is

equivalent to $1.609$ kilometers. The table should display the first ten positive numbersas miles and pair them with their respective kilometer representation.

↪→

↪→

I'm going to post my code for this problem. I have written a program in Java that convertsbetween miles and kilometers. It takes an input of either "miles" or "kilometers" and thenprints the answer out to a txt file. The program works, but I just don't think that it is avery elegant solution. Here is the code:

↪→

↪→

↪→

miles to kilometers, or miles to kilometers in the reverse direction. The user enters "miles"or "kilometers" and the program prints out the answer.↪→

Writing a Java program that shows a conversion table from miles to kilometers

Generation 4-10: Not codeWrite a Java program that shows a conversion table from miles to kilometers where one mile is

equivalent to $1.609$ kilometers. The table should display the first ten positive numbersas miles and pair them with their respective kilometer representation. The program shouldbe in the form of a loop that goes through the first 10 numbers, then a loop that goesthrough the next 10 numbers, and so on.

↪→

↪→

↪→

↪→

For the first 10 positive numbers, the program should output a list that contains the numberand its kilometer representation.↪→

For the next 10 positive numbers, the program should output a list that contains the number andits kilometer representation.↪→

For the next 10 positive numbers, the program should output a list that contains the number andits kilometer representation.↪→

For the next 10 positive numbers, the program should output a list that contains the number and

Page 55

Page 56: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

Generation 4-11: In CWrite a program that shows a conversion table from miles to kilometers where one mile is

equivalent to $1.609$ kilometers. The table should display the first ten positive numbersas miles and pair them with their respective kilometer representation. You can assume thatthe user will provide the kilometers as an integer value.

↪→

↪→

↪→

I wrote a program to do this. It is running fine but there is a problem that I am not able toresolve. My program outputs this :↪→

10.000000 10.0000011.000000 11.0000012.000000 12.0000013.000000 13.0000014.000000 14.0000015.000000 15.0000016.000000 16.0000017.000000 17.0000018.000000 18.0000019.000000 19.00000

The correct answer should be :

10.000000 10.0000011.000000 11.0000012.000000 12.0000013.000000 13.0000014.000000 14.0000015.000000 15.0000016.000000 16.0000017.000000 17.0000018.000000 18.0000019.000000 19.0000020.000000 20.00000

The program is given below :

#include <stdio.h>

int main(){int i,k,j,m,km,d;

printf("Enter the number of kilometers : ");scanf("%d",&k);

for(i=1;i<=k;i++){printf("Enter the kilometers : ");scanf("%d",&km);

printf("Enter the miles : ");scanf("%d",&m);

if(m>km)d=m-km;elsed=km-m;

printf("The kilometers = %d and the miles = %d",km,m);

Page 56

Page 57: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

printf("The difference is %d",d);

if(d>0)printf("%d",d);elseprintf("%d",d);

}return 0;

}

I don't understand why the program is printing the last row. Can you please explain the problem?

If you are going to assume that the miles are miles then the program is doing the right thing,but I can see a problem if you are going to assume that the kilometers are miles. Youshould have a conversion table that can handle negative numbers.

↪→

↪→

{CyrusJul 6 '12 at 13:15

No, I am not assuming that the miles

Generation 4-12: Not codeWrite a program that shows a conversion table from miles to kilometers where one mile is

equivalent to $1.609$ kilometers. The table should display the first ten positive numbersas miles and pair them with their respective kilometer representation.

↪→

↪→

I am currently writing a program that takes a given integer value and then calculates thenumber of miles it is equivalent to in kilometers. For example, if a user enters the number3, the program will return the number 0.95, which is the number of miles it is equivalentto in kilometers.

↪→

↪→

↪→

I am currently writing a program that takes a given integer value and then calculates thenumber of miles it is equivalent to in kilometers. For example, if a user enters the number3, the program will return the number 0.95, which is the number of miles it is equivalentto in kilometers.

↪→

↪→

↪→

I am currently writing a program that takes a given integer value and then calculates thenumber of miles it is equivalent to in kilometers. For example, if a user enters the number3, the program will return the number 0.95, which is the number of miles it is equivalentto in kilometers.

↪→

↪→

↪→

I am currently writing a program that takes a given integer value and then calculates thenumber of miles it is equivalent to in kilometers. For example, if a user enters the number3, the program will return the number 0.95, which is the number of miles it is equivalentto in kilometers.

↪→

↪→

↪→

I am currently writing a program

Generation 4-13: IncorrectWrite a program that shows a conversion table from miles to kilometers where one mile is

equivalent to $1.609$ kilometers. The table should display the first ten positive numbersas miles and pair them with their respective kilometer representation.

↪→

↪→

Here is what I've got:

const milToKm = (miles, km) => {

let miles = String(miles)

Page 57

Page 58: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

let km = String(km)

let miles_ = []

let km_ = []

let km_len = 0

let m_len = 0

if (miles === "") {

miles_ = []

} else if (km === "") {

km_ = []

} else {

let a = miles.length

let b = km.length

let c = Math.floor((a / 1000) / 12)

let d = Math.floor(a / 100)

let e = a % 100

let f = Math.floor(a / 100)

let g = Math.floor(d / 10)

let h = Math.floor(d % 10)

let i = Math.floor(f / 10)

let j = Math.floor(f % 10)

let k = Math.floor(g / 10)

let l = Math.floor(g % 10

Generation 4-14: In C

Write a program that shows a conversion table from miles to kilometers where one mile isequivalent to $1.609$ kilometers. The table should display the first ten positive numbersas miles and pair them with their respective kilometer representation.

↪→

↪→

If you want to learn how to use the built in functions, I recommend you start with them. Theycan be used to solve more than the exercise here.↪→

#include <stdio.h>

void main(){

int miles[10];

printf("Enter the first ten positive numbers as miles");

Page 58

Page 59: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

for (int i = 0; i < 10; i++)

scanf("%d", &miles[i]);

printf("\n\nThe following table shows the conversion table from miles to kilometers.\n");

printf("\nThe first 10 positive numbers are displayed as miles.\n");

for (int i = 0; i < 10; i++)

printf("%d\t%d\n", i, miles[i]);

}

### How to do it...

We need to declare `miles` as a `float` array. We can use the built in function `scanf()` toread the input.↪→

We can also use the built in function `printf()` to display the table. Note that we do not needto declare `printf()` as a function. This is↪→

Generation 4-15: Not codeWrite a program that shows a conversion table from miles to kilometers where one mile is

equivalent to $1.609$ kilometers. The table should display the first ten positive numbersas miles and pair them with their respective kilometer representation.

↪→

↪→

7.

Write a program that shows a conversion table from meters to miles where one meter isequivalent to $39.37$ inches. The table should display the first ten positive numbers asinches and pair them with their respective mile representation.

↪→

↪→

8.

Write a program that shows a conversion table from kilometers to miles where one kilometer isequivalent to $0.62$ miles. The table should display the first ten positive numbers askilometers and pair them with their respective mile representation.

↪→

↪→

9.

Write a program that shows a conversion table from yards to meters where one yard is equivalentto $↪→

D.5 Exercise 5:Write a program that accepts an integer and displays that integer with its digits shown in reverse. You should create and use amethod void reverse(int number) which will show the reversed-digit form of the parameterised number.Generation 5-1: Not codeWrite a Java program that accepts an integer and displays that integer with its digits shown in

reverse. You should create and use a method \textit{void reverse(int number)} which willshow the reversed-digit form of the parameterised number.

↪→

↪→

Use a for loop to print the digits of the number and use a method \textit{void printDigits(intnumber)} to print the digits.↪→

Sample inputs and outputs:

Input: 15 Output: 514

Page 59

Page 60: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

Input: 23 Output: 523

Input: 42 Output: 24

Input: 789 Output: 898

Input: 534 Output: 32

Input: -10 Output: -1

Input: 12345 Output: 2345

Input: -12345 Output: -2345

Input: -123456 Output: -

Generation 5-2: Not codeWrite a Java program that accepts an integer and displays that integer with its digits shown in

reverse. You should create and use a method \textit{void reverse(int number)} which willshow the reversed-digit form of the parameterised number.

↪→

↪→

Note: You can assume that the integer will have at least one digit, and will not be negative.

If you wish to use the numbers zero to nine for your digits, you may choose to define thedigits as a static final char[], or you may use an array of strings.↪→

For example, if the digits are defined as a static final char[], you could define them likethis:↪→

In this case, you would have to use a loop to access the array, and this is probably the mostinefficient method.↪→

However, if you use an array of strings, you can use

Generation 5-3: Not codeWrite a Java program that accepts an integer and displays that integer with its digits shown in

reverse. You should create and use a method \textit{void reverse(int number)} which willshow the reversed-digit form of the parameterised number. You should also use the built-inmethods for \textit{int} and \textit{String} and for \textit{boolean} to construct yourprogram.

↪→

↪→

↪→

↪→

You should implement the method \textit{void reverse(int number)} to show the reversed-digitform of the parameterised number and return the result. You should use the built-in method\textit{int toInteger(int i)} to convert the parameterised number to its integerrepresentation. You should use the built-in method \textit{int toDigits(int i)} to convertthe integer representation of the

↪→

↪→

↪→

↪→

Generation 5-4: In CWrite a Java program that accepts an integer and displays that integer with its digits shown in

reverse. You should create and use a method \textit{void reverse(int number)} which willshow the reversed-digit form of the parameterised number. For example, calling the methodon \texttt{3} will show \texttt{111} on the screen.

↪→

↪→

↪→

#include <stdio.h>

void reverse(int number)

{

Page 60

Page 61: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

int i, j;

for(i = number; i>0; i--)

{

j = number - i;

printf("%d", j);

}

}

\textbf{Exercise}

#include <stdio.h>

void reverse(int number)

{

int i, j;

for(i = number; i>0; i--)

{

j = number - i;

printf("%d", j);

}

}

\textbf{Exercise}

#include <stdio.h>

void reverse(int number)

{

int i, j;

for(i = number; i>0; i--)

{

j = number - i;

printf("%d", j);

}

}

Generation 5-5: Not code

Page 61

Page 62: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

Write a Java program that accepts an integer and displays that integer with its digits shown inreverse. You should create and use a method \textit{void reverse(int number)} which willshow the reversed-digit form of the parameterised number.

↪→

↪→

This is a bit difficult to explain because there is a lot of information to be conveyed.

The original integer is stored as a char array. The char array is reversed. The new reversedinteger is stored as a new char array. The new reversed integer is printed out.↪→

In order to perform this operation, you need to access the individual characters of theoriginal integer. This is done with the charAt method. You then need to change the value ofthe character to a '0' (using the charAt method again). This is done using the methodchr(x) to convert the character to an

↪→

↪→

↪→

Generation 5-6: Not codeWrite a Java program that accepts an integer and displays that integer with its digits shown in

reverse. You should create and use a method \textit{void reverse(int number)} which willshow the reversed-digit form of the parameterised number.

↪→

↪→

The method \textit{void reverse(int number)} should be of the following type:

\begin{java}void reverse(int number)\end{java}

The following \textit{main} method should be used to run the program.

\begin{java}int main()\end{java}

\textbf{Exercise:} Write the above code. Run it and test the program. You can use the method\textit{void reverse(int number)} and \textit{System.out.println()} to print↪→

Generation 5-7: IncorrectWrite a Java program that accepts an integer and displays that integer with its digits shown in

reverse. You should create and use a method \textit{void reverse(int number)} which willshow the reversed-digit form of the parameterised number.

↪→

↪→

Example:

Input: 5Output: 54321

Hint:

You can use the code of the following Java program as a starting point.

public class ReverseDigit {

public static void main(String[] args) {

int number = 5;

System.out.println(reverse(number));

}

public static void reverse(int number) {

Page 62

Page 63: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

int i = 0;

int j = number;

while (j!= 0) {

i++;

j = j / 10;

}

}

}

Hi, I am not sure about the solution you have mentioned. I think the solution should be likethis.↪→

1. I am not sure about the solution you have mentioned. I think the solution should be likethis.↪→

public class ReverseDigit {

public static void main(String[] args) {

int number = 5;

System.out.println(reverse(number));

}

public static void reverse(int number) {

int i = 0;

int j = number;

while (j!= 0) {

i++;

j = j / 10;

}

}

}

By looking at the question, I think the solution is in reverse(number) method.

public static void reverse(int number) {

int i = 0;

int j = number;

while (j!= 0) {

Page 63

Page 64: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

i++;

j = j / 10;

}

}

In the above code, we are using

Generation 5-8: No changes

Write a Java program that accepts an integer and displays that integer with its digits shown inreverse. You should create and use a method \textit{void reverse(int number)} which willshow the reversed-digit form of the parameterised number.

↪→

↪→

Solution:

import java.util.Scanner;

public class Test {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.println("Enter the number to reverse");

int num = sc.nextInt();

while (num > 0) {

System.out.print((num % 10));

num /= 10;

}

}

}

import java.util.Scanner;

public class Test {public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.println("Enter the number to reverse");int num = sc.nextInt();

while (num > 0) {System.out.print((num % 10));num /= 10;

}}

}

Generation 5-9: Not code

Page 64

Page 65: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

Write a Java program that accepts an integer and displays that integer with its digits shown inreverse. You should create and use a method \textit{void reverse(int number)} which willshow the reversed-digit form of the parameterised number. For example, if the parameterisednumber is 123456789, then the output should be displayed as 1! 2! 3! 4! 5! 6! 7! 8! 9!

↪→

↪→

↪→

Write a Java program that accepts a list of integers as input and returns the sum of all theelements of the list.↪→

Write a Java program that accepts a list of integers as input and returns the sum of all theelements of the list.↪→

Write a Java program that accepts a list of integers as input and returns the sum of all theelements of the list.↪→

Write a Java program that accepts a list of

Generation 5-10: Incorrect

Write a Java program that accepts an integer and displays that integer with its digits shown inreverse. You should create and use a method \textit{void reverse(int number)} which willshow the reversed-digit form of the parameterised number.

↪→

↪→

For example, if the number is 123, you should see \textit{2313} displayed.

You can assume the parameterised number is positive.

Your solution should be as follows:

import java.util.Scanner;

class ReverseDigits{

public static void main(String[] args){

Scanner input = new Scanner(System.in);

System.out.print("Enter an integer: ");

int number = input.nextInt();

reverse(number);

}

public static void reverse(int number){

// Write your code here

}

}

Here is the Output:

Enter an integer: 5

Your program will output:

5

Page 65

Page 66: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

2

1

0

The Output is the reverse of the given integer.

This Java program was created by me and is called ReverseDigits.java. You can check thesolution by using the following command line:↪→

java ReverseDigits

How to Compile and Run the Program

Compile the program using the following command:

javac ReverseDigits.java

Generation 5-11: Incorrect

Write a Java program that accepts an integer and displays that integer with its digits shown inreverse. You should create and use a method \textit{void reverse(int number)} which willshow the reversed-digit form of the parameterised number.

↪→

↪→

\begin{verbatim}import java.util.Scanner;public class Main{

public static void main(String[] args){

Scanner sc = new Scanner(System.in);int x = sc.nextInt();reverse(x);

}

public static void reverse(int number){

int a = number % 10;int b = number / 10;int c = number % 10;int d = number / 10;int e = number % 10;int f = number / 10;int g = number % 10;int h = number / 10;int i = number % 10;int j = number / 10;int k = number % 10;int l = number / 10;int m = number % 10;int n = number / 10;int o = number % 10;int p = number / 10;int q = number % 10;int r = number / 10;int s = number % 10;int t = number / 10;int u = number % 10;int v = number / 10;

Page 66

Page 67: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

int w = number % 10;int x = number / 10;int y = number % 10;int z = number / 10;int A = a;int B = b;int C = c;int D = d;int E = e;int F = f;int G = g;int H = h;int I = i;int J = j;int K = k;int L = l;int M = m;int N = n;int O = o;int P = p;int Q = q;int R = r;int S = s;int T = t;int U = u;int V = v;int W = w;int X = x;int Y = y;int Z = z;String s = String.format("%d", A);

Generation 5-12: Not code

Write a Java program that accepts an integer and displays that integer with its digits shown inreverse. You should create and use a method \textit{void reverse(int number)} which willshow the reversed-digit form of the parameterised number.

↪→

↪→

\begin{itemize}\item\textbf{Input:} An integer number to be displayed in reverse.\item\textbf{Output:} The reversed-digit form of the parameterised number.\end{itemize}

\textbf{Exercise:} Write the method \textit{void reverse(int number)} to display the number inreverse.↪→

\begin{itemize}\item\textbf{Input:} An integer number to be displayed in reverse.\item\textbf{Output:} The reversed-digit form of the parameterised number.\end{itemize}

\textbf{Exercise:} Write the method \textit{void reverse(int number)} to display the number inreverse.↪→

\begin{itemize}\item\textbf{Input:} An integer number to be displayed in reverse.\item\textbf{Output:} The reversed-digit form of the parameterised number.\end{itemize}

Page 67

Page 68: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

\textbf{Exercise:} Write the method \textit{void reverse(int number)} to display the number inreverse.↪→

Generation 5-13: Not codeWrite a Java program that accepts an integer and displays that integer with its digits shown in

reverse. You should create and use a method \textit{void reverse(int number)} which willshow the reversed-digit form of the parameterised number.

↪→

↪→

\begin{itemize}\item[i)]Write a method \textit{void display(int number)} which will print the number on a single line.\end{itemize}

\end{frame}

\begin{frame}\frametitle{Data Structure}

We will use \textit{java.lang.String} data type to store our information.

\begin{itemize}\item[i)]String is an immutable type, it cannot be changed.\item[ii)]String is a class which contains all the methods to manipulate strings.\item[iii)]String is an object and can be assigned to variables of type \textit{String}.\item[iv)]String is a subclass of \textit{Object}.\item[v)]We can use \textit{String.split()} method to split a string into an array of strings.\item[vi)]We can use \textit{String.replace()} method to replace one or more characters in a string.\item[vii)]We can use \textit{String.

Generation 5-14: Not codeWrite a Java program that accepts an integer and displays that integer with its digits shown in

reverse. You should create and use a method \textit{void reverse(int number)} which willshow the reversed-digit form of the parameterised number.

↪→

↪→

Write a Java program that accepts a number from the user and displays the number as a list ofits digits. The list of digits should be printed in the same order as the digits in thenumber.

↪→

↪→

Write a Java program that accepts a number from the user and displays the number as a list ofits digits. The list of digits should be printed in the same order as the digits in thenumber.

↪→

↪→

Write a Java program that accepts a number from the user and displays the number as a list ofits digits. The list of digits should be printed in the same order as the digits in thenumber.

↪→

↪→

Generation 5-15: IncorrectWrite a Java program that accepts an integer and displays that integer with its digits shown in

reverse. You should create and use a method \textit{void reverse(int number)} which willshow the reversed-digit form of the parameterised number.

↪→

↪→

Solution

Page 68

Page 69: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

First, we can get the binary representation of the number by converting it to a string with themethod \textit{String.valueOf(int)} and then we can reverse the digits by using the method\textit{String.substring(int start, int end)} and changing the position of the substring.Finally, we can convert the string back to the integer value with the method\textit{int.parseInt(String)} and we will get the reversed integer.

↪→

↪→

↪→

↪→

Let’s take an example to see how we can reverse a number.

Suppose we have a number with binary representation 10010101 and we want to reverse it.

So, the number with binary representation 10010101 is equal to 12.

Thus, we can get the reversed-digit form of the number with the method\textit{String.substring(int start, int end)}.↪→

In our case, the \textit{start} is equal to 2 and the \textit{end} is equal to 3.

Thus, we get the reversed form of the number with the method \textit{String.substring(2, 3)}.

Now, we can convert the string to integer by using the method \textit{int.parseInt(String)} andthe result will be equal to 12.↪→

Thus, we have created a method \textit{void reverse(int number)} which will show thereversed-digit form of the parameterised number.↪→

For example, we can write the following program to show the reversed-digit form of the number12.↪→

importjava.util.Scanner;publicclass ReversedDigits{publicstaticvoid main(String[]args){Scannerinput=newScanner(System.in);System.out.println("Enter a number: ");intnumber=input.nextInt();String reversed=newString();int length=number/10;int start=2;intend=number%10;for(inti=length-1;i>=0;i--)reversed+=String.valueOf(number%10)+"";System.out.println(reversed);}}

↪→

↪→

↪→

↪→

Write a Java program that accepts a list of integer numbers and display the sum of all numbersin the list. You should create and use a method \textit{void sum(int[] numbers)} which willreturn the sum of all elements of the list of integers.

↪→

↪→

Solution

First, we need to get the sum of all the elements in the list.

For this purpose, we need to use the method \textit{int sum(int[] numbers)} and we can get thesum of all the elements in the list by changing the position of the method \textit{intsum(int[] numbers)}.

↪→

↪→

So, we can get the sum of all the elements in the list by using the method \textit{intsum(int[] numbers)} and we can↪→

D.6 Exercise 6:Write a program that accepts 10 integers and shows them in reversed order.

Generation 6-1: No changesWrite a Java program that accepts 10 integers and shows them in reversed order.

This program is quite easy to implement, you just need to create a list of 10 integers and thenreverse it.↪→

The following program demonstrates the solution.

Page 69

Page 70: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

import java.util.Scanner; import java.io.IOException; public class Solution { public staticvoid main(String[] args) { Scanner s = new Scanner(System.in); System.out.println("Enter 10numbers"); int[] nums = new int[10]; for (int i = 0; i < 10; i++) { s.nextInt(); nums[i] =s.nextInt(); } for (int i = nums.length - 1; i >= 0; i--) { System.out.print(nums[i]); } } }

↪→

↪→

↪→

Click here to see solution on ideone

This solution is pretty simple, but it can be improved a bit.

As we can see, the solution uses an array of integers.

The size of this array is 10.

This array is filled with 10 integers.

We loop through the array and print out the numbers.

So, we have 10 numbers in our array.

If we print them,

import java.util.Scanner;import java.io.IOException;

public class Solution {public static void main(String[] args) {

Scanner s = new Scanner(System.in);System.out.println("Enter 10 numbers");int[] nums = new int[10];for (int i = 0; i < 10; i++) {

s.nextInt(); nums[i] = s.nextInt();}for(int i = nums.length - 1; i >= 0; i--) {

System.out.print(nums[i]);}

}}

Generation 6-2: No changesWrite a Java program that accepts 10 integers and shows them in reversed order.

I have written a java program that accepts 10 integers and shows them in reversed order. I amstuck at a problem that I have to print the same numbers as the input. But the output isnot as expected.

↪→

↪→

import java.util.Scanner;public class Prog3{

public static void main(String args[]){Scanner in = new Scanner(System.in);int[] arr;int i=0;arr = new int[10];for(int a = 0;a<=9;a++){

arr[a] = in.nextInt();}for(i=0;i<10;i++){

System.out.print(arr[i]);}

}

Page 70

Page 71: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

}

import java.util.Scanner;public class Prog3{

public static void main(String args[]){Scanner in = new Scanner(System.in);int[] arr;int i=0;arr = new int[10];for(int a = 0;a<=9;a++){

arr[a] = in.nextInt();}for(i=0;i<10;i++){

System.out.print(arr[i]);}

}}

Generation 6-3: In CWrite a Java program that accepts 10 integers and shows them in reversed order.

Sample input:

3 2 1

Sample output:

1 2 3

#include <iostream>#include <vector>

using namespace std;

int main(){

vector<int> input;

cin >> input;

// Reverse the order of the numbers in the vector

reverse(input.begin(), input.end());

// Output the numbers

cout << endl << "The numbers in reverse order are: ";

for (int i = input.size() - 1; i >= 0; i--)

cout << input[i] << endl;

return 0;

}

The above program can be used to reverse the order of the numbers stored in a vector. In theprogram, the vector input is initialized to store the input 10 integers and the reversedorder of the vector is shown using cout.

↪→

↪→

Page 71

Page 72: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

If you find the above program too lengthy and difficult to understand, you can use a morecompact program.↪→

We can use a combination of std::reverse and std::copy to achieve the above task.

The first step is to store the input 10 integers in

Generation 6-4: Misc. error

Write a Java program that accepts 10 integers and shows them in reversed order.

I have written a program that takes 10 integers and shows them in reverse order. However, thereis a bug in my code that I don't know how to fix. It has to do with the way I'm using theRandom class. If anyone could help me fix this, I would appreciate it. Here is my code:

↪→

↪→

public class TenNumbers {

public static void main(String[] args) {

int[] numbers = new int[10];

System.out.print("Enter 10 integers in reverse order: ");

for (int i = 0; i < numbers.length; i++) {

numbers[i] = Integer.parseInt(

JOptionPane.showInputDialog(null,

"Enter a number: "));

}

for (int i = numbers.length - 1; i >= 0; i--) {

System.out.print(numbers[i] + " ");

}

}

}

When I run the program, the output is not correct. Here is an example of what it is supposed tolook like:↪→

Enter 10 integers in reverse order: 2 3 1 4 5 6 7 8 9

The output that it is giving me is:

9 8 7 6 5 4 3 2 1

A:

Your loop is going to the wrong end.You can either do for(i=numbers.length-1; i>=0; i--) or if you want to do it by index, do

for(int i=numbers.length-1; i>=0; i--){System.out.print(numbers[i] + " ");}.↪→

If you want to go from 0-9 in reverse order, you can do for(int i=0; i<10;i++){System.out.print(numbers[i] + " ");}↪→

Page 72

Page 73: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

A:

In your for loop, the last value of i is going to be the length of the array, so you willalways be looping over the last item in the array. You should be looping from 0 to 9inclusive:

↪→

↪→

for (int i = 0; i < numbers.length; i++) {//...

}

import javax.swing.*;

public class TenNumbers {

public static void main(String[] args) {

int[] numbers = new int[10];

System.out.print("Enter 10 integers to reverse: ");

for (int i = 0; i < numbers.length; i++) {numbers[i] = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter

a number: "));↪→

}

for (int i = numbers.length - 1; i >= 0; i--) {System.out.print(numbers[i] + " ");

}}

}

Generation 6-5: Misc. errorWrite a Java program that accepts 10 integers and shows them in reversed order.

My attempt:import java.util.Scanner;

public class Test {

public static void main(String[] args) {Scanner sc = new Scanner(System.in);

int[] num = new int[10];

System.out.println("Enter the numbers in reverse order");for (int i = 0; i < num.length; i++) {

num[i] = sc.nextInt();}

for (int i = num.length - 1; i >= 0; i--) {System.out.print(num[i] + " ");

}}

}

A:

Use Collections.sort() to sort an array of ints in ascending order.

Page 73

Page 74: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

Collections.sort(array);

A:

Use Collections.sort(arr);This will sort in ascending order.

Scanner sc = new Scanner(System.in);

int[] num = new int[10];

System.out.println("Enter the numbers in reverse order");for (int i = 0; i < num.length; i++) {

num[i] = sc.nextInt();}

Collections.sort(num);for (int i = num.length - 1; i >= 0; i--) {

System.out.print(num[i] + " ");}

}

}

}

}

}

}

}

}

}

}

}

}

}

}

}

}

}

}

import java.util.Scanner;

Page 74

Page 75: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

public class Test {

public static void main(String[] args) {Scanner sc = new Scanner(System.in);

int[] num = new int[10];

System.out.println("Enter the numbers to reverse");for (int i = 0; i < num.length; i++) {

num[i] = sc.nextInt();}

for (int i = num.length - 1; i >= 0; i--) {System.out.print(num[i] + " ");

}}

}

Generation 6-6: Misc. error

Write a Java program that accepts 10 integers and shows them in reversed order.

In the following code snippet I've used a while loop to accept 10 integers from the user andstore it in the array int[] a. I've used Arrays.sort() method to reverse the array. Theloop is terminated when the array is sorted. I'm expecting the output to be like this :

↪→

↪→

8 1 2 7 3 4 5 6 10 9

and the code is as follows :

import java.util.Scanner;

public class JavaProgram

{

public static void main (String args[])

{

int[] a;

Scanner sc = new Scanner(System.in);

System.out.println("Enter 10 integers");

a = new int[10];

while(sc.hasNext())

{

a[sc.nextInt()-1] = sc.nextInt();

}

System.out.println(Arrays.sort(a));

}

Page 75

Page 76: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

}

But the output is :

10 9 8 1 2 7 3 4 5 6

What is the problem with the code?

It is the first time I'm working with arrays and I

Generation 6-7: Incorrect

Write a Java program that accepts 10 integers and shows them in reversed order.

Answers

You can use java.util.Arrays class to sort any array of data.

String[] array = new String[10];

Arrays.sort(array);

for (String s : array) {

System.out.println(s);

}

//output will be as below

//9 8 7 6 5 4 3 2 1 0

You can use Collections.reverse() method to reverse the order of the elements of an array.

Arrays.sort(array);

Collections.reverse(array);

for (String s : array) {

System.out.println(s);

}

//output will be as below

//0 1 2 3 4 5 6 7 8 9

How to make the code dynamic?

The code will work fine, but if the number of integers to be sorted is dynamic then we can usea for loop.↪→

int i = 0;

for (i = 0; i < array.length; i++) {

Arrays.sort(array);

Page 76

Page 77: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

Collections.reverse(array);

for (String s : array) {

System.out.println(s);

}

}

The output will be as below

//0 1 2 3 4 5 6 7 8 9

I want to sort the values of the array in descending order.

We can use Arrays.sort() method with negative comparator.

Arrays.sort(array, new Comparator<Integer>() {

public int compare(Integer a, Integer b) {

return b.intValue() - a.intValue();

}

});

Generation 6-8: No changes

Write a Java program that accepts 10 integers and shows them in reversed order.

Question

Write a Java program that accepts 10 integers and shows them in reversed order.

What is the output?

Answer

Solution

import java.util.Scanner;

class Solution {

public static void main(String args[]) {

Scanner sc = new Scanner(System.in);

int[] array = new int[10];

System.out.println("Enter 10 numbers one by one");

for(int i=0; i<10; i++) {

array[i] = sc.nextInt();

}

Page 77

Page 78: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

for(int i=9; i>=0; i--) {

System.out.print(array[i] + " ");

}

}

}

Solution

Solution

import java.util.Scanner;

class Solution {

public static void main(String args[]) {

Scanner sc = new Scanner(System.in);

int[] array = new int[10];

System.out.println("Enter 10 numbers one by one");

for(int i=0; i<10; i++) {

array[i] = sc.nextInt();

}

for(int i=0; i<10; i++) {

System.out.print(array[i] + " ");

}

}

}

Solution

import java.util.Scanner;

class Solution {

public static void main(String args[]) {

Scanner sc = new Scanner(System.in);

int[] array = new int[10];

System.out.println("Enter 10 numbers one by one");

for(int i=0; i<10; i++) {

array[i] = sc.nextInt();

Page 78

Page 79: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

}

for(int i=9; i>=0; i--) {

System.out.print(array[i] + " ");

}

}

}

Solution

Solution

import java.util.Scanner;

class Solution {

public static void main(String args[]) {

Scanner sc = new Scanner(System.in);

import java.util.Scanner;

class Solution {

public static void main(String args[]) {

Scanner sc = new Scanner(System.in);int[] array = new int[10];System.out.println("Enter 10 numbers one by one");

for(int i=0; i<10; i++) {array[i] = sc.nextInt();

}

for(int i=9; i>=0; i--) {System.out.print(array[i] + " ");

}}

}

Generation 6-9: No changesWrite a Java program that accepts 10 integers and shows them in reversed order. The integers

must be stored in an array. The integer is read as a string and stored in a variable namedString nums[] = new String[10]; and the string is converted to int.

↪→

↪→

You are not required to print the array in reverse order.

This is how you can do it:

import java.util.*;

public class Reversed

{

Page 79

Page 80: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

public static void main(String[] args)

{

Scanner sc = new Scanner(System.in);

System.out.println("Enter 10 integers");

int[] nums = new int[10];

for (int i = 0; i < nums.length; i++)

nums[i] = sc.nextInt();

for (int i = nums.length - 1; i >= 0; i--)

System.out.println(nums[i]);

}

}

The output will be:

Enter 10 integers

2 4 6 8 1 5 7 0 9

##### **Printing a Character**

In this section, you will create a Java program that prints a character from a

import java.util.*;

public class Reversed {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);System.out.println("Enter 10 integers");int[] nums = new int[10];

for (int i = 0; i < nums.length; i++)nums[i] = sc.nextInt();

for (int i = nums.length - 1; i >= 0; i--)System.out.println(nums[i]);

}

}

Generation 6-10: Not codeWrite a Java program that accepts 10 integers and shows them in reversed order.

The main method accepts 10 integers from the user. The main method uses awhile loop to keep asking the user for integers until the user enters -1.The method then uses a for loop to display the 10 integers in reverse order.

Write a Java program that accepts 10 integers and shows them in ascendingorder.

Page 80

Page 81: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

The main method accepts 10 integers from the user. The main method uses awhile loop to keep asking the user for integers until the user enters -1.The method then uses a for loop to display the 10 integers in ascendingorder.

Write a Java program that

Generation 6-11: Incorrect

Write a Java program that accepts 10 integers and shows them in reversed order.

Input

The first line of the input file contains 10 positive integers separated by white space.

Output

The output file contains the 10 integers in reversed order.

I have tried the below code but it's not giving the output

Code:

import java.io.BufferedReader;import java.io.FileReader;import java.io.IOException;import java.io.PrintWriter;import java.util.Arrays;import java.util.Scanner;

public class ReversedOrder {

static String[] input;

static int[] number = new int[10];

static int[] numberRev = new int[10];

public static void main(String[] args) {

BufferedReader reader = new BufferedReader(new FileReader("input.txt"));

PrintWriter writer = new PrintWriter("output.txt");

for(int i=0; i<input.length; i++){

String line = reader.readLine();

int[] numbers = Arrays.stream(line.split(" ")).mapToInt(Integer::parseInt).toArray();

for(int j=numbers.length-1; j>=0; j--){

number[i] = numbers[j];

numberRev[i] = number[i];

}

}

Page 81

Page 82: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

Arrays.sort(numberRev);

for(int i=0; i<numberRev.length; i++){

System.out.println(numberRev[i]);

}

writer.close();

}

}

It's giving the output in ascending order

Generation 6-12: Partially correct (doesn’t read an input)Write a Java program that accepts 10 integers and shows them in reversed order.

We can use a for loop to reverse the elements in an array. The code will look like this:

public class ForLoopExample {

public static void main(String[] args) {

int[] numbers = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

int[] numbersReversed = new int[numbers.length];

for (int i = numbers.length - 1; i > 0; i--) {

numbersReversed[i] = numbers[i];

}

System.out.println(Arrays.toString(numbersReversed));

}

}

As you can see, we use a for loop to loop through all the elements of the array and store thereversed elements in the numbersReversed array.↪→

Let’s see what the output will be in the console:

[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

The code above is working fine, but the problem is, the output is getting printed in the sameorder as the original↪→

Generation 6-13: Partially correct (doesn’t read an input)Write a Java program that accepts 10 integers and shows them in reversed order.

for example:

1023

Page 82

Page 83: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

4567891

A:

This program will give the result in reverse orderpublic class Main {

public static void main(String[] args) {

int[] a = new int[] {10, 2, 3, 4, 5, 6, 7, 8, 9, 1};

int i = 0;

while (i < a.length) {

System.out.print(a[i]);

i++;}

System.out.println();}

}

A:

public class ReverseInts {public static void main(String[] args) {

int[] ints = { 10, 2, 3, 4, 5, 6, 7, 8, 9, 1 };

int i = 0;

while (i < ints.length) {System.out.print(ints[i]);i++;

}}

}

A:

public static void main(String[] args) {int[] a = new int[] {10, 2, 3, 4, 5, 6, 7, 8, 9, 1};

for(int i = a.length-1; i >= 0; i--) {System.out.print(a[i]);

}}

Generation 6-14: Incorrect

Page 83

Page 84: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

Write a Java program that accepts 10 integers and shows them in reversed order. You should doit using Java's Collections Framework.↪→

Here is the code for the Java program:

public class Solution {

public static void main(String[] args) {

int[] numbers = {1,2,3,4,5,6,7,8,9,10};

System.out.println("Reversed order of the numbers is:");

Collections.sort(numbers);

for(int i=0;i<10;i++){

System.out.println(numbers[i]);

}

}

}

Here is the output of the program:

Reversed order of the numbers is:

10 9 8 7 6 5 4 3 2 1

How to solve the problem?

Solution 1: Create a class that implements the Comparable interface. The class should have acompareTo() method. The method should return a negative value if the first argument issmaller than the second argument, and should return a positive value if the first argumentis larger than the second argument.

↪→

↪→

↪→

The class should have a method that returns a negative value if the first argument is smallerthan the↪→

Generation 6-15: Off by one error

Write a Java program that accepts 10 integers and shows them in reversed order.

The below is the input and output as shown in the output.

Input:

1 2 3 4 5 6 7 8 9 10

Output:

10 9 8 7 6 5 4 3 2 1

import java.io.*;

public class ReversedInput

{

Page 84

Page 85: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

public static void main(String args[])throws IOException

{

System.out.println("Enter the numbers to be reversed: ");

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

int[] array = new int[10];

for(int i=0;i<10;i++)

{

array[i] = Integer.parseInt(br.readLine());

}

for(int i=10;i>0;i--)

System.out.println(array[i]);

}

}

Answer:

import java.io.*;

public class ReversedInput

{

public static void main(String args[])throws IOException

{

System.out.println("Enter the numbers to be reversed: ");

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

int[] array = new int[10];

for(int i=0;i<10;i++)

{

array[i] = Integer.parseInt(br.readLine());

}

for(int i=10;i>0;i--)

System.out.println(array[i]);

}

Page 85

Page 86: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

}

Output:

Enter the numbers to be reversed: 1 2 3 4

import java.io.*;

public class ReversedInput {public static void main(String args[])throws IOException {

System.out.println("Enter the numbers to be reversed: ");BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

int[] array = new int[10];for(int i=0;i<10;i++) {

array[i] = Integer.parseInt(br.readLine());}

for(int i=9;i>=0;i--) {System.out.println(array[i]);

}}

}

D.7 Exercise 7:Write a program that accepts a 4× 4 matrix of real numbers and prints the total of all numbers placed on the leading diagonalof the matrix. You should create and use a method double sumMajorDiagonal(double[][] m) which will return the total of allnumbers placed on the leading diagonal of the parameterised matrix.Generation 7-1: Not codeWrite a Java program that accepts a $4\times 4$ matrix of real numbers and prints the total of

all numbers placed on the leading diagonal of the matrix. You should create and use amethod \textit{double sumMajorDiagonal(double[][] m)} which will return the total of allnumbers placed on the leading diagonal of the parameterised matrix.

↪→

↪→

↪→

Solution

To sum the numbers on the leading diagonal, we can find the sum of all numbers on the diagonaland subtract the diagonal numbers from it.↪→

If we find the sum of all numbers on the diagonal, we will have a formula to calculate the sumof all numbers on the diagonal.↪→

We can use the formula for the sum of the diagonal numbers to calculate the sum of all numberson the diagonal.↪→

Now we have the sum of all numbers on the diagonal, we can subtract the diagonal numbers fromthe sum.↪→

So we will have the total sum of numbers on the diagonal.

Generation 7-2: Not codeWrite a Java program that accepts a $4\times 4$ matrix of real numbers and prints the total of

all numbers placed on the leading diagonal of the matrix. You should create and use amethod \textit{double sumMajorDiagonal(double[][] m)} which will return the total of allnumbers placed on the leading diagonal of the parameterised matrix.

↪→

↪→

↪→

Write a Java program that accepts a $4\times 4$ matrix of real numbers and prints the total ofall numbers placed on the leading diagonal of the matrix. You should create and use amethod \textit{double sumMajorDiagonal(double[][] m)} which will return the total of allnumbers placed on the leading diagonal of the parameterised matrix.

↪→

↪→

↪→

Page 86

Page 87: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

Write a Java program that accepts a $4\times 4$ matrix of real numbers and prints the total ofall numbers placed on the leading diagonal of the matrix. You should create and use amethod \textit{double sumMajorDiagonal

↪→

↪→

Generation 7-3: Not codeWrite a Java program that accepts a $4\times 4$ matrix of real numbers and prints the total of

all numbers placed on the leading diagonal of the matrix. You should create and use amethod \textit{double sumMajorDiagonal(double[][] m)} which will return the total of allnumbers placed on the leading diagonal of the parameterised matrix.

↪→

↪→

↪→

The following is an example of a matrix.

\begin{array}{lcccccc}1 & 1 & 1 & 1 \\1 & 1 & 1 & 1 \\1 & 1 & 1 & 1 \\1 & 1 & 1 & 1 \\\end{array}

Explanation:

The leading diagonal has two 1's and four 0's. The total of the numbers on the leading diagonalis 3 + 4 + 4 + 4 + 4 + 4 + 4 + 4 + 4 + 4 + 4 + 4 + 4 + 4 + 4 + 4 +↪→

Generation 7-4: Not codeWrite a Java program that accepts a $4\times 4$ matrix of real numbers and prints the total of

all numbers placed on the leading diagonal of the matrix. You should create and use amethod \textit{double sumMajorDiagonal(double[][] m)} which will return the total of allnumbers placed on the leading diagonal of the parameterised matrix.

↪→

↪→

↪→

Write a Java program that accepts a $4\times 4$ matrix of real numbers and prints the sum ofall numbers placed on the leading diagonal of the matrix. You should create and use amethod \textit{double sumLeadingDiagonal(double[][] m)} which will return the sum of allnumbers placed on the leading diagonal of the parameterised matrix.

↪→

↪→

↪→

Write a Java program that accepts a $4\times 4$ matrix of real numbers and prints the total ofall numbers placed on the leading diagonal of the matrix. You should create and use amethod \textit{double sumLeading

↪→

↪→

Generation 7-5: No changesWrite a Java program that accepts a $4\times 4$ matrix of real numbers and prints the total of

all numbers placed on the leading diagonal of the matrix. You should create and use amethod \textit{double sumMajorDiagonal(double[][] m)} which will return the total of allnumbers placed on the leading diagonal of the parameterised matrix. You should test yourprogram with the following input:

↪→

↪→

↪→

↪→

$\begin{bmatrix}1 & 2 & 3 & 4 \\5 & 6 & 7 & 8 \\9 & 10 & 11 & 12 \\13 & 14 & 15 & 16\end{bmatrix}$

Do not use arrays to store your data.

What is your solution? (you can use any method of your choice)

I have tried to solve this problem with a method but it is not giving the correct answer

Page 87

Page 88: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

My solution:import java.util.Scanner;public class FindSumOfMajorDiagonal {public static void main(String[] args) {

Scanner sc = new Scanner(System.in);double[][] array = new double[4][4];int i = 0;int j = 0;for(i = 0; i < array.length; i++)

for(j = 0; j < array[i].length; j++)array[i][j] = sc.nextDouble();

double total = 0;for(i = 0; i < array.length; i++)

total += array[i][i];System.out.println(total);}

}

A:

For loop is not necessary for this. You can use a single line method.double sumMajorDiagonal(double[][] m) {

double total = 0;for(int i = 0; i < m.length; i++)

total += m[i][i];return total;

}

And you can test it like this.public static void main(String[] args) {

double[][] matrix = {{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};double total = sumMajorDiagonal(matrix);System.out.println(total);

}

double total = sumMajorDiagonal(matrix);System.out.println(total);

double total = sumMajorDiagonal(matrix);System.out.println(total);

This will print out:

696969

Note: I have removed the redundant variable declarations.

double total = sumMajorDiagonal(matrix);System.out.println(total);

This will print out:

696969

Note: You can put the variable declarations back in as

Page 88

Page 89: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

import java.util.Scanner;public class FindSumOfMajorDiagonal {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);double[][] array = new double[4][4];

int i = 0;int j = 0;for(i = 0; i < array.length; i++) {

for(j = 0; j < array[i].length; j++) {array[i][j] = sc.nextDouble();

}}

double total = 0;for(i = 0; i < array.length; i++) {

total += array[i][i];}System.out.println(total);

}}

Generation 7-6: Not codeWrite a Java program that accepts a $4\times 4$ matrix of real numbers and prints the total of

all numbers placed on the leading diagonal of the matrix. You should create and use amethod \textit{double sumMajorDiagonal(double[][] m)} which will return the total of allnumbers placed on the leading diagonal of the parameterised matrix.

↪→

↪→

↪→

\begin{Dice}\dice{totalMajorDiagonal}

\end{Dice}

\begin{problem}Write a Java program that accepts a $4\times 4$ matrix of real numbers and prints the total

of all numbers placed on the leading diagonal of the matrix. You should create and use amethod \textit{double sumMajorDiagonal(double[][] m)} which will return the total of allnumbers placed on the leading diagonal of the parameterised matrix.

↪→

↪→

↪→

\begin{Dice}\dice{totalMajorDiagonal

Generation 7-7: Not codeWrite a Java program that accepts a $4\times 4$ matrix of real numbers and prints the total of

all numbers placed on the leading diagonal of the matrix. You should create and use amethod \textit{double sumMajorDiagonal(double[][] m)} which will return the total of allnumbers placed on the leading diagonal of the parameterised matrix.

↪→

↪→

↪→

This is an exercise from \OJ 101: Java Programming", a book by Paul Wilson and Robin Hunter. Itis the fourth exercise of the first chapter.↪→

Please note that the matrix of numbers is not assumed to be symmetrical. For example, thefollowing is a legal matrix:↪→

The matrix is represented as an array of doubles. The length of the matrix should be equal tothe length of the array, and the first element of the array should contain the first row ofthe matrix. The array should be read-only and should not be modified.

↪→

↪→

We can express the program as a method of the class \textit{SumMajorDiagonal} and pass thearray \textit{m} to the method. The following is an example of the solution:↪→

Page 89

Page 90: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

This is a good way to start working on a Java program, and it is not a bad idea to start byusing a similar approach in another language, say C++. We can do this for example by usingthe \texttt{std::vector} class in C++.

↪→

↪→

In this example, we use a \texttt{std::vector} as a temporary variable to store the numbers inthe leading diagonal of the parameter↪→

Generation 7-8: Not code

Write a Java program that accepts a $4\times 4$ matrix of real numbers and prints the total ofall numbers placed on the leading diagonal of the matrix. You should create and use amethod \textit{double sumMajorDiagonal(double[][] m)} which will return the total of allnumbers placed on the leading diagonal of the parameterised matrix.

↪→

↪→

↪→

2. Write a Java program that accepts an array of $4\times 4$ matrices of real numbers andprints the sum of all numbers placed on the leading diagonals of all the matrices. Youshould create and use a method \textit{double[][] sumAllMajorDiagonals(double[][][] m)}which will return the sum of all numbers placed on the leading diagonals of theparameterised matrices.

↪→

↪→

↪→

↪→

3. Write a Java program that accepts an array of $4\times 4$ matrices of real numbers andprints the sum of all numbers placed on↪→

Generation 7-9: Not code

Write a Java program that accepts a $4\times 4$ matrix of real numbers and prints the total ofall numbers placed on the leading diagonal of the matrix. You should create and use amethod \textit{double sumMajorDiagonal(double[][] m)} which will return the total of allnumbers placed on the leading diagonal of the parameterised matrix.

↪→

↪→

↪→

For example, if we pass the following matrix as an argument to your method:$$\left[\begin{matrix}1&2&3&4\\1&3&5&7\\2&4&6&8\\3&5&7&9\end{matrix}\right]$$You should output the number $58$.You may write a function \textit{double sumMajorDiagonal(double[][] m)} which will return the

total of all numbers placed on the leading diagonal of the parameterised matrix.↪→

Input

An array \

Generation 7-10: Not code

Write a Java program that accepts a $4\times 4$ matrix of real numbers and prints the total ofall numbers placed on the leading diagonal of the matrix. You should create and use amethod \textit{double sumMajorDiagonal(double[][] m)} which will return the total of allnumbers placed on the leading diagonal of the parameterised matrix. You should then createa method \textit{double sumMinorDiagonal(double[][] m)} which will return the total of allnumbers placed on the minor diagonal of the parameterised matrix.

↪→

↪→

↪→

↪→

↪→

\textbf{Input}\begin{enumerate}\itemAn $n\times n$ matrix of real numbers. The first row is the top row and the last row is the

bottom row.↪→

\itemThe parameter $k$ which will be the number of rows on the matrix.

\itemThe parameter $r$ which will be the number

Page 90

Page 91: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

Generation 7-11: Not codeWrite a Java program that accepts a $4\times 4$ matrix of real numbers and prints the total of

all numbers placed on the leading diagonal of the matrix. You should create and use amethod \textit{double sumMajorDiagonal(double[][] m)} which will return the total of allnumbers placed on the leading diagonal of the parameterised matrix.

↪→

↪→

↪→

Write a Java program that accepts a $4\times 4$ matrix of real numbers and prints the sum ofall numbers in the leading diagonal. You should create and use a method \textit{doublesumDiagonal(double[][] m)} which will return the sum of all numbers in the leading diagonalof the parameterised matrix.

↪→

↪→

↪→

Write a Java program that accepts a $4\times 4$ matrix of real numbers and prints the sum ofall numbers in the leading diagonal. You should create and use a method \textit{doublesumDiagonal(double[][] m)} which will return the

↪→

↪→

Generation 7-12: Not codeWrite a Java program that accepts a $4\times 4$ matrix of real numbers and prints the total of

all numbers placed on the leading diagonal of the matrix. You should create and use amethod \textit{double sumMajorDiagonal(double[][] m)} which will return the total of allnumbers placed on the leading diagonal of the parameterised matrix.

↪→

↪→

↪→

Your program should contain:

- a main method which prompts the user to enter a matrix- a method that prompts the user to enter values for each cell of the matrix- a method that calculates the total of all numbers placed on the leading diagonal- a method that calculates the sum of all numbers in the matrix.

All input and output operations must be via the console.

The method \textit{double sumMajorDiagonal(double[][] m)} should take a parameterised matrix asan input, and should return the sum of all numbers placed on the leading diagonal of thematrix.

↪→

↪→

You may write a separate method for calculating the sum of all numbers in the matrix, but youshould include it as part of the method \textit{double sumMajorDiagonal(double[][] m)}.↪→

You may use any method you like to calculate the sum of all numbers in the matrix, but you mustmake sure that the method you use is correct and that it is also correct when the matrixhas values other than numbers.

↪→

↪→

**Extra Credit**

The method \textit{double sumMajorDiagonal(double[][] m)}

Generation 7-13: No changesWrite a Java program that accepts a $4\times 4$ matrix of real numbers and prints the total of

all numbers placed on the leading diagonal of the matrix. You should create and use amethod \textit{double sumMajorDiagonal(double[][] m)} which will return the total of allnumbers placed on the leading diagonal of the parameterised matrix.

↪→

↪→

↪→

import java.util.Scanner;

public class Coding_comp_challenge {

public static void main(String[] args) {Scanner sc = new Scanner(System.in);System.out.println("Enter a $4\times 4$ matrix of real numbers");double[][] m = new double[4][4];

Page 91

Page 92: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

double sum = 0.0;for (int row = 0; row < 4; row++) {

for (int column = 0; column < 4; column++) {m[row][column] = sc.nextDouble();

}}for (int row = 0; row < 4; row++) {

sum += m[col][row];}System.out.println("The sum of the numbers on the leading diagonal is: " + sum);

}}

import java.util.Scanner;

public class Coding_comp_challenge {

public static void main(String[] args) {Scanner sc = new Scanner(System.in);System.out.println("Enter a $4\times 4$ matrix of real numbers");double[][] m = new double[4][4];double sum = 0.0;for (int row = 0; row < 4; row++) {

for (int column = 0; column < 4; column++) {m[row][column] = sc.nextDouble();

}}for (int row = 0; row < 4; row++) {

sum += m[row][row];}System.out.println("The sum of the numbers on the leading diagonal is: " + sum);

}}

Generation 7-14: Not codeWrite a Java program that accepts a $4\times 4$ matrix of real numbers and prints the total of

all numbers placed on the leading diagonal of the matrix. You should create and use amethod \textit{double sumMajorDiagonal(double[][] m)} which will return the total of allnumbers placed on the leading diagonal of the parameterised matrix.

↪→

↪→

↪→

For example, if the input is:$$\begin{bmatrix} 1 & 1 & 1 & 1 \\ 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0

\end{bmatrix}$$↪→

the output should be:$$\begin{bmatrix} 1 & 1 & 1 & 1 \\ 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0

\end{bmatrix} \rightarrow 6$$↪→

Please write the code for the above example.

I'm having a problem with the homework because my answer is incorrect. I'm pretty sure theanswer is correct but I'm not sure why my answer is wrong. Can someone explain it to me?↪→

A:

Your code is correct.The problem is with the output.You should add a line after the print statement, to display the value of the double

sumMajorDiagonal method:↪→

System.out.println("Double sum of the major diagonal is " + doubleSumMajorDiagonal(m));

This should give you the output you expect.

Generation 7-15: Misc. error

Page 92

Page 93: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

Write a Java program that accepts a $4\times 4$ matrix of real numbers and prints the total ofall numbers placed on the leading diagonal of the matrix. You should create and use amethod \textit{double sumMajorDiagonal(double[][] m)} which will return the total of allnumbers placed on the leading diagonal of the parameterised matrix.

↪→

↪→

↪→

You should also create and use a method \textit{printDiagonal(double[] m)} which will print outthe values of the parameterised matrix.↪→

I've found a solution, but it's a very long code, so I need to know how can I simplify it.public class DiagonalSum {

public static void main(String[] args) {double[][] matrix = new double[4][4];double total = 0;for (int i = 0; i < matrix.length; i++) {

for (int j = 0; j < matrix[0].length; j++) {if (j == 0) {

matrix[i][j] = i + j + 1;} else {

matrix[i][j] = 0;}

}}for (int i = 0; i < matrix.length; i++) {

for (int j = 0; j < matrix[0].length; j++) {total = total + matrix[i][j];

}}System.out.println(total);

}

public static double sumMajorDiagonal(double[][] m) {double total = 0;for (int i = 0; i < m.length; i++) {

for (int j = 0; j < m[0].length; j++) {if (j == 0) {

total = total + m[i][j];} else {

total = total + 0;}

}}return total;

}

public static void printDiagonal(double[] m) {for (int i = 0; i < m.length; i++) {

System.out.print(m[i]);}

}}

A:

public class DiagonalSum {public static void main(String[] args) {

double[][] matrix = new double[4][4];double total = 0;for (int i = 0; i < matrix.length; i++) {

Page 93

Page 94: arXiv:2201.07406v1 [cs.CL] 19 Jan 2022

for (int j = 0; j < matrix[0].length; j++) {matrix[i][j] = i + j + 1;

}}for (int i = 0; i < matrix.length; i++) {

for (int j = 0; j < matrix[0].length; j++) {total = total + matrix[i][j];

}}System.out.println(total);

}

public static double sumMajorDiagonal(double[][] m) {double total = 0;for (int i = 0; i < m.length; i++) {

for (int j = 0; j < m[0].length; j++) {total = total + m[i][j];

}}return total;

}

public static void printDiagonal(double[] m) {for (int i = 0; i < m.length; i++) {

System.out.print(

public class DiagonalSum {

public static double sumMajorDiagonal(double[][] m) {double total = 0;for (int i = 0; i < m.length; i++) {

for (int j = 0; j < m[0].length; j++) {if (j == i) {

total = total + m[i][j];} else {

total = total + 0;}

}}return total;

}}

Page 94