I'm working on another assignment and am stuck. First off, I realize I probably won't get the results I want from this code, but at the moment I can't run the code to even see how close or far away I am. I'm sure I'm missing something simple and hope that something will pop out to someone here so I can move past this point. My mother tongue is English but I'm living in Sweden and trying to learn code in a Swedish class so I added //for translations.
Again, I am working with very basic code so am not looking for an easy hack, more of just some insight to where I have gone wrong.
My assignment is to ask the user to enter 10 numbers, store those as an array. Then, offer the user 4 options to calculate those numbers and a 5th option to quit the program.
Here's what I have so far:
package inlämningsuppgift3;
import java.util.Scanner;
import java.util.Arrays;
public class Inlämningsuppgift3 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int nr;
int antal = 0;
int[] num = new int[10];
int sum = 0;
int min = 0;
int max = 0;
for (nr = 0; nr < 10; nr++) {
System.out.println("Ange ett tal " + (nr+1) + " : ");
int tal = input.nextInt();
num[nr] = tal;
if (nr == 0) { //first number
min = tal;
max = tal;
}
else { // All other numbers
if (tal > max) { max = tal; }
if (tal < min) { min = tal; }
}
sum = sum + tal;
}
{
// What would you like to do?
System.out.println("Välj vad du vill göra?");
// Show largest number
System.out.println("1: Visa storsta talet.");
// Show smallest number
System.out.println("2: Visa minsta talet.");
// Show average
System.out.println("3: Visa medeltalet.");
// Show all numbers
System.out.println("4: Visa alla inmatade tal.");
// Quit
System.out.println("5: Avsluta");
}
do {
int k = input.nextInt();
if (k == 1) {
// Largest number is:
System.out.println("Storsta talet är: " + max);
}
else if (k == 2) {
// Smallest number is:
System.out.println("Minsta talet är: " + min);
}
else if (k == 3) {
// Average number is:
System.out.println("Medeltalet är: " + sum/10);
}
else if (k == 4) {
// All the entered numbers:
System.out.println("Alla tal: " + num[10] + ", ");
}
else if (k==5) {
// Goodbye
System.out.println("Hej då!");
break;
}
else {
System.out.println("Felaktigt, prova igen.");
// Unrecognized, try again.
}
while (k<5);
}
}
}
I'm getting error on the last 3 } and I'm not sure why. Are they in the wrong place? I've tried moving them around, I've tried deleting them (obviously, didn't help either) I tried changes to my {} placement above in the code and just haven't found a way around this error. Thank you in advance for any input!
java do-while syntax is:
do {
// Statements
}while(Boolean_expression);
so, change it to:
int k = 0;
do {
k = input.nextInt();
if (k == 1) {
System.out.println("Storsta talet är: " + max);
} else if (k == 2) {
System.out.println("Minsta talet är: " + min);
} else if (k == 3) {
System.out.println("Medeltalet är: " + sum / 10);
} else if (k == 4) {
System.out.println("Alla tal: " + num[10] + ", ");
} else if (k == 5) {
System.out.println("Hej då!");//good bye
break;
} else {
System.out.println("Felaktigt, prova igen.");
}
} while (k < 5) ;
and after while line must be two } now.
Hej Hej!
I made the modifications I think like you asked to make it 'just about work'
package Dunno;
import java.util.Scanner;
public class NumberCollector { //No special characters in source files,
//Can get transformed during deployment
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int nr;
int antal =0;
int[] num = new int[10];
int sum = 0;
int min=0;
int max=0;
for (nr=0; nr<10; nr++)
{
System.out.println("Ange ett tal " + (nr+1) + " : ");
int tal = input.nextInt();
num[nr]=tal;
if(nr == 0) //first number
{
min=tal;
max=tal;
}
else //all other numbers
{
if(tal>max)max =tal;
if(tal<min) min=tal;
}
sum = sum + tal;
}
System.out.println("Välj vad du vill göra?");
//what would you like to do?
System.out.println("1: Visa storsta talet.");
//Show largest number
System.out.println("2: Visa minsta talet.");
//show smallest number
System.out.println("3: Visa medeltalet.");//show average
System.out.println("4: Visa alla inmatade tal.");
//show all numbers
System.out.println("5: Avsluta");//quit
while (true) //Moved the stop condition to start of the loop makes it easier to read logically.
{
int k = input.nextInt();
if (k==1)
{
System.out.println("Storsta talet är: " + max);
//largest number is:
}
else if (k==2)
{
System.out.println("Minsta talet är: " + min);
//smallest number is:
}
else if (k==3)
{
System.out.println("Medeltalet är: " + sum/10);
//average number is:
}
else if (k==4)
{
System.out.println("Alla tal: " + num[10] + ", ");
//all the entered numbers:
}
else if (k==5)
{
System.out.println("Hej då!");//good bye
break;
}
else
{
System.out.println("Felaktigt, prova igen.");
//unrecognized, try again.
}
};
}
}
I only had to move around some braces.
It seems to broadly do what you want? It throws an exception if you ask for result 4, I'll leave that to you :)
Maybe this will be a good starting point? Consider replacing the loop with a switch/case condition would be nicer to read and maintain?
I am currently working on a java program that has to do with taking classes and the amount of credits for each class. I have everything set up how I need it, except the order.
I would like it to ask for a class, then how many credits that class is, then ask for the next class, and those credits, and so on. Right now, it will ask for all of the classes, then all of the credits. Here's the code I have:
//Jake Petersen
import java.util.Scanner;
public class test1{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("How many courses are you going to list?");
int courses = Integer.parseInt(scan.nextLine());
String courseArray[] = new String[courses];
for (int i = 0; i < courseArray.length; i++){
System.out.println("Please enter a course:");
courseArray[i] = scan.nextLine();
}
int creditArray[] = new int[courses];
for (int i = 0; i < creditArray.length;) {
System.out.println("Please enter how many credits "+ courseArray[i] + " is:");
int input = scan.nextInt();
if (input >= 1 && input <= 4) {
creditArray[i++] = input;
}
}
int sum = 0;
for (int i : creditArray){
sum += i;
}
for (int i = 0; i < courseArray.length; i++) {
System.out.print(courseArray[i] + " is a " + creditArray[i] + " credit class. \n");
}
print(sum);
}
public static void print(int sum){
if(sum >= 12 && sum <= 18){
System.out.println("You are taking " + sum + " total credits, which makes you a full time student.");
}else if(sum < 12){
System.out.println("You are taking " + sum + " total credits, which makes you not a full time student.");
}else{
System.out.println("You are taking " + sum + " total credits, which means you are overloaded");
}
}
}
Do all the prompts in a single for loop:
import java.util.Scanner;
public class test1{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.print("How many courses are you going to list?");
int courses = Integer.parseInt(scan.nextLine());
String courseArray[] = new String[courses];
int creditArray[] = new int[courses];
for (int i = 0; i < courseArray.length; i++){
System.out.print("Please enter a course:");
courseArray[i] = scan.nextLine();
System.out.print("Please enter how many credits "+ courseArray[i] + " is:");
String credits = scan.nextLine();
int input = Integer.parseInt(credits);
if (input >= 1 && input <= 4) {
creditArray[i] = input;
}
else {
creditArray[i] = 0;
}
} int sum = 0;
for (int i : creditArray){
sum += i;
}
for (int i = 0; i < courseArray.length; i++) {
System.out.print(courseArray[i] + " is a " + creditArray[i] + " credit class. \n");
}
print(sum);
}
public static void print(int sum){
if(sum >= 12 && sum <= 18){
System.out.println("You are taking " + sum + " total credits, which makes you a full time student.");
}else if(sum < 12){
System.out.println("You are taking " + sum + " total credits, which makes you not a full time student.");
}else{
System.out.println("You are taking " + sum + " total credits, which means you are overloaded");
}
}
}
Of course this assumes that the 2 arrays have the same size. Perhaps you want to prompt for a class count first, to know how large to make the arrays, or grow them dynamically.
I am writing the lemonade stand game in Java but I am having a bit of trouble trying to figure out the perfect recipe. I mean something like if weather is Sunny and temperature is greater than 85 the perfect recipe would be 8 lemons, 6 cups of sugar and 12 ice cubes per cup. I have most of the code done, except the math logic seems a little off. Please let me know how can I improve the code. I included all the code so you can get a better idea on how all the logic goes so far.
public static void main(String[] args) {
///declaration of variables
int playAgain;
int days, customers = 120;
int CUPS_PITCHER = 14;
double money = 20.00, earned = 0;
double [] cupsPrice = {0.93, 1.65, 2.77}, lemonsPrice = {0.98, 2.05, 4.38}, sugarPrice = {0.74, 1.63, 3.31}, icePrice = {0.99, 2.01, 3.95};
//inventory
///string input
String cupsS = "", lemonsS = "", sugarS = "", iceS = "";
//int input values
int cups = 0, lemons = 0, sugar = 0, ice = 0;
//String for Pitcher
double priceCup;
int lemonsPitcher, sugarPitcher, iceCup;
////array for items options
String [] cupsOptions = {"25","50","100"};
String [] lemonsOptions = {"10","30","75"};
String [] sugarOptions = {"8","20","48"};
String [] iceOptions = {"100","250","500"};
int temperature;
String [] weather = {"Sunny","Hazy","Cloudy","Overcast","Rainny"};
JOptionPane.showMessageDialog(null,"Welcome to our Lemonade Stand Game");
days = getDays();
///set flag for loops
boolean ingredients, cupsFlag, lemonsFlag, sugarFlag, iceFlag;
boolean [] flag = {false,false,false,false};
NumberFormat defaultFormat = NumberFormat.getCurrencyInstance();
String [] itemName = {"Cups","Lemons","Sugar","Ice Cubes"};
String [][] itemOptions = {cupsOptions,lemonsOptions,sugarOptions,iceOptions};
for(int i=1; i<=days; i++){
/////random weather
Random rand = new Random();
int randomWeather = rand.nextInt(5);
//random temperature from 59 to 99
temperature = rand.nextInt(99-59) + 59;
int response = 0;
///loop while not play game
while(response != 1){
String[] options = new String[] {"Buy", "Play Game", "Cancel"};
response = JOptionPane.showOptionDialog(null, "You currently have " + defaultFormat.format(money) + " Day " + i + "\nCups: " + cups + " *** Lemons: " + lemons + "\nSugar: " +
sugar + " *** Ice: "+ice + "\nHigh Temperature: " + temperature + "\nWeather Forecast: " + weather[randomWeather], "Inventory",
JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE,
null, options, options[0]);
ingredients = false;
///if buy ingredientes ** when they click buy
while(response == 0 && !ingredients){
String[] optionsBuy = new String[] {"Buy Cups", "Buy Lemons", "Buy Sugar", "Buy Ice","Back to Game"};
String line1 = "\n25 Cups: $" + cupsPrice[0] + " 10 Lemons: $" + lemonsPrice[0]
+ " 8 Cups of Sugar: $" + sugarPrice[0] + " 100 Ice Cubes: $"+icePrice[0];
String line2 = "\n50 Cups: $" + cupsPrice[1] + " 30 Lemons: $" + lemonsPrice[0]
+ " 20 Cups of Sugar: $" + sugarPrice[1] + " 250 Ice Cubes: $"+icePrice[1];
String line3 = "\n100 Cups: $" + cupsPrice[2] + " 75 Lemons: $" + lemonsPrice[2]
+ " 48 Cups of Sugar: $" + sugarPrice[2] + " 500 Ice Cubes: $"+icePrice[2];
int responsePurchase = JOptionPane.showOptionDialog(null, "You currently have " + defaultFormat.format(money) + " Day " + i + line1 + line2 + line3 + "\nHigh Temperature: " + temperature + "\nWeather Forecast: " + weather[randomWeather], "Inventory",
JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE,
null, optionsBuy, optionsBuy[0]);
double [][] priceOptions = {cupsPrice,lemonsPrice,sugarPrice,icePrice};
int [] qty = {0,0,0,0};
for(int j=0; j<4; j++){
if(responsePurchase == j)
qty[j] = buyItems(itemName[j],itemOptions[j],flag[j],money);
//money = money - itemPrice[j][0];
}
///deduct money
for(int k=0;k<4;k++){
for(int j=0;j<3;j++){
if(qty[k] == Integer.parseInt(itemOptions[k][j])){
money = money - priceOptions[k][j];
}
}
}
////add items purchased
cups += qty[0];
lemons += qty[1];
sugar += qty[2];
ice += qty[3];
//System.out.println(itemOptions[0][1]);
/*
if(qty[0] == 25){
money = money - cupsPrice[0];
}
if(qty[0] == 50){
money = money - cupsPrice[1];
}
if(qty[0] == 100){
money = money - cupsPrice[2];
}
// buy lemons
cupsFlag = false;
if (responsePurchase == 0) {
int qty = buyItems("Cups",cupsOptions,cupsFlag,money);
if (qty != 0) {
cups += qty;
}
}
// buy lemons
lemonsFlag = false;
if (responsePurchase == 1) {
int qty = buyItems("Lemons",lemonsOptions,lemonsFlag,money);
if (qty != 0) {
lemons += qty;
}
}
*/
///go back to game when back to game click
if(responsePurchase == 4){
ingredients = true;
}
}///end while buy ingredients
}///end while buy
JTextField fieldCup = new JTextField("0.25");
JTextField fieldLemons = new JTextField("4");
JTextField fieldSugar = new JTextField("4");
JTextField fieldIce = new JTextField("4");
Object[] fields = {"Price per Cup in Cents", fieldCup,"Lemons per Pitcher", fieldLemons,"Sugar per Pitcher", fieldSugar, "Ice per Cup", fieldIce};
int responsePitcher = JOptionPane.showConfirmDialog(null,fields,"Price",JOptionPane.OK_CANCEL_OPTION);
if(responsePitcher == JOptionPane.CANCEL_OPTION){
int stopGame = JOptionPane.showConfirmDialog(null,"Do you wish to cancel the game? All progress will be lost","",JOptionPane.YES_NO_OPTION);
if(stopGame == JOptionPane.YES_OPTION){
System.exit(0);
}
}
while(!validateDouble(fieldCup.getText()) || !validateInt(fieldLemons.getText()) || !validateInt(fieldSugar.getText()) || !validateInt(fieldIce.getText())){
if(responsePitcher == JOptionPane.CANCEL_OPTION){
int stopGame = JOptionPane.showConfirmDialog(null,"Do you wish to cancel the game? All progress will be lost","",JOptionPane.YES_NO_OPTION);
if(stopGame == JOptionPane.YES_OPTION){
System.exit(0);
}
}
JOptionPane.showMessageDialog(null,"One of the inputs is incorrect! try Again","ERROR",JOptionPane.ERROR_MESSAGE);
responsePitcher = JOptionPane.showConfirmDialog(null,fields,"Price",JOptionPane.OK_CANCEL_OPTION);
}
priceCup = Double.parseDouble(fieldCup.getText());
lemonsPitcher = Integer.parseInt(fieldLemons.getText());
sugarPitcher = Integer.parseInt(fieldSugar.getText());
iceCup = Integer.parseInt(fieldIce.getText());
for(int k=0; k<5; k++){
if(weather[randomWeather].equals(weather[k])){
////if weather is not sunny reduce possible customers
if(!weather[randomWeather].equals(weather[0])){
customers = customers - (customers * k/15);
}
}
}
//System.out.println(customers);///testing results
//System.out.println(fieldCup.getText());///testing results
System.out.println(customers);///testing results
//showBar();
///perfect recepie
if(temperature > 58){
///if sunny
if(weather[randomWeather].equals(weather[0])){
}
}
//too expensive or not right ingredients reduce possible customers
if(priceCup > 0.25){
customers = customers - (customers * 10/100);///reduce customers by 10%
}
if(lemonsPitcher > 7 || lemonsPitcher < 5){
customers = customers - (customers * 10/100);///reduce customers by 10%
}
if(sugarPitcher > 7 || sugarPitcher < 5){
customers = customers - (customers * 10/100);///reduce customers by 10%
}
if(iceCup > 10 || iceCup < 6){
customers = customers - (customers * 15/100);///reduce customers by 15%
}
///determine max cups according to inventory
int maxCupsLemons = (lemons / lemonsPitcher) * CUPS_PITCHER;
int maxCupsSugar = (sugar / sugarPitcher) * CUPS_PITCHER;
int maxCupsIce = (ice / iceCup);
int maxCupsp = cups;
int [] maxCups = {maxCupsLemons, maxCupsSugar, maxCupsIce, maxCupsp};
System.out.println(Arrays.toString(maxCups));
int minValue = maxCups[0];
for(int m=0;m<maxCups.length;m++){
if(maxCups[m] < minValue){
minValue = maxCups[m];
}
}
System.out.println(minValue);
if(minValue < customers){
customers = minValue;
}
System.out.println(customers);///testing results
////profit
earned = priceCup * customers;
money += earned;
///deduct inventory
//14 cups per pitcher
int lemonsSpent = (customers / CUPS_PITCHER) * lemonsPitcher;
int sugarSpent = (customers / CUPS_PITCHER) * sugarPitcher;
lemons = lemons - lemonsSpent;
sugar = sugar - sugarSpent;
cups = cups - customers;
JOptionPane.showMessageDialog(null,"Your profit for day " + i + " is " + defaultFormat.format(earned));
/////reset variables for next day
customers = 120;
earned = 0;
ice = 0;
}
//JOptionPane.showMessageDialog(null,days);
}
}
I think your problem is on the pricing.
Better leave it as 14 cups. Then generate the price per cup.
First, you should have a standard measure on how many cups of an ingredient will be in one pitcher. That way, you will have a basis.
Let's say. 8 lemons + 6 cups of sugar + 12 ice cubes = 1 pitcher
Multiply the cup price. 8 * 0.98, etc. then add it to other ingredients price.
But, it will be better and easier if you will remove the pitcher from the price computation. Since you will sell it by cups.
I'll give you a tip in formulating a program's logic. Most of the time, the obvious way to do it is the easiest way. Put yourself in the position of the program, if you were the program, what will you do?
In improving your program's logic, check every thing your program does. Ask yourself, is it the most likely thing I will do?
If your program works, never fear to take risks. Try other ways, try other algorithms, and read. Then decide which of those will improve your work. Most of the time trying something new begets failure, but that's the bittersweet way of learning.
Happy coding!
The purpose of my program is to ask what the temperature(F) is and what the weather condition outside is like.
The weather condition can be either sunny(1), raining(2), cloudy(3) or snowing(4.) The numbers 1-4 will be used to clarify what the weather condition is (I'm not sure how to do it any other way...)
Then, depending on the combination of temp and weatherCondition I want to be able to display 3 garments out of 10 choices, based on the combo of temp and weatherCondition.
I'm still learning so I apologize if my question or problem seems mundane...
At the moment when a user enters the temp and weatherCondition, a response is given depending on the combo of the two inputs (ex. hot-sunny, freezing-snowing).
Instead, I would like to create one or more txt files and have each one named something like hotSunny.txt for example. Inside these txt files I've listed 10 types of garments. I ultimately want the program to recognize which combo matches its appropriate txt file and then randomly display 3 of the 10.
What I've got so far...
public static void main(String[] args)
{
double temperature;
int weatherCondition;
String input;
input = JOptionPane.showInputDialog("What is " +
"the current temperature?");
temperature = Double.parseDouble(input);
input = JOptionPane.showInputDialog("Sweet I now know the temperature! " +
"Now please take a look out the nearest window is it Sunny , Rainy ," +
" Cloudy or Snowy? " +
"(1 = Sunny) (2 = Raining) " +
"(3 = Cloudy) (4 = Snowing)");
weatherCondition = Integer.parseInt(input);
if (temperature <= 32){
if (weatherCondition == 4){
freezingSnowing();
} else if (weatherCondition == 3){
freezingCloudy();
} else if (weatherCondition == 2){
freezingRain();
} else {
freezingSunny();
}
}..........
else if ((temperature >= 33) && (temperature <= 50)) {
else if ((temperature >= 51) && (temperature <= 75)) {
else if ((temperature >= 76) && (temperature <= 140)) {
public static void freezingSnowing()
{
JOptionPane.showMessageDialog(null, "It's is snowing! I recommend that you dress very warm" +
"and wear a large coat that is preferably water proof.");
}
Your freezingSnowing method should look like this:
public static void freezingSnowing() {
file = new File(MyWeatherApp.class.getResource
(path + "freezingSnowing.txt"));
// path to the txt file
// where path is the local path to the file
scanner = new Scanner(file);
ArrayList<String> garments = new ArrayList<>(10);
while(scanner.hasNextLine()) {
garments.add(scanner.nextLine());
}
ArrayList<Integer> indices = new ArrayList<>(3);
for(int i = 0; i < 3; i++) {
while(true) { // watch out for duplicates
int rand = (int)(Math.random() * 9);
if(!indices.contains(rand))
break;
}
indices.add(rand);
JOptionPane.showMessageDialog(null, "It's is snowing! " +
"I recommend that you dress very warm " +
"and wear " + garments.get(indices.get(1)) +
", " garments.get(indices.get(2)) +
" and " + garments.get(indices.get(3)) +
".");
}
This is my version of randomly picking item.
public static void main(String[] args) {
String[] weatherCond = new String[] {"cold", "hot"};
ArrayList<String> garmets = new ArrayList<String>();
garmets.add("clothes");
garmets.add("hat");
garmets.add("gloves");
garmets.add("coat");
ArrayList<String> pick;
int ITEM = 3;
int temperature = 29;
if (temperature >= 30) { // hot condition
System.out.println("weather condition " + weatherCond[0]);
pick = garmets;
for (int i = 0; i < ITEM; i++) {
int idx = (int) (Math.round(Math.random() * pick.size()) % pick.size());
System.out.print(pick.get(idx) + " " );
pick.remove(idx);
}
} else {
System.out.println("weather condition " + weatherCond[1]);
pick = garmets;
for (int i = 0; i < ITEM; i++) {
int idx = (int) (Math.round(Math.random() * pick.size()) % pick.size());
System.out.print(pick.get(idx) + " " );
pick.remove(idx);
}
}
}
Also, if you want to use a fix set of garmets for a specific weather condition, you could use a hashmap which uses weather condition as a key and garmet groups as a value.
This is what I have:
import java.util.*;
import java.text.*;
public class Proj4 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String again = "y";
final int MAX_STUDENTS = 100;
final int MIN_EXAM = 0;
final int MAX_EXAM = 50;
final int MIN_FINAL = 0;
final int MAX_FINAL = 100;
String[] names = new String[MAX_STUDENTS];
int[] exams = new int[MAX_STUDENTS * 4];
int student = 1;
DecimalFormat df = new DecimalFormat("#0.0");
do {
System.out.print("Please enter the name of student " + student
+ ": ");
String line;
line = s.nextLine().toUpperCase();
names = line.split(" ");
for (int i = 0; i < 4; i++) {
if (i == 3) {
System.out.print("Please enter score for Final Exam: ");
exams[i] = s.nextInt();
}
else {
System.out.print("Please enter score for Exam " + (i + 1)
+ ": ");
exams[i] = s.nextInt();
if (student == 1) {
if ((exams[0] < MIN_EXAM || exams[0] > MAX_EXAM)
|| (exams[1] < MIN_EXAM || exams[1] > MAX_EXAM)
|| (exams[2] < MIN_EXAM || exams[2] > MAX_EXAM)) {
System.out.println("Invalid enter 0-50 only...");
System.out.print("Please re-enter score: ");
exams[i] = s.nextInt();
} else if (exams[3] < MIN_FINAL || exams[3] > MAX_FINAL) {
System.out.println("Invalid enter 0-100 only...");
System.out.print("Please re-enter score: ");
exams[i] = s.nextInt();
}
} else if (student == 2) {
if ((exams[0] < MIN_EXAM || exams[0] > MAX_EXAM)
|| (exams[1] < MIN_EXAM || exams[1] > MAX_EXAM)
|| (exams[2] < MIN_EXAM || exams[2] > MAX_EXAM)) {
System.out.println("Invalid enter 0-50 only...");
System.out.print("Please re-enter score: ");
exams[i + 4] = s.nextInt();
} else if (exams[3] < MIN_FINAL || exams[3] > MAX_FINAL) {
System.out.println("Invalid enter 0-100 only...");
System.out.print("Please re-enter score: ");
exams[i + 4] = s.nextInt();
}
}
}
}
System.out.print("do you wish to enter another? (y or n) ");
again = s.next();
if (again.equalsIgnoreCase("y"))
student++;
} while (again.equalsIgnoreCase("y"));
System.out.println("***Class Results***");
System.out
.println(names[1]
+ ","
+ names[0]
+ " "
+ "Exam Percentage: "
+ ((float) (exams[0] + exams[1] + exams[2] + exams[3]) / (MAX_EXAM * 3 + MAX_FINAL))
* 100 + "%");
if (student == 2)
;
System.out
.println(names[3]
+ ","
+ names[2]
+ " "
+ "Exam Percentage: "
+ ((float) (exams[4] + exams[5] + exams[6] + exams[7]) / (MAX_EXAM * 3 + MAX_FINAL))
* 100 + "%");
if (student == 3)
;
System.out
.println(names[5]
+ ","
+ names[4]
+ " "
+ "Exam Percentage: "
+ ((float) (exams[8] + exams[9] + exams[10] + exams[11]) / (MAX_EXAM * 3 + MAX_FINAL))
* 100 + "%");
if (student == 4)
;
System.out
.println(names[7]
+ ","
+ names[6]
+ " "
+ "Exam Percentage: "
+ ((float) (exams[12] + exams[13] + exams[14] + exams[15]) / (MAX_EXAM * 3 + MAX_FINAL))
* 100 + "%");
}
}
My program seems to be running exactly the way i want/need it to, the only problem is, when i allow the program to run again it outputs two strings on the same line like this:
Please enter the name of student 2: Please enter score for Exam 1:
I don't know what to do to fix this. is there something in my code that messes up only on the second and probably 3rd and 4th times?
Remove semicolons after ifs
if (student == 3)
; // <- remove it
System.out.println(//...
because now Java understands it as
if (student == 3){}
System.out.println(//...
change
System.out.print("do you wish to enter another? (y or n) ");
again = s.next();
to
System.out.print("do you wish to enter another? (y or n) ");
again = s.nextLine();
next will not consume new line mark, so when you use nextLine after next it will consume only this new line mark and go to another instruction. Same rule apply for nextInt.
To store array of student names you could use two dimensional array of Strings
String[][] names = new String[MAX_STUDENTS][];
and store student names in each row based on student number
names[student] = line.split(" ");
To get first name of first student you will have to use this form
names[0][0]; //you probably know that indexes in array starts from zero
To get names of all students you can iterate over each rows and then over columns
for(int stId=0; stId<student; stId++){
for(int nameNumber=0; nameNumber<names[stId].length; nameNumber++){
// print names[stId][nameNumber]`
If you want the strings to print on a new line use println instead of print, or include a linebreak character in your string.