I'm attempting to write a program that will ask a user how many pre-requisites a particular class has, ask for the name of each pre-requisite, and then output a list of the pre-requisites in a single line.
My program is running without returning any errors; however, when it outputs the list of the pre-requisites, it only repeats the last one entered by the user instead of listing all of the pre-requisites entered. I believe that this is because the value of the object is changing every time the user enters a new pre-requisite; however, I cannot figure out how to get it to save each value and concatenate them together for the output.
The following code is what I'm using to collect the pre-requisites from the user
public static void getPrereqs() {
System.out.print("How many pre-requisites does the course have? ");
numPrereqs = console.nextInt();
console.nextLine();
for (int i = 1; i <= numPrereqs; i++) {
System.out.print("List Pre-requisite #" + i + "? ");
listPrereq = console.nextLine();
}//Close for loop
}//Close getPrereqs method
and this is the code I'm using to output the list (also includes recalling some other pieces of information but those are outputting correctly)
public static void printToScreen () {
System.out.println(courseCode + ": " + courseName);
System.out.print("Pre-requisites: ");
for (int i = 1; i <= numPrereqs; i++) {
System.out.print(listPrereq + ", ");
}//Close for loop
System.out.println();
System.out.println("Total number of seats = " + TOTAL_SEATS);
System.out.println("Number of students currently registered = " + studentsReg);
openSeats = calcAvail(studentsReg);
System.out.println("Number of seats available = " + openSeats);
if (openSeats >= 5) {
System.out.println ("There are a number of seats available.");
}//Close if loop
else {
if (openSeats <= 0) {
System.out.println ("No seats remaining.");
}//Close if loop
else {
System.out.println ("Seats are almost gone!");
}//Close else
}//Close else statement
}//Close printToScreen method
I have seen some threads discussing array lists; however, I am very unfamiliar with what this is and not comfortable using one at this time. Is there a way to get the results I'm looking for using a cumulative algorithm?
You currently overwrite the String variable listPrereq each iteration. You need to store into an array (preferred), or concatenate as one large String.
If you do not like Lists, then an array should be fine.
Instead of declaring listPrereq as a String, instead declare as an array:
String[] listPrereq;
Then you need to create it large enough to store each prerequisite:
numPrereqs = console.nextInt();
listPrereq = new String[numPrereqs];
Then store the values:
for (int i = 0; i < numPrereqs; i++) {
System.out.print("List Pre-requisite #" + (i+1) + "? ");
listPrereq[i] = console.nextLine();
} // Close for loop
Then to print:
System.out.print("Pre-requisites: ");
for (int i = 0; i < numPrereqs; i++) {
System.out.print(listPrereq[i]);
if (i != numPrereqs - 1)
System.out.println(",");
}//Close for loop
You could concatenate together a large string instead of using arrays (is this your preference?), but you lose the ability then to easily refer to each prerequisite individually afterwards.
EDIT: How to create a large String
String listPrereq = "";
for (int i = 0; i < numPrereqs; i++) {
System.out.print("List Pre-requisite #" + (i+1) + "? ");
listPrereq += console.nextLine();
if (i != numPrereqs - 1)
listPrereq += ",";
} // Close for loop
// To print:
System.out.println(listPrereq);
import java.util.*;
public class CourseDetails {
private static Scanner console;
public static void getPrereqs() {
console = new Scanner(System.in);
int numPrereqs;
String listPrereq = "";
System.out.print("How many pre-requisites does the course have? ");
numPrereqs = console.nextInt();
console.nextLine();
for (int i = 1; i <= numPrereqs; i++) {
System.out.print("List Pre-requisite #" + i + "? ");
listPrereq = listPrereq + i + " " + console.nextLine();
listPrereq = listPrereq + "\n";
} // Close for loop
System.out.println("Pre-requisites: ");
System.out.println(listPrereq);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
getPrereqs();
}
}
Second Way:
import java.util.Scanner;
public class CourseDetailsA {
private static Scanner console;
public static void getPrereqs() {
console = new Scanner(System.in);
int numPrereqs;
int j = 1;
String[] listPrereq;
System.out.print("How many pre-requisites does the course have? ");
numPrereqs = console.nextInt();
listPrereq = new String[numPrereqs];
console.nextLine();
for (int i = 0; i <= numPrereqs - 1; i++) {
System.out.print("List Pre-requisite #" + j + "? ");
listPrereq[i] = j + " " + console.nextLine() + "\n";
j++;
} // Close for loop
System.out.println("Pre-requisites: ");
for (int i = 0; i <= numPrereqs - 1; i++) {
System.out.print(listPrereq[i]);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
getPrereqs();
}
}
Related
I am new to java coding. I have written the code below to the problem: How can I write a statement that can be used in a Java program to read two integers and display the number of integers that lie between them, including the integers themselves?
I couldn't run it in Eclipse. When I try to run it through Eclipse, it tells me "The selection cannot be launched, and there are no recent launches. Anyway, can someone please tell me if this code correct? Are there any errors in it?
import java.util.Scanner;
public class Assignment4 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Enter the first integer:10");
int first = s.nextInt();
System.out.print("Enter the second integer:20");
int second = s.nextInt();
System.out.println("How many integers are between "+first+" and "+second+"???");
}
}
Please put some more effort on your query, for sure you can come up with your answers by yourself and you will learn faster. For now You can refer to below answer.
package com.barnwal.jeetendra.learn;
import java.util.Scanner;
public class Assignment4 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Enter the first integer:");
int first = s.nextInt();
System.out.print("Enter the second integer:");
int second = s.nextInt();
System.out.println("How many integers are between " + first + " and "
+ second + "???");
// To print number of integer between entered number
if (second > first) {
System.out.println("Answer : " + (second - first - 1));
// To print the numbers
for (int i = first + 1; i < second; i++)
System.out.print(i + " ");
} else {
// To print number of integer between entered number
System.out.println("Answer : " + (first - second - 1));
// To print the numbers
for (int i = second + 1; i < first; i++)
System.out.print(i + " ");
}
}
}
To avoid the unnecessary if-else statement to look which value is bigger, you can also use the functionality of the class java.lang.Math like this
Scanner s = new Scanner(System.in);
System.out.print("Enter the first integer:");
int first = s.nextInt();
System.out.print("Enter the second integer:");
int second = s.nextInt();
int small = Math.min(first, second) ;
int big = Math.max(first, second);
System.out.println("How many integers are between " + small + " and " + big + "???");
System.out.println("Answer : " + (big - small + 1));
// To print the numbers
for (int i = small; i <= big; i++)
System.out.print(i + " ");
You can use looping like this:
if (first > second){
big = first;
small = second;
}
else if (second > first){
big = second;
small = first;
}
for (int i = small; i <= big; i++)
System.out.print(i + " ");
first of all, when you use resources (System.in) you should close them. You can do it with try-finally or you can use try-with-resources.
Here is your code:
import java.util.Scanner;
public class Assignment4 {
public static void main(String[] args) {
try (Scanner s = new Scanner(System.in)){
System.out.print("Enter the first integer:10");
int first = s.nextInt();
System.out.print("Enter the second integer:20");
int second = s.nextInt();
System.out.println("How many integers are between "+first+" and "+second+"???");
if (first != second)
System.out.println("Answer: " + Math.abs(first-second - 1));
else
System.out.println("Answer: 0");
}
}
}
How about this:
int diff = second - first - 1;
let secont = 25 and first = 23 so the output will be:
25-23-1 = 1;
which is 24
I'm new to Java and I'm attempting to learn off different sites and videos and I've been stuck on a problem for a couple of days now and I'm wondering can anyone help out. What I'm trying to do is ask the user how many key actors are in a film. Then i want to ask the actors name and the role they play in the film, this should be asked for each actor for however many the user specified are in the film before finally displaying the actors name and his role?
import java.util.Scanner;
public class rough {
public static void main(String[] args) {
// TODO Auto-generated method stub
int actorCount;
Scanner input = new Scanner(System.in);
Scanner kb = new Scanner(System.in);
System.out.println("How many actors are in the film? ");
actorCount = kb.nextInt();
for (int k = 1; k <= actorCount ; k++)
{
float actor, character;
System.out.println("What is the actors name? ");
actor = kb.nextFloat();
System.out.println("What is " + actor + "'s character?");
character = kb.nextFloat();
System.out.print(actor + " - " + character);
}
kb.close();
input.close();
}
}
This is what I would have done:
import javax.swing.*;
public class rough {
public static void main(String[] args) {
// TODO Auto-generated method stub
int actorCount;
String output = "";
actorCount = Integer.parseInt(JOptionPane.showInputDialog(null,"How many actors are in the film? "));
for (int k = 1; k <= actorCount ; k++)
{
String actor, character;
actor = JOptionPane.showInputDialog(null, "What is the actors name?");
character = JOptionPane.showInputDialog(null, "What is " +actor + "s character?");
output += actor + " - " + character + "\n";
}
JOptionPane.showMessageDialog(null, output);
}
}
Remember that if you want all of the roles/actors to be printed at the same time you must put the print outside the for loop and store the roles/actors to some output String. Moreover, I cannot see why you have used a float variable for the roles/actors a String would be the most logical.
So you should do it in this way:
public static void main(String[] args) {
int actorCount;
Scanner input = new Scanner(System.in);
Scanner kb = new Scanner(System.in);
System.out.println("How many actors are in the film? ");
actorCount = kb.nextInt();
String[][] actorValues = new String[actorCount][2];
for (int k = 0; k < actorCount ; k++)
{
String actor, character;
System.out.println("What is the actors name? ");
actor = kb.next();
System.out.println("What is " + actor + "'s character?");
character = kb.next();
System.out.print(actor + " - " + character +"\n");
actorValues[k][0] = actor;
actorValues[k][1] = character;
}
//Printout the Characters in the List
System.out.println("All Actors:");
for (int i = 0; i < actorValues.length; i++) {
String[] strings = actorValues[i];
System.out.println("Actorssname: "+strings[0]+" Character:"+strings[1]);
}
kb.close();
input.close();
}
I am trying to find the occurrences of all integers submitted by the user into the program and so far here's what I got. It works but I don't think it's a legit way to do it, is there any way I can try to do this without using the list[10]=9999;? Because if I don't do it, it'll show out of boundary error.
import java.util.*;
public class OccurrencesCount
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int[] list = new int[11];
//Accepting input.
System.out.print("Enter 10 integers between 1 and 100: ");
for(int i = 0;i<10;i++){
list[i] = scan.nextInt();
list[10] = 9999;
}
//Sort out the array.
Arrays.sort(list);
int count = 1;
for(int i = 1;i<11;i++){
if(list[i-1]==list[i]){
count++;
}
else{
if(count<=1){
System.out.println(list[i-1] + " occurs 1 time.");
}
else{
System.out.println(list[i-1] + " occurrs " + count + " times.");
count = 1;
}
}
}
}
}
Personally, I think this is a perfectly good solution. It means that you can deal with the last group in the same way as all others. The only change I would make is putting the line list[10] = 9999; outside the for loop (there's no reason to do it 10 times).
However, if you want to use an array of length 10, you can change the line
if(list[i-1]==list[i])
to
if(i < 10 && list[i-1]==list[i])
If you do this, you won't get an ArrayIndexOutOfBoundsException from list[i] because the expression after the && is not evaluated when i == 10.
import java.util.*;
class OccurrencesCount {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int[] list = new int[101];
System.out.print("Enter 10 integers between 1 and 100: ");
for(int i = 0;i<10;i++) {
int x = scan.nextInt();
list[x]++;
}
for(int i = 1; i <= 100; i++)
if(list[i] != 0)
System.out.println(i + " occurs " + list[i] + " times ");
}
}
To store count of numbers from 1 to 100 you need to use a list of 100 integers each one storing the number of occurrences of itself. Better approach would be to use a Map.
I have made use of ArrayList and Collections package instead of regular arrays as a different flavor if it interests you check it out.
import java.util.*;
public class OccurrencesCount {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
List<Integer> list = new ArrayList<>();
//Accepting input.
System.out.print("Enter 10 integers between 1 and 100: ");
for (int i = 0; i < 10; i++) {
list.add(scan.nextInt());
}
Collections.sort(list);
Integer prevNumber = null;
for (int number : list) {
if (prevNumber == null || prevNumber != number) {
int count = Collections.frequency(list, number);
System.out.println(number + " occurs " + count + (count > 1 ? " times." : " time."));
}
prevNumber = number;
}
}
}
I got it figured out guys, only changed a couple of small things inside the conditions and everything went smoothly! Thanks for the help! Now I just need to find a way to restrict the inputs from going above 100.
import java.util.*;
public class CountOccurrences
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int[] list = new int[10];
//Accepting input.
System.out.print("Enter 10 integers between 1 and 100: ");
for(int i = 0;i<=9;i++){
list[i] = scan.nextInt();
}
//Sort out the array.
Arrays.sort(list);
int count = 1;
for(int i = 1;i<=10;i++){
if(i<=9 && list[i-1]==list[i]){
count++;
}
else{
if(count<=1){
System.out.println(list[i-1] + " occurs 1 time.");
}
else{
System.out.println(list[i-1] + " occurrs " + count + " times.");
count = 1;
}
}
}
}
}
I have this code:
When I launch it, I am able to get numbers i = 0 to i = 10. However I know this is not the objective of the code as the objective is to reach into the Scanner. But the scanner does not seem to work? Am I making an error importing a file or is this to do with the code? I'm noob.
package buggyProgram;
import java.util.Scanner;
public class BuggyProgram {
/**
* The main method of the program. This is where it all starts.
*/
public static void main(String[] args) {
String[] saNames = new String[5];
String[] saNumbers = new String[5];
Scanner scIn = new Scanner(System.in);
for (int i = 0; i <= 4; i++) {
System.out.print("Enter name: ");
saNames[i] = scIn.nextLine();
System.out.print("Enter number: ");
saNumbers[i] = scIn.nextLine();
}
System.out.println();
for (int i = 1; i < 4; i++) {
System.out.println("The number of " + saNames[i] + " is "
+ saNames[i] + ".");
}
}
}
Java arrays start at 0 (not 1), and you're printing the same array element twice (in your second for-loop). Finally, you could always use a debugger to help you determine where things are no longer working as you expect.
// for (int i = 1; i < 4; i++) {
for (int i = 0; i <= 4; i++) { // <-- to match your first loop.
System.out.println("The number of " + saNames[i] + " is "
+ saNumbers[i] + ".");
}
You might also use formatted output (the formatter syntax) like
for (int i = 0; i <= 4; i++) {
System.out.printf("The number of %s is %s.%n", saNames[i], saNumbers[i]);
}
One of the first things you can do to make it easier to debug is to make the input fixed between runs. If you change Scanner scIn = new Scanner(System.in); to this:
Scanner scIn = new Scanner(new BufferedReader(new FileReader("some-file.txt")));
Assuming that some-file.txt is populated with the appropriate input, then you can run the program multiple times without having to manually re-enter the input. In addition, the input is fixed, so comparing the output of different runs becomes more useful.
I can confirm, that your code works, as long as you change your final output:
String[] saNames = new String[5];
String[] saNumbers = new String[5];
Scanner scIn = new Scanner(System.in);
for (int i = 0; i <= 4; i++) {
System.out.print("Enter name: ");
saNames[i] = scIn.nextLine();
System.out.print("Enter number: ");
saNumbers[i] = scIn.nextLine();
}
System.out.println();
for (int i = 1; i < 4; i++) {
System.out.println("The number of " + saNames[i] + " is "
+ saNumbers[i] + ".");
}
I am a beginner in Java and am working on a basic program that includes arrays and loops. The program must:
- ask the user to enter the name of a 'salesman' 5 times. These 5 names will be stored into a String array.
- another DOUBLE array is used to store the amount of sales each person has made.
- the data will be printed in the end.
Here's what I have so far:
public static void main (String[] args)
{
String[] names = new String[5];
System.out.println ("What is the name of the person?")
String name = scan.next();
double[] sales = new double[5];
sales[0] = 15000.00;
sales[1] = 10000.00;
sales[2] = 4500.00;
sales[3] = 2500.00;
sales[4] = 3500.00;
System.out.println(name1 + "sold " + sales[0]);
System.out.println(name2 + "sold " + sales[1]);
System.out.println(name3 + "sold " + sales[2]);
System.out.println(name4 + "sold " + sales[3]);
System.out.println(name5 + "sold " + sales[4]);
}
}
I know the first part is incorrect... as well as most of the output.
My instructor is not very interested in explaining much to our class. She is usually too busy working with a different part of the class. I basically know nothing about arrays.
I will certainly learn something if one of you is kind enough to tell me what I need to enter and where?
You need to use for loops to avoid having to repeat the lines of code for each instance. You want something more like this:
public static void main (String[] args)
{
String[] names = new String[5];
double[] sales = new double[5];
Scanner scan = new Scanner(System.in);
for (int i=0; i<5; i++) {
System.out.println ("What is the name of the person?");
name[i] = scan.next();
System.out.println ("How much did they sell?");
sales[i] = scan.nextDouble();
}
for (int i=0; i<5; i++) {
System.out.println (name[i] + " sold " + sales[i]);
}
}
look here http://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html for more on how to use the for loop. The loops that I wrote will execute the code inside when i=0, 1, 2, 3 and 4. i=0 tells the loop where to begin. i<5 tells the loop to execute the code inside as long as i is less than 5. And i++ is shorthand for i=i+1 and tells the loop what to do to i at the end (increase i by 1 and test the end condition again).
ETA: http://www.homeandlearn.co.uk/java/user_input.html shows how to use the Scanner class to get input.
It will be easier when you use collections.
Use this for simple implementation and better understanding for collections.
Scanner scanner = new Scanner(System.in);
List<String> list = new ArrayList<String>();
for (int i = 0; i < 5; i++) {
list.add(scanner.nextLine());
}
For printing use this.
for(String result : list){
System.out.println(result);
}
Simply use Scanner inside a loop.
String[] names = new String[5];
double[] sales = new double[5];
Scanner scanner = new Scanner(System.in);
for(int i = 0; i < names.length; i++){
System.out.print ("Please input name of sale " + (i+1) + ": ");
names[i] = scanner.nextLine();
System.out.print ("Please input sales of sale " + (i+1) + ": ");
sales[i] = scanner.nextDouble();
}
// following lines is for testing
for(int i=0; i < names.length; i++){
System.out.println(names[i]+" " + sales[i]);
}
Since Java is a Object oriented, so I recommend you to create a class named Salesman containing name and sale attributes.
// Salesman class
class Salesman{
private String name;
private double sales;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSales() {
return sales;
}
public void setSales(double sales) {
this.sales = sales;
}
}
And once again the main method.
public static void main (String[] args)
{
List<Salesman> salesmanList = new ArrayList<Salesman>(5);
Scanner scanner = new Scanner(System.in);
for(int i = 0; i < 5; i++){
Salesman salesman = new Salesman();
System.out.print ("Please input name of sale " + (i+1) + ": ");
salesman.setName(scanner.nextLine());
System.out.print ("Please input sales of sale " + (i+1) + ": ");
salesman.setSales(scanner.nextDouble());
salesmanList.add(salesman);
}
// following lines is for testing
for(Salesman salesman : salesmanList){
System.out.println(salesman.getName()+" " + salesman.getSales());
}
}
Try this:
public void getInput(){
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the total no of i/p :")
int count = scanner.nextInt();
List<String> collectionOfInput = new ArrayList<String>();
for (int i = 0; i < count; i++) {
collectionOfInput.add(scanner.nextLine());
}
}
public void printOutput(){
for(String outputValue : collectionOfInput){
System.out.println(result);
}