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();
}
Related
public static void main(String[] args) {
i got to enter the amount of names i want, then input them by scanner in console, and after print the longest one, it's mostly done, but i want to print it by JoptionPane aswell
Scanner wczytanie = new Scanner(System.in);
System.out.println("ENTER THE AMOUNT OF NAMES");
int size = wczytanie.nextInt();
String[] array = new String[size];
System.out.println("ENTER THE NAMES");
String name = wczytanie.nextLine();
for (int i = 0; i < array.length; i++) {
array[i] = wczytanie.nextLine();
if (name.length() < array[i].length()) {
name = array[i];
}
}
// System.out.println("LONGEST NAME: " + name);
String name1 = new String();
if(name == name1) {
JOptionPane.showMessageDialog(null, " THE LONGEST NAME IS " + name1);
}
}
You have a lot of problems here: you're reading from the scanner before the loop when reading names and you're doing a raw object equality on a new string for some reason that will never work. You want something more like this:
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
System.out.println("How many names? ");
int num = scanner.nextInt();
List<String> names = new ArrayList<>(num);
System.out.println("Enter names: ");
for (int i = 0; i < num; i++) {
names.add(scanner.next());
}
String longest = names.stream().reduce((a, b) -> a.length() > b.length() ? a : b).get();
System.out.println("The longest name is: " + longest);
JOptionPane.showMessageDialog(null, "The longest name is: " + longest);
}
}
I'm a beginner in Java. I have an assignment that require me to take 3 input from user, then output the 3 at the same time.
here is my code. i have only get 1 output.
suppose look like this:
anyone could help, thx!
here is my code
Scanner sc = new Scanner(System.in);
int i = 0;
String classname = " ";
String rating = " ";
int plus = 0;
while(i < 3){
System.out.print("What class are you rating? ");
classname = sc.nextLine();
System.out.print("How many plus signs does " + classname +" get? ");
rating = sc.nextLine();
plus = Integer.parseInt(rating);
i++;
}
System.out.print(classname + ": ");
while (plus > 0){
System.out.print("+");
plus --;
}
System.out.println();
The very first thing I would do is create a Course POJO (Plain Old Java Object). It should have two fields, name and rating. And I would implement the display logic with a toString in that Course POJO. Like,
public class Course {
private String name;
private int rating;
public Course(String name, int rating) {
this.name = name;
this.rating = rating;
}
public String toString() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < rating; i++) {
sb.append("+");
}
return String.format("%s: %s", name, sb);
}
}
Then your main method simply involves filling a single array of three Course instances in one loop, and displaying them in a second loop. Like,
Scanner sc = new Scanner(System.in);
Course[] courses = new Course[3];
int i = 0;
while (i < courses.length) {
System.out.print("What class are you rating? ");
String className = sc.nextLine();
System.out.printf("How many plus signs does %s get? ", className);
int classRating = Integer.parseInt(sc.nextLine());
courses[i] = new Course(className, classRating);
i++;
}
i = 0;
while (i < courses.length) {
System.out.println(courses[i]);
i++;
}
You overwrite your variables classname and rating in each loop. You need to store each iteration in a field of an array.
Scanner sc = new Scanner(System.in);
int i = 0;
String[] classname = new String[3]; //create array
String rating = " "; //rating can be overwritten, it is not needed after the loop
int[] plus = new int[3];
while(i < 3){
System.out.print("What class are you rating? ");
classname[i] = sc.nextLine(); //name[index] to read/write fields of an array
//index starts at 0
System.out.print("How many plus signs does " + classname +" get? ");
rating = sc.nextLine();
plus[i] = Integer.parseInt(rating);
i++;
}
for(i = 0;i<3;i++){ //iterate over all elements in the array
System.out.print(classname[i] + ": ");
while (plus[i] > 0){
System.out.print("+");
plus[i] --;
}
System.out.println();
}
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();
}
}
I'm working on a programming project for my intro class. I have a code that I'm trying to compile, but I'm having a hard time getting it to work after I added the PrintWriter. All was running well until I tried to print to a text file. Can someone help me figure out how to get it to run?
(Also, if you find any errors in my logic/layout/whatever, try to contain it! I still want to debug the program myself, I just can't do that until it runs :)
Attempt: (so far)
import java.util.Scanner; //import scanner
import java.util.Random; //import randomizer
import java.io.*; //needed for throws clause
public class randomLottery
{
public static void main(String[] args) throws IOException
{
String fullName;
Scanner keyboard = new Scanner( System.in );
//so we can generate random numbers
Random rand = new Random();
//declare a constant number of numbers
final int LOTTERY_NUMBERS = 5;
//Retrieve names
System.out.print("Please enter a first and last name for lottery "
+ "entry (type 'quit' to end): ");
fullName = keyboard.nextLine();
while(!fullName.contains(" "))
{
System.out.print("Please enter BOTH a first and last name."
+ " Try Again: ");
fullName = keyboard.nextLine();
}
while(!fullName.contains("quit"))
{
//separate first/last name
String[] parts = fullName.split(" ");
String firstName = parts[0];
String lastName = parts[1];
//Open the file
PrintWriter outputFile = new PrintWriter("LotteryEntrants.txt");
//Print the name onto the file
outputFile.print(lastName + ", " + firstName + ": ");
int number;
for (number = 1; number <= LOTTERY_NUMBERS; number++)
{
if (number == LOTTERY_NUMBERS)
{
int lotteryNumber = rand.nextInt(100) + 1;
outputFile.println(lotteryNumber);
}
else
{
int lotteryNumber = rand.nextInt(100) + 1;
outputFile.print(lotteryNumber + ", ");
}
}
//get the next name
System.out.print("Please enter BOTH a first and last name."
+ " Try Again: ");
fullName = keyboard.nextLine();
}
//Winning Lottery Numbers
outputFile.print("The winning numbers are: ");
int winning;
for (winning = 1; winning <= LOTTERY_NUMBERS; winning++)
{
if (winning == LOTTERY_NUMBERS)
{
int lotteryNumber = rand.nextInt(100) + 1;
outputFile.print(lotteryNumber);
}
else
{
int lotteryNumber = rand.nextInt(100) + 1;
outputFile.print(lotteryNumber + ", ");
}
}
outputFile.close();
}
}
PrintWriter outputFile = new PrintWriter("LotteryEntrants.txt");
Should be outside (before) the while loop. Having it inside the loop means it is not in the scope of your other uses of outputFile after the while loop.
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);
}