Why won't my java code run.. it's not necessarily even giving me an error for how i can fix it? [closed] - java

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 days ago.
Improve this question
This is what it says when i try to run the code.
Exception in thread "main"
java.lang.Error: Unresolved compilation problems:
system cannot be resolved
system cannot be resolved
system cannot be resolved
at MonthDays.main(MonthName.java:87)
Now in my code, they're no red lines or errors showing.. it's like i wrote the code correctly but it won't run. I understand the switche's aren't finished but they aren't the reason why it's not running
// shorter access to print function
import static java.lang.System.out;
// access to standard input
import java.util.Scanner;
// Java class
public class MonthDays
{
// code runs here
public static void main(String[] args)
{
// string constants
final String PROG_ID = "\n Filename: MonthDays.java" +
"\n «your full name here»" +
"\n Classwork - month name" +
"\n 13 February 2023" +
"\n ********************************************";
// input prompt
final String MO_INPUT = " Enter a month (mm): ";
// error messages
final String MO_ERR = "\n The month number you entered, %d, is invalid.";
final String PROG_EX = "\n Exiting program...";
// output message
final String OUT_TAG = "\n %d corresponds to %s.\n";
// month names
final String JAN_NAME = "January";
final String FEB_NAME = "February";
final String MAR_NAME = "March";
final String APR_NAME = "April";
final String MAY_NAME = "May";
final String JUN_NAME = "June";
final String JUL_NAME = "July";
final String AUG_NAME = "August";
final String SEP_NAME = "September";
final String OCT_NAME = "October";
final String NOV_NAME = "November";
final String DEC_NAME = "Decenmeber";
// numeric constants
final int JAN_POS = 1;
final int FEB_POS = 2;
final int MAR_POS = 3;
final int APR_POS = 4;
final int MAY_POS = 5;
final int JUN_POS = 6;
final int JUL_POS = 7;
final int AUG_POS = 8;
final int SEP_POS = 9;
final int OCT_POS = 10;
final int NOV_POS = 11;
final int DEC_POS = 12;
// variables
int nMonth = 0;
String sMonthName = "";
//Scanner = null;
// program identification
out.println(PROG_ID);
// create input object
Scanner scan = new Scanner(System.in);
// get month number
System.out.print(MO_INPUT);
// check month validity
// use an if
// exit program if invalid
// month number entered
if ( nMonth < JAN_POS || nMonth > DEC_POS)
{
system.out.printf(MO_ERR, nMonth);
system.out.printf(PROG_EX);
system.exit(1);
// match month name to number
// use a switch
switch (nMonth)
{
case JAN_POS:
sMonthName = JAN_NAME;
break;
case FEB_POS:
sMonthName = FEB_NAME;
break;
case MAR_POS:
sMonthName = MAR_NAME;
break;
}
}
} }

Related

Uni Assignment help (arrays and read from file) JAVA [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
My assignment requires me to have Java read a file that was given to me and use an arrays to input data from the file I believe, but I have no idea where to begin or how to start. Any help will be appreciated. This program tracks who may have a notebook that went missing from checking when the times have crossed.
Uni assignment
An example file might be formatted as follows:
Yusif 11 13
Amber 9 14
Marco 14 17
import java.util.Scanner;
public class NotebookTracker {
public static Scanner kbd = new Scanner(System.in);
public static boolean timesCross(int start1, int end1, int start2, int end2) {
if (end1 > start2) {
return true;
}
else {
return false;
}
}
public static int getCrossingStaff(int missingtime1, int missingtime2)
{
int havenotebook = 0;
System.out.println("Enter the number of staff in the lab: ");
int staffnum = kbd.nextInt();
for (int i = staffnum; i > 0; i--) {
System.out.println("Enter the staff member's name: ");
String staffname = kbd.next();
System.out.println("Enter the entry time: ");
int entrytime = kbd.nextInt();
System.out.println("Enter the exit time: ");
int exittime = kbd.nextInt();
if (timesCross(missingtime1, missingtime2, entrytime, exittime)) {
System.out.println(staffname + " might have the notebook.");
havenotebook += 1;
}
else {
System.out.println(staffname + " will not have the notebook.");
}
}
return havenotebook;
}
public static boolean timesCrossLate(int start1, int end1, int start2, int end2) {
if (end2 < start2 || end1 > start2) {
return true;
}
else {
return false;
}
}
public static void main(String[] args) {
System.out.println("What is the earliest the notebook could have been lost?");
int earliest = kbd.nextInt();
System.out.println("When did you notice the notebook was missing?");
int whenmissing = kbd.nextInt();
System.out.println("Number of staff who might have the notebook: " + getCrossingStaff(earliest, whenmissing));
}
}
You can read a file line by line by using the following classes ...
String expected_value = "Hello, world!";
String file ="src/test/resources/fileTest.txt";
BufferedReader reader = new BufferedReader(new FileReader(file));
do {
String currentLine = reader.readLine();
// Process the line here.
}while(currentLine != null);
reader.close();
It looks like you just need help reading the contents of the file/input using the Scanner class.
The Java docs on this class have some good examples on how to use Scanner.
https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
Below is a simple program that can read data from a various inputs.
public static void main(final String[] args) throws IOException
{
final StringBuilder sb = new StringBuilder();
sb.append("Yusif 11 13");
sb.append(System.lineSeparator());
sb.append("Amber 9 14");
sb.append(System.lineSeparator());
sb.append("Marco 14 17");
sb.append(System.lineSeparator());
final String input = Files.readAllLines(Paths.get("C:/UniAssignment.txt")).stream().map(n -> String.valueOf(n))
.collect(Collectors.joining(System.lineSeparator()));
//final InputStream input = System.in;
//final String input = sb.toString();
try (final Scanner kbd = new Scanner(input))
{
while (kbd.hasNext())
{
final String name = kbd.next();
final int start1 = kbd.nextInt();
final int end1 = kbd.nextInt();
System.out.println("Name : " + name);
System.out.println("Time Checked Out : " + start1);
System.out.println("Time Checked In : " + end1);
System.out.println();
}
}
}

How can I fix an illegal start of an expression? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
The assignment deals with create a main class and then two other classes for a canned statement and a random statement. The canned statement prints whatever canned responses. That portion works just fine. However my random portion works on its own but in this scenario it doesn't. I'm missing some statement that associates it to the right class.
This is the main class:
package it511_module8_milestone4;
import java.util.Scanner;
public class IT511_Module8_Milestone4 {
//Allow for User Input
int UserInput;
Scanner input = new Scanner(System.in);
//Implement shoutOutCannedMessage
public void shoutOutCannedMessage(String[] myArray) {
for (int index = 0; index <= 3; index++) {
//Print out the Array Container
System.out.print(myArray[index] + "\n");
}
}
public void shoutOutRandomMessage(String[] Subject, String[] Verb,
String[] Adjective, String[] Object, String[] Adverb) {
//Random number generator
int num0 = [int] (Math.random()*6); ***This is the issue***
int num1 = (int) (Math.random()*3);
int num2 = (int) (Math.random()*3);
int num3 = (int) (Math.random()*3);
int num4 = (int) (Math.random()*3);
{
//Print Random Message
System.out.println(Subject[num0]+Verb[num1]+Adjective[num2]+
Object[num3]+Adverb[num4]);
}
}
}
This is the public class:
public class RandomMessage {
public static void main(String[] args) {
//String of six names to be stored in the Array
String []Subject;
Subject = new String[6];
//Subject Array Container
Subject[0] = ("Ken");
Subject[1] = ("Erica");
Subject[2] = ("Nathan");
Subject[3] = ("Alana");
Subject[4] = ("Nolan");
Subject[5] = ("Ethan");
//Verb Array
String []Verb;
Verb = new String[3];
//Verb Array Container
Verb[0] = (" threw ");
Verb[1] = (" kicked ");
Verb[2] = (" caught ");
//Adjective Array Container
String []Adjective;
Adjective = new String[3];
//Adjective Array Container
Adjective[0] = ("the red");
Adjective[1] = ("the blue");
Adjective[2] = ("the white");
//Object Array Container
String []Object;
Object = new String[3];
//Object Array Container
Object[0] = (" football ");
Object[1] = (" soccer ball ");
Object[2] = (" baseball ");
//Adverb Array Container
String []Adverb;
Adverb = new String[3];
//Verb Array Container
Adverb[0] = ("hard.");
Adverb[1] = ("far.");
Adverb[2] = ("sadly.");
String list = new RandomMessage().shoutOutRandomMessage(Subject, Verb,
Adjective, Object, Adverb);
}
public String shoutOutRandomMessage(String[] Subject, String[] Verb,
String[] Adjective, String[] Object, String[] Adverb) {
//Random number generator
int num0 = (int) (Math.random()*6);
int num1 = (int) (Math.random()*3);
int num2 = (int) (Math.random()*3);
int num3 = (int) (Math.random()*3);
int num4 = (int) (Math.random()*3);
System.out.println(Subject[num0]+Verb[num1]+Adjective[num2]+
Object[num3]+Adverb[num4]);
//Return statement
String message = ("Great Choice!");
return message;
}
}
you are casting double to int , and format of casting is using () and add class or primitive type you want to cast inside, so replace [] by ().
int num0 = (int) (Math.random()*6);

Why cant i access worldnew method java? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I am having trouble as my code is not recognising worldnew, any ideas? The problem is in the move method, I have in comments what I am trying to achieve. What I dont understand is how bug.hospos is getting access but worldnew.setMap isn't?
package buglife;
import java.util.Scanner;
import java.util.Random;
public class main {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
ABug[] BugObj = new ABug[4]; //Creating object BugObj of class ABug
int loop = 4;
int i = 0;
int cycles;
MyClass worldnew = new MyClass();
System.out.println("Please enter the number of cycles you wish to run:");
cycles = reader.nextInt(); //getting the amount of cycles to be run
System.out.print("____Current World____\n\n");
worldnew.printWorld(); //calling method to print out world
System.out.println("____Key____\n_F_ - Food\n_O_ - Object\n_ _ - Space\nSymbol - Bug");
do{
BugObj[i] = new ABug(); //creating instance
System.out.print("Please enter the symbol which you wish to represent the bug:");
BugObj[i].symbol = reader.next();
System.out.print("Please enter the name of the bug:");
BugObj[i].name = reader.next();
System.out.println("Please enter the species of the bug:");
BugObj[i].species = reader.next();
System.out.println("Please enter the horizontal position of the bug:");
BugObj[i].horpos = reader.nextInt();
System.out.println("Please enter the vertical postion of the bug:");
BugObj[i].vertpos = reader.nextInt();
System.out.println("_______________ Bug " +(+i+1) + " _______________\n" );
System.out.println("Symbol: " + BugObj[i].symbol); //Printing bug information out
System.out.println("Name: " + BugObj[i].name);
System.out.println("Species: " + BugObj[i].species);
System.out.println("Horizontal Position: " + BugObj[i].horpos);
System.out.println("Vertical Postion: " + BugObj[i].vertpos + "\n\n");
move(BugObj[i], worldnew);
i++;
System.out.println("Would you like to enter another bug? \n 0-No, 1-Yes\n");
loop = reader.nextInt();
}while(loop == 1);
}
public static void move(ABug bug, MyClass wolrdnew){
Scanner reader = new Scanner(System.in);
System.out.println("Would you like this bug to move?\n 0-No, 1-Yes\n");
if (reader.nextInt() == 0)
{
System.exit(0);
}
int x = bug.horpos;
int y = bug.vertpos;
String a = bug.symbol;
worldnew.setMap(x,y,bug.symbol());
worldnew.printWorld();
System.out.println("New Horizontal Position: " +bug.horpos );
System.out.println("New Vertical Postion: " +bug.vertpos);
}
}
enum Item {
OBJECT ('O'),FOOD ('F'), SPACE (' ');
private final char symbol;
Item(char symbol) {
this.symbol = symbol;
}
char getSymbol() { return symbol; }
}
class MyClass {
public void setMap(int x, int y, Item symbol)
{
this.map[x][y] = symbol;
}
Item[][] map = new Item[15][25];
public void printWorld() {
int v, h; //v - vert, h - hor
for (v=1; v<=15; ++v)
{
for (h=1; h<=25; ++h)
{
final Item[] items = {Item.OBJECT, Item.FOOD, Item.SPACE, Item.SPACE, Item.SPACE, Item.SPACE, Item.SPACE, Item.SPACE};
Random random = new Random();
int selection = random.nextInt(items.length);
map[v-1][h-1] = items[selection];
System.out.print(map[v-1][h-1].getSymbol() + "_");
}
System.out.printf("\n");
}
}
}
class ABug { //ABug class
int horpos, vertpos, energy, id;
String species, name;
String symbol;
}
You have a typo mistake in name of a method argument:
public static void move(ABug bug, MyClass wolrdnew){
It's wolrdnew instead of worldnew. That's why you cannot access such variable.
the variable name in move has a typo - wolrdnew

List and arraylist initialization and use

I'm attempting to create a list because of the ability to "add" and element as opposed to checking size then dynamically expanding an array every time a new element is input. I can't get this to compile. I've scoured stack and google and nothing I've found is helping me. Someone mentioned creating an array and using that to be added to the list, but it seems to me i should be able to do this without all that.
I'm trying to get the system to add a string to the list every time a certain result occurs.
For ease of finding the List is called "incorrect"
import java.text.DecimalFormat;
import java.util.*;
public class User{
private String wrongQuestion; //quiz question
private String userName; //store user name
private String myOutput; //store output for toString and file write
private int score; //store user current score
private float average; //store user average score
private int diffLevel; //difficulty level
private int testType; //last test type
private int numTests; //store number of tests taken
private List <String> incorrect; //declare list for incorrect answers
private FileIO uFile; //declare FileIO object
public User(String inName) throws Exception
{
//local constants
final int VARIABLE_COUNT = 5; //loop sentinel
final int TOKEN_SKIP = 4; //loop sentinel
//local variables
int index; //loop index
int count; //loop counter
String token; //store tokens from line
StringTokenizer tokenLine; //store tokenized line
//instantiate file object
uFile = new FileIO (inName);
//if user exists
if (uFile.checkUser())
{
for (count = 0; count < VARIABLE_COUNT; count++)
{
//initialize tokenized line
tokenLine = new StringTokenizer(uFile.readLine());
//try to store the variables
try
{
//get and store user average
//for the first 2 tokens, skip
for (index = 0; index < TOKEN_SKIP; index++)
{
//move to next token
token = tokenLine.nextToken();//end for
switch (count)
{
case 1:
//store number of tests taken
numTests = Integer.parseInt(token);
//end case
break;
case 2:
//store difficulty of last test taken
diffLevel = Integer.parseInt(token);
//end case
break;
case 3:
//store score of last test taken
score = Integer.parseInt(token);
//end case
break;
case 4:
//store average of tests taken
average = Integer.parseInt(token);
//end case
break;
default:
break;
}//end switch
}//end for
//store next line
token = uFile.readLine();
//while there are more lines in the file
while (token != null)
{
//instantiate list for incorrect answers
incorrect = new ArrayList<String>();
//add line to end of list
incorrect.get(token);
//store next line
token = uFile.readLine();
}//end while
}//end try
//catch input mismatch exception
catch (InputMismatchException error)
{
//output error message
System.out.println ("This file is not formatted properly." +
" Either continue as a new user or log in again");
//initialize data to 0
average = 0;
testType = 0;
diffLevel = 0;
numTests = 0;
incorrect = new ArrayList <String>();
}//end catch
}//end for
}//end if
else
{
//initialize data to 0
average = 0;
testType = 0;
diffLevel = 0;
numTests = 0;
incorrect = new ArrayList<String>();
}//end else
//close input stream
uFile.closeFileReader();
}//end constructor
public float calcAverage(int newScore)
{
//local constants
//local variables
float avg; //store temp average
/**************Begin calcAverage*********/
//recalibrate avg for new calculation
avg = 0;
//calculate new average test score
avg = ((average * numTests) + newScore )/(numTests + 1);
//return average to be stored
return avg;
}
public void updateUser(int newTestType, int newDiffLevel, int newScore)
{
//local constants
//local variables
/***************Begin updateUser************/
//update new data after test is taken
score = newScore;
average = calcAverage(newScore);
diffLevel = newDiffLevel;
testType = newTestType;
numTests = numTests + 1;
}
public void writeFile() throws Exception
{
//local constants
//local variables
String line; //current line to write to file
int index; //loop index
/*************************Begin writeFile***************/
//open output stream
uFile.openOutput(userName);
//write user name
line = "User Name:\t" + userName +"\n";
uFile.writeLine(line);
//write number of tests taken
line = "Tests Taken:\t" + numTests + "\n";
//write number of tests taken
line = "Difficulty Level:\t" + diffLevel + "\n";
uFile.writeLine(line);
//write score of last test taken
line = "Last Test:\t" + score + "\n";
uFile.writeLine(line);
//write current user average
line = "User Average:\t" + average + "\n";
uFile.writeLine(line);
//for each element in the list
for (index = 0; index < incorrect.size(); index++)
{
//store then write the string
line = incorrect.get(index);
uFile.writeLine(line);
}//end for
//close file writer
uFile.closeFileWrite();
}//end writeFile
public void storeIncorrect(String inString)
{
//local constants
//local variables
/************Begin storeIncorrect*************/
//add formatted question to the list
incorrect.add(inString);
}
public String toString()
{
//local constants
//local variables
String buildUserName;
String buildAvg;
String buildNumTests;
String buildDiffLevel;
String buildScore;
DecimalFormat fmt; //declare decimal format object
/****************Begin toString***********/
//initialize decimal format
fmt = new DecimalFormat ("0.00");
//build output strings
buildUserName = Util.setLeft(20, "User Name:") + Util.setRight(25, userName);
buildNumTests = Util.setLeft(20, "Tests Taken:") + Util.setRight(18, numTests+"");
buildDiffLevel = Util.setLeft(20, "Last Difficulty:") + Util.setRight(24, diffLevel+"");
buildScore = Util.setLeft(20, "Last Score:") + Util.setRight(24, score+"");
buildAvg = Util.setLeft(20, "Test Average:") + Util.setRight(24, fmt.format(average)+"");
myOutput = buildUserName + "\n" + buildNumTests + "\n" + buildDiffLevel + "\n" + buildScore + "\n" + buildAvg;
return myOutput;
}//Display all users info
}
Few comments that might help :
// add line to end of list
incorrect.get(token); // <- change this to incorrect.add(token)
To iterate thru list use :
for (String item : incorrect) {
System.out.printlnt(item);
}
Also, you don't need to reinitialize your list as you do multiple times by
incorrect = new ArrayList<String>();
If you'd like to clear it, you could use incorrect.clear()
As you are not interested in Random access (i.e. via index), perhaps you could use LinkedList instead of ArrayList

Passing info between main and method Java [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
Stuck on my final project and either forgot how to pass data back and forth or i'm just missing something all together. Would really love a hint or answer thanks!
package coutingdays;
import coutingdays.day.Day;
import java.util.*;
public class CoutingDays {
public static void main(String[] args)
{
// declare the scanner for the keyboard
Scanner kb = new Scanner(System.in);
int farDay;
String userDay;
// create the Day object
Day theDay = new theDay();
userDay = "";
farDay = 0;
// get the users day
System.out.println("Enter today's Day in caps: ");
userDay = kb.next();
System.out.println("Enter the number of days from today to calculate: ");
farDay = kb.nextInt();
// pass the input to the object
theDay.setDay(userDay, farDay);
// print the results
theDay.printDay();
}
}
class Day
public class Day
{
// declare the private variables.
private String toDay;
private String toMorrow;
private String yesterDay;
private String laterDay;
private int d = 0;
private int e;
// create array of the days of the week
private String[] weekDays = {"SUNDAY","MONDAY","TUESDAY","WEDNESDAY","THURSDAY","FRIDAY","SATURDAY"};
// create a constructor to initialize the object to zero
public Day()
{
toDay = "";
toMorrow = "";
yesterDay = "";
laterDay = "";
e = 0;
}
// define the setDay method that will calculate today's day,
// tomorrow's day, yesterday's day, and a day in the future
public void setDay(String userDay, int farDay)
{
//declare variables to be used by the method
toMorrow = userDay;
yesterDay = userDay;
laterDay = userDay;
e = farDay;
int x = 0;
int y = 0;
int z = 0;
// print today's day based on user input
System.out.println("Today is: " + userDay);
// loop through the array to match day entered by user
// then add one to return array value of tomorrow
for (x = 0; x<7; x++)
{
if (toMorrow.equals (weekDays[6]))
{
toMorrow = weekDays[0];
break;
}
else
{
if (toMorrow.equals(weekDays[x]))
{
toMorrow = weekDays[x+1];
break;
}
}
}
//loop through the array to match day entered by user
//then subtract one to return yesterday value
for (y=0; y<7; y++)
{
if (yesterDay.equals (weekDays[0]))
{
yesterDay = weekDays[6];
break;
}
else
{
if (yesterDay.equals (weekDays[y]))
{
yesterDay = weekDays[y-1];
break;
}
}
}
//loop through the array to match value entered by user
//then use modulus to calculate days in the future
for (z = 0; z<7; z++)
{
if (laterDay.equals (weekDays[z]))
{
d = (farDay + z) % 7;
break;
}
}
}
//define the printDay method to print results
public void printDay()
{
System.out.println("Tomorrow is: " + toMorrow);
System.out.println("Yesterday was: " + yesterDay);
System.out.println(e + " days from today is: " + weekDays[d]);
}
// fin
}
}
I don't know whether you misspelled your Day while constructing the object:
Day theDay = new theDay();
should be
Day theDay = new Day();

Categories