Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have a for loop which stores results in an int array and from these results I need to be able to search for eg. how many 1 are in the array so I declared an int variable outside the loop but it keeps saying that my array hasn't been initialized. Could you guys help me thanks.
import java.util.Scanner;
import java.util.Arrays;
class TestDie {
public static void main (String [] args)
{
Die firstDie = new Die();
int[] playerOneResults;
firstDie.roll();
System.out.println(firstDie.getFaceValue());
Scanner userInput = new Scanner(System.in);
System.out.println("PLease enter the name of player one");
String playerOneName = userInput.next();
System.out.println("Please enter the name of player two");
String playerTwoName = userInput.next();
System.out.println("Enter the number of dice to be thrown");
int numDice = userInput.nextInt();
System.out.println("First player's name: " + playerOneName);
System.out.println("Second player's name: " + playerTwoName);
System.out.println("Number of dice will be thrown: " + numDice);
for(int counter = 0; counter != numDice; counter++)
{
playerOneResults = new int[numDice];
firstDie.roll();
playerOneResults[counter] = firstDie.getFaceValue();
System.out.println("Player one results: " + playerOneResults[counter]);
}
Arrays.sort(playerOneResults);
int c = Arrays.binarySearch(playerOneResults, 1);
System.out.println(c);
}
}
Try this code
public static void main(String args[]) {
Die firstDie = new Die();
int[] playerOneResults = null;
firstDie.roll();
System.out.println(firstDie.getFaceValue());
Scanner userInput = new Scanner(System.in);
System.out.println("PLease enter the name of player one");
String playerOneName = userInput.next();
System.out.println("Please enter the name of player two");
String playerTwoName = userInput.next();
System.out.println("Enter the number of dice to be thrown");
int numDice = userInput.nextInt();
System.out.println("First player's name: " + playerOneName);
System.out.println("Second player's name: " + playerTwoName);
System.out.println("Number of dice will be thrown: " + numDice);
playerOneResults = new int[numDice];
for (int counter = 0; counter != numDice; counter++) {
firstDie.roll();
playerOneResults[counter] = firstDie.getFaceValue();
System.out.println("Player one results: " + playerOneResults[counter]);
}
Arrays.sort(playerOneResults);
int position=0;
while(position<0){
int c = Arrays.binarySearch(playerOneResults, position,playerOneResults.length-1, 1);
position=c;
System.out.println(c);
}
}
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
Getting a main method error which is only affecting my retrieve salary method I'm not sure what to do to fix the issue I have added particular items but I can't get the error to go away. Is the only thing on my program that brings up an error and I am unable to continue. Image included of the only issues I'm encountering now
"Error: Main method not found in class, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application"
Image included
public class finalproject {
public static class employeeCase {
EMPLOYEE[] employees;
int AMOUNT;
employeeCase(){
employees = new EMPLOYEE[100];
AMOUNT = 0;
}
private void loadEmployee() {
String ID = null;
int SALARY = 0;
Scanner sc = new Scanner(System.in);
System.out.println(" ");
System.out.println("How many employees do you want to load?: ");
int num = sc.nextInt();
for(int i = 0; i < num; i++){
// Display parallel arrays
System.out.println(" ");
System.out.println("Name: " + employees[i] + " " + "ID: " + ID + " " + "Salary: " + SALARY);
sc.close();
}
}
private int addEmployee() {
Scanner sc = new Scanner(System.in);
System.out.println(" ");
System.out.println("How many employees do you want to enter?: ");
AMOUNT = 0;
AMOUNT = sc.nextInt();
String Again1 = "no";
String Fname;
String ID;
int SALARY = 0;
do {
for(int i = 0; i < AMOUNT; i++) {
System.out.printf("Enter employee's first name: ");
Fname = sc.nextLine();
System.out.printf("Enter employee ID (5 digits): ");
ID = sc.next();
System.out.printf("Enter employee salary: ");
SALARY = sc.nextInt();
System.out.println(" ");
this.employees[this.AMOUNT] = new EMPLOYEE(Fname, ID, SALARY);
this.AMOUNT++;
sc.close();
} } while (Again1.equalsIgnoreCase("yes"));
return SALARY;
}
private void displayEmployee() {
for(int i = 0; i < AMOUNT; i++){
// Display parallel arrays
System.out.println(" ");
System.out.println(this.employees[i]);
}
}
private void retrieveSpecific() {
Scanner sc = new Scanner(System.in);
System.out.println(" ");
System.out.println("Enter employee ID: ");
String id = sc.next();
//Search for ID in all the stored employees
for(int i=0; i<this.AMOUNT; i++) {
if(id.contentEquals(this.employees[i].ID)) {
System.out.println(this.employees[i]);
sc.close();
}}}
private void retrieveSalary() {
Scanner scan = new Scanner(System.in);
System.out.println(" ");
System.out.println("Enter lowest employee salary: ");
int LSALARY = scan.nextInt();
System.out.println(" ");
System.out.println("Enter highest employee salary: ");
int HSALARY = scan.nextInt();
for(int i = 0; i < AMOUNT; i++) {
if(employees[i].SALARY >= LSALARY & employees[i].SALARY <= HSALARY) {
System.out.println(employees[i]);
scan.close();}}
}
public static void main(String[] args) {
employeeCase EmployeeData = new employeeCase();
Scanner sc = new Scanner(System.in);
int Select = 0;
do {
displayMenu();
System.out.print("Input your selection from the menu: ");
Select = sc.nextInt();
switch (Select) {
case 1 : EmployeeData.loadEmployee();
break;
case 2 : EmployeeData.addEmployee();
break;
case 3 : EmployeeData.displayEmployee();
break;
case 4 : EmployeeData.retrieveSpecific();
break;
case 5 : EmployeeData.retrieveSalary();
break;
case 6 : System.out.println("Thank you, goodbye!");
break;
default : System.err.println("Invalid Input");
break;
}
} while (Select != 6);
sc.close();
}
public static void displayMenu() {
System.out.println(" MENU");
System.out.println("============================================");
System.out.println("1: Load employees' data");
System.out.println("2: Add new employee");
System.out.println("3: Display all employees");
System.out.println("4: Retrieve specfic employee data");
System.out.println("5: Retrieve employee based on salary range");
System.out.println("6: Exit program");
}
}}
Your main method needs to be static. Change public void main to public static void main.
Access modifier for main method should be static here you define a non static main method
Replace your main method with
public static void main(String[] args){}
This is probably very basic stuff, but I am not too sure how I should ask questions because I am very new to this, so here goes.
I am practicing vectors and what we can do to them. I have prompted the user for the elements of the vectors (per my directions) among other things successfully. For my next step, I have to "print out the element at index i in each of the two vectors." I was given the methods which I am supposed to use, but the explanations I saw of them were very unclear. Here they are:
Object get (int which)
Object remove (int which)
set (int index, object element)
How would I get the system output to be the element at the index i?
package vectorusage;
import java.util.*;
public class VectorUsage {
public static void main(String[] args) {
Vector a = new Vector ();
Vector b = new Vector ();
System.out.println (a);
System.out.println (b);
Scanner input = new Scanner(System.in);
String first;
System.out.print("Please enter 4 strings.");
first = input.next();
a.add (first);
String second;
second = input.next();
a.add (second);
String third;
third = input.next();
a.add (third);
String fourth;
fourth = input.next();
a.add (fourth);
String fifth;
System.out.print("Please enter 4 more strings.");
fifth = input.next();
b.add (fifth);
String sixth;
sixth = input.next();
b.add (sixth);
String seventh;
seventh = input.next();
b.add (seventh);
String eighth;
eighth = input.next();
b.add (eighth);
System.out.println("Vector a is size " + (a.size()) + " and contains: " + (a));
System.out.println("Vector b is size " + (b.size()) + " and contains: " + (b));
int i;
System.out.println("Please enter an integer.");
i = input.nextInt();
System.out.println("Element at index " + i + " in Vector a is: " + ;
Avoid using vectors, they are deprishiated. Use ArrayList instead.
Using a for loop you can simplify your code like below,
(Please note, this code does not validate user input or do error handling)
import java.util.ArrayList;
import java.util.Scanner;
public class Test {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
ArrayList<Integer> numbers = new ArrayList<Integer>();
System.out.println("Please enter 8 strings.");
for(int i = 1; i <= 8; i++) {
System.out.print("Please enter strings #" + i + ": ");
numbers.add(input.nextInt());
}
for(int j = 0; j < numbers.size(); j++) {
System.out.println("Number at index " + j + " is " + numbers.get(j));
}
}
}
I usually use a mix of while and for loop. The while loop is used to add the user input into the vector. The for loop prints out the elements of the vector using index i. I've set it to print all the elements of the vector but you can modify it by using if conditions. Here's my code, hope it helps!
import java.util.*;
import java.io.*;
public class VectorUsage {
public static void main(String[]args) {
Scanner input=new Scanner(System.in);
Vector a=new Vector();
int count =0;
while(count<4)
{
System.out.print("Enter a string: ");
a.addElement(input.nextLine());
count++;
}
for(int i=0;i<a.size();i++)
{
System.out.println(a.elementAt(i));
}
Vector b=new Vector();
int count1=0;
while(count1<4)
{
System.out.print("Enter a string: ");
b.addElement(input.nextLine());
count1++;
}
for(int i=0;i<b.size();i++)
{
System.out.println(b.elementAt(i));
}
}
}
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.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I'm trying to make a script that asks for multiple inputs then prints them out below.
For example:
How many inputs do you want? -> 3
What is the 1. input? -> 5
What is the 2. input? -> 3
What is the 3. input? -> 4
You gave these inputs:
1) 5
2) 3
3) 4
Below you can see how far I got with it. Asks for all the inputs nicely but I can't figure out how to print them out below the input.
import java.util.Scanner;
public class Inputs {
public static void main(String[] args){
Scanner read = new Scanner(System.in);
System.out.println("How many inputs?");
int inp=read.nextInt();
for (int i=1;i<=inp;i++){
System.out.print("What was " + i + ". input? ");
int print=read.nextInt();
System.out.println(print);
}
}
}
public class Inputs {
public static void main(String[] args){
Scanner read = new Scanner(System.in);
System.out.println("How many inputs?");
int inp=read.nextInt();
int[] answers = new int[inp];
for (int i=1;i<=inp;i++){
System.out.print("What was " + i + ". input? ");
int print=read.nextInt();
System.out.println(print);
answers[i] = print;
}
int index = 0;
for(int a : answers){
System.out.println( index + ")" + " " + a);
index ++;
}
}
}
You can code clean it yourself as a practice =)
You can use Collections (i used List) to protect your inputs;
public class Inputs {
public static void main(String[] args){
Scanner read = new Scanner(System.in);
System.out.println("How many inputs?");
int inp=read.nextInt();
List<Integer> numbers = new ArrayList<Integer>();
for (int i=1;i<=inp;i++){
System.out.print("What was " + i + ". input? ");
int print=read.nextInt();
numbers.add(print);
System.out.println(print);
}
System.out.println("Inputs are :");
for (Integer integer : numbers) {
System.out.println(integer);
}
}
}
And the output is;
How many inputs?
3
What was 1. input? 5
5
What was 2. input? 3
3
What was 3. input? 4
4
Inputs are :
5
3
4
You need to create an array of integers for later use.
int array = new int[inp];
You need to store the inputs and print them later
import java.util.Scanner;
public class Inputs {
public static void main(String[] args){
Scanner read = new Scanner(System.in);
System.out.println("How many inputs?");
int inp=read.nextInt();
int[] keepInputsHere=new int[inp];
for (int i=0;i<inp;i++){
System.out.print("What was " + i + ". input? ");
int readInt=read.nextInt();
keepInputsHere[i]=readInt;
}
System.out.print("Print results: ");
for (int i=0;i<inp;i++){
System.out.print( keepInputsHere[i]);
}
}
}
Dont forget to close the Scanner and separate the login into different functions:
public class Inputs {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
System.out.println("How many inputs?");
int inp = read.nextInt();
Print(ReadInput(inp,read));
}
private static int[] ReadInput(int questionsNo, Scanner sc) {
int[] inputs = new int[questionsNo];
for (int i = 0; i < questionsNo; i++) {
System.out.print("What was " + i + ". input? ");
int readInt = sc.nextInt();
inputs[i] = readInt;
}
sc.close();
return inputs;
}
private static void Print(int[] inputs) {
System.out.println("Print results: ");
for (int i = 0; i < inputs.length; i++) {
System.out.println( i + ")" + " " + inputs[i]);
}
}
}
So here is my program:
import java.util.*;
import java.io.*;
import java.util.Random;
public class cardsAgainstHumanity
{
public static void main(String[] args) throws FileNotFoundException
{
Random rand = new Random();
int again = 1;
String blank1 = "";
String blank2 = "";
int playerOneScore = 0;
int playerTwoScore = 0;
String playerOneCard = "";
String playerTwoCard = "";
String[] oneHand = new String[10];
String[] twoHand = new String[10];
Scanner input = new Scanner(System.in);
Scanner input1 = new Scanner(System.in);
Scanner input2 = new Scanner(System.in);
System.out.println("1 = Vanilla \n2 = Rando Cardrissian \n3 = God Is Dead \nInput Game Type (using those numbers) \nJust a note, players hands reset after each round.");
String gameMode = input.nextLine();
Scanner whiteScanner = new Scanner(new File("C:/Users/William/Documents/CardsAgainstHumanityWhite.txt"));
whiteScanner.useDelimiter("<>");
Scanner blackScanner = new Scanner(new File("C:/Users/William/Documents/CardsAgainstHumanityBlack.txt"));
blackScanner.useDelimiter("<>");
int whitecount = 0;
int blackcount = 0;
String[] whiteCardsArray = new String[538];
String[] blackCardsArray = new String[92];
//Inputing cards into array
while(whitecount<=537)
{
whiteCardsArray[whitecount]=whiteScanner.next();
whitecount++;
}
while(blackcount<92)
{
blackCardsArray[blackcount]=blackScanner.next();
blackcount++;
}
//Keeps going and asking questions until again = 0 (meaning they dont want to play again)
while(again == 1)
{
//Asking player One
String currentQuestion = blackCardsArray[rand.nextInt(91)+0];
System.out.println("This is the question: " + currentQuestion);
System.out.println("Player Two look away, Player One hit enter to see your cards.");
blank1 = input1.nextLine();
System.out.println("These are player ones cards: ");
for(int x = 0; x<10; x++)
{
String tmpWhiteString = whiteCardsArray[rand.nextInt(537)+0];
oneHand[x] = tmpWhiteString;
System.out.println((x+1)+":" + " " + oneHand[x]);
}
System.out.println("Please select your card");
playerOneCard = oneHand[(input.nextInt())-1];
//Asking player Two
System.out.println("Player One look away, Player Two hit enter to see your cards.");
blank2 = input2.nextLine();
System.out.println("This is the question: " + currentQuestion);
System.out.println("These are player twos cards: ");
for(int x = 0; x<10; x++)
{
String tmpWhiteString = whiteCardsArray[rand.nextInt(537)+0];
twoHand[x] = tmpWhiteString;
System.out.println((x+1)+":" + " " + twoHand[x]);
}
System.out.println("Please select your card");
playerTwoCard = twoHand[(input.nextInt())-1];
//Tallying Score
System.out.println("Player one selected: " + playerOneCard);
System.out.println("Player two selected: " + playerTwoCard);
System.out.println("The question was: " + currentQuestion);
System.out.println("Who won?");
if(input.nextInt() == 1) playerOneScore++;
else if(input.nextInt() == 2) playerTwoScore++;
System.out.println("Player Ones score is: " + playerOneScore);
System.out.println("Player Twos score is: " + playerTwoScore);
//play another?
System.out.println("Would you like to play another round? (1 for yes, 0 for no)");
again = input.nextInt();
}
if(playerOneScore>playerTwoScore)
{
System.out.println("Player One wins with " + playerOneScore + " points.");
System.out.println("Player Two has " + playerTwoScore + " points");
}
else
{
System.out.println("Player Two wins with " + playerTwoScore + " points.");
System.out.println("Player One has " + playerOneScore + " points");
}
}
}
As you may be able to tell it is a cards against humanity program. I am referencing two files that have the different cards delineated by <>. So white cards are in one file and black cards are in another.
As you can see the program references these files. How can I export the program but still have it work? (P.S. I am a beginner so I have never exported before).
I will be changing this into a form that opens up a basic UI but I just have the basics for now.
Thanks so much in advance,
William
OK, I'm assuming you want to export your program as a JAR. This method will allow you to do this.
Just put the files in your compiled programs folder (typically /bin; if you're in Eclipse, you can put them in /src and have them copied over automatically).
Then get your scanner by using:
Scanner fileScanner = new Scanner(getClass().getResourceAsStream
("Where you kept the file (the root is the bin folder)"));