I am trying to run a Java program to display 9 input boxes requesting names and examination scores and display on the message box the names and appropriate grades of each score. I tried doing something like this:
import javax.swing.JOptionPane;
public class StudentGrade {
public static void main(String[] args) {
String inputname;
String inputscore;
int number;
inputcourse = JOptionPane.showInputDialog("Enter name");
inputscore = JOptionPane.showInputDialog("Enter score");
number = Integer.parseInt(inputscore);
if (number < 40){
System.out.println ((inputcourse) + " " + "D"); }
else if (number <50){
System.out.println((inputcourse) + " " + "C");}
else if (number <60){
System.out.println((inputcourse) + " " + "B");}
else System.out.println((inputcourse) + " " + "A");}
}
However, this can only run once. Please, how can I make it run nine times? Thanks.
Try this it'll work. In your code Check Inputname and InputCourse
or change inputCourse to inputName
import javax.swing.JOptionPane;
public class world {
public static void main(String[] args) {
String inputname;
String inputscore;
int number;
for(int i=0;i<9;i++){
inputname = JOptionPane.showInputDialog("Enter name");
inputscore = JOptionPane.showInputDialog("Enter score");
number = Integer.parseInt(inputscore);
if (number < 40){
System.out.println ((inputname) + " " + "D");
}else if (number <50){
System.out.println((inputname) + " " + "C");
}else if (number <60){
System.out.println((inputname) + " " + "B");
}else {
System.out.println((inputname) + " " + "A");
}
}
}
}
To loop in control structure you can use a for, while loop, or a do-while loop. For a for-loop you should try:
public class StudentGrade{
public static void main(String[] args){
for (int i=0; i<9; i++){ repeat 9 times
// all the code you have in your main method now
}
}
}
For a while loop you should try:
public class StudentGrade{
public static void main(String[] args){
int i=0;
while (i++ < 9){ //repeat 9 times
// all the code you have in your main method now
}
}
}
For a do-while loop you should try:
public class StudentGrade{
public static void main(String[] args){
int i=1;
do{ //repeat 9 times
// all the code you have in your main method now
}while (i++ < 9);
}
}
Hope this helps.
put the code inside a for loop:
for(int i=0; i<9; i++){
inputcourse = JOptionPane.showInputDialog("Enter name");
inputscore = JOptionPane.showInputDialog("Enter score");
number = Integer.parseInt(inputscore);
if (number < 40){
System.out.println ((inputcourse) + " " + "D");
} else if (number <50){
System.out.println((inputcourse) + " " + "C");
} else if (number <60){
System.out.println((inputcourse) + " " + "B");
} else {
System.out.println((inputcourse) + " " + "A");
}
}
Related
How to add a roll dice method and a check guess method?
My code:
package oui;
import java.util.Scanner;
public class dicecalc {
public static void main(String args[]) {
Scanner kb = new Scanner(System.in);
int numGuess;
System.out.println("Enter the number the numer the dice will roll: ");
numGuess = kb.nextInt();
int dice1=(int)(Math.random()*6+1);
int dice2=(int)(Math.random()*6+1);
int sum = dice1 + dice2;
System.out.println("Roll: total = " + sum);
{
if (sum != numGuess) {
System.out.println("Sorry with a " + sum + " You LOSE :(");
} else {
System.out.println("Woah!!! With a " + sum + " You WIN!!!!!!!");
}
}
}
}
I need to have this assignment resubmitted because I forgot those things but I don't know how to add it. Please help. I already have tried for days.
Here's one possible basic layout. Replace the ??? with some code!
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.print("Enter the number the numer the dice will roll: ");
int numGuess = kb.nextInt();
int sum = sumOfTwoDiceRolls();
System.out.println("Roll: total = " + sum);
{
if (!checkGuess(numGuess, sum)) {
System.out.println("Sorry with a " + sum + " You LOSE :(");
} else {
System.out.println("Woah!!! With a " + sum + " You WIN!!!!!!!");
}
}
}
public static int sumOfTwoDiceRolls() {
return ??? ;
}
public static int singleDiceRoll() {
// Math.random() * (max - min + 1) + min
return (int)(Math.random() * (6 - 1 + 1) + 1);
}
public static boolean checkGuess(int guess, int numberToGuess) {
return ??? ;
}
}
My first class that creates the ArrayList and populates it with the Skill objects
import java.util.ArrayList;
public class Skill {
String skillName;
int skillValue;
public static ArrayList<Skill> skillList = new ArrayList<Skill>();
public Skill(String newSkillName, int newSkillValue){
setSkillName(newSkillName);
setSkillValue(newSkillValue);
}
public static void initializeSkillList(){
//Creating the Skill obj's
Skill str = new Skill("Str", 1);
Skill dex = new Skill("Dex", 1);
Skill intl = new Skill("Int", 1);
Skill con = new Skill("Con", 3);
//Adding them to the Skill ArrayList
skillList.add(str);
skillList.add(dex);
skillList.add(intl);
skillList.add(con);
//Debug statement to check if the values are correct
System.out.println(skillList.get(1).skillValue);
}
}
I am attempting to access the objects skillValue and skillName from the ArrayList in my Main.java class. I have setters and getters.
This is the Main class
import java.util.Scanner;
public class Main {
static Character playerCharacter;
static boolean charCreationComplete = false;
static boolean endGame = false;
static Scanner scnr = new Scanner(System.in);
public static void main(String[] args){
System.out.println("\n\nWelcome to Garterra!\n\n");
Archetype.initializeArchetypeList();
Skill.initializeSkillList();
if (!charCreationComplete){
charCreation(scnr);
charCreationComplete = true;
}
charCreation(scnr); then accesses the skillList through getters and setters
charCreation() Method:
private static void charCreation(Scanner scnr){
System.out.println("\nEnter player name:\n\n");
String newName = scnr.nextLine();
System.out.println("You Entered " + newName + " for your name!\n");
System.out.println("Next, Choose your Archetype: 0 = Ranger\n");
int archetypeIndex = scnr.nextInt();
Character.currArchetype = Archetype.archetypeList.get(archetypeIndex);
Character.archetypeName = Archetype.archetypeList.get(archetypeIndex).getArchetypeName();
System.out.println("You have chosen " + Character.archetypeName + ".\nThis gives you " + Character.currArchetype.totalSpendableSkillPoints + " total spendable skill points!\n");
System.out.println("Now, spend those skill points.\n");
if (Character.currArchetype.getArchetypeName().contains("Ranger")){
Ranger.dexModifierCalc(1);
Ranger.conModifierCalc(1);
}
while (Character.currArchetype.totalSpendableSkillPoints > 0){
System.out.println("How many points would you like to put into Strength?\nThis impacts your melee weapon damage and carry weight.\n");
int strAddPoints = scnr.nextInt();
Skill.skillList.get(0).setSkillValue(Skill.skillList.get(0).getSkillValue() + strAddPoints);
Character.currArchetype.setTotalSpendableSkillPoints(Character.currArchetype.totalSpendableSkillPoints - strAddPoints);
strAddPoints = 0;
System.out.println("You now have " + Skill.skillList.get(0).getSkillValue() + "\n");
if (Character.currArchetype.totalSpendableSkillPoints == 0){
break;
}
if (Character.currArchetype.totalSpendableSkillPoints > 0){
System.out.println("How many points would you like to put into Dexterity?\nThis impacts your ranged weapon damage.\n");
int dexAddPoints = scnr.nextInt();
Skill.skillList.get(1).setSkillValue(Skill.skillList.get(1).getSkillValue() + dexAddPoints);
Character.currArchetype.setTotalSpendableSkillPoints(Character.currArchetype.totalSpendableSkillPoints - dexAddPoints);
dexAddPoints = 0;
System.out.println("You now have " + Skill.skillList.get(1).getSkillValue() + "\n");
}
if (Character.currArchetype.totalSpendableSkillPoints == 0){
break;
}
if (Character.currArchetype.totalSpendableSkillPoints > 0){
System.out.println("How many points would you like to put into Intelligence?\nThis impacts your magic damage.\n");
int intAddPoints = scnr.nextInt();
Skill.skillList.get(2).setSkillValue(Skill.skillList.get(2).getSkillValue() + intAddPoints);
Character.currArchetype.setTotalSpendableSkillPoints(Character.currArchetype.totalSpendableSkillPoints - intAddPoints);
intAddPoints = 0;
System.out.println("You now have " + Skill.skillList.get(2).getSkillValue() + "\n");
}
if (Character.currArchetype.totalSpendableSkillPoints == 0){
break;
}
if (Character.currArchetype.totalSpendableSkillPoints > 0){
System.out.println("How many points would you like to put into Strength?\nThis impacts your melee weapon damage and carry weight.\n");
int conAddPoints = scnr.nextInt();
Skill.skillList.get(3).setSkillValue(Skill.skillList.get(3).getSkillValue() + conAddPoints);
Character.currArchetype.setTotalSpendableSkillPoints(Character.currArchetype.totalSpendableSkillPoints - conAddPoints);
conAddPoints = 0;
System.out.println("You now have " + Skill.skillList.get(3).getSkillValue() + "\n");
}
}
int newHealthPoints = Character.healthPointsCalc();
System.out.println("You have " + newHealthPoints + " health points!\n\n");
int newTotalCarryWeight = Character.carryWeightCalc(Character.currArchetype.getLevel());
System.out.println("Your total carry weight is " + newTotalCarryWeight + ".\n");
int newExperince = 0;
playerCharacter = new Character(newName, newHealthPoints, newExperince, 1, Archetype.archetypeList.get(archetypeIndex), newTotalCarryWeight);
}
If you create a getter for "skillList" then you can just say
Skill.getSkillList();
And then do whatever you want with this list.
To make your code a little better, change this
public static ArrayList<Skill> skillList = new ArrayList<>();
to this
public static List<Skill> skillList = new ArrayList<>();
I'm just a beginner in coding and trying to make my 1st project with several classes that is a hangman game. I know there are a lot of threads on the topic here but couldn't manage to find a solution that would work with StringBuilder. I'm stuck with catching multiple letters in the word. Could anyone possibly help?
the method under question is checkAnswer and is below:
public void checkAnswer (){
if (logic.line.indexOf(answer)!= -1){
System.out.println ("You are right! The letter " + answer + " exists");
StringBuilder guessedChar = new StringBuilder(logic.newLine);
guessedChar.setCharAt(logic.line.indexOf(answer), answer);
lettersGuessed = answer +lettersGuessed;
score = score + 1;
System.out.println("Letters guessed: " + lettersGuessed);
System.out.println("Letters missed: " + lettersMissed);
System.out.println("Your score is:" + score);
logic.newLine = guessedChar.toString();
System.out.println(logic.newLine);
}}
Below is the full code:
main class
public class Main {
public static void main(String[] args) throws Exception {
Logic act = new Logic();
Game game = new Game();
act.getListOfMovies();
act.CodedLine();
do { game.input();
game.checkCondition();
game.checkAnswer();
game.checkScore();
} while (game.lettersGuessed.length() != act.line.length() && game.score!= -10);
}}
Class Logic
public class Logic {
static String line;
static String newLine;
public String[] listOfMovies;
public Scanner fileScanner;
public Logic() {
}
public String getListOfMovies() throws Exception {
File fileWithMovies = new File("MoviesList.txt");//file access
Scanner fileScanner = new Scanner(fileWithMovies);//file scan
while (fileScanner.hasNext()) { // while there is a next line
line = fileScanner.nextLine();
String[] listOfMovies = new String[24]; //introduce array
for (int i = 0; i < listOfMovies.length; i++) { //
listOfMovies[i] = fileScanner.nextLine();
}
int random = (int) (Math.random() * listOfMovies.length); //get random number
for (int i = 0; i < line.length(); i++) { //get random movie
if (Character.isLetter(line.charAt(i))) {
line = listOfMovies[random];
System.out.println(line);
}
return line;
}
return line;
}return line;
}
public String CodedLine() {
newLine = line.replaceAll("[a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z]", "_");
System.out.println(newLine);
return newLine;
}}
Class Game
public class Game {
char answer;
Logic logic = new Logic();
String lettersGuessed = " ";
String lettersMissed = " ";
int score = 0;
public char input () {
Scanner inputScanner = new Scanner(System.in);
System.out.println("Type in your guess");
answer = inputScanner.next().charAt(0);
System.out.println("Your guess: " + answer);
return answer;
}
public void checkCondition (){
if (logic.line.indexOf(answer)==-1){
System.out.println("You are wrong. The letter " + answer + " does not exist");
lettersMissed = answer + lettersMissed;
score = score - 1;
System.out.println("Letters guessed: " + lettersGuessed);
System.out.println("Letters missed: " + lettersMissed);
System.out.println("Your score is:" + score);
}}
public void checkAnswer (){
if (logic.line.indexOf(answer)!= -1){
System.out.println ("You are right! The letter " + answer + " exists");
StringBuilder guessedChar = new StringBuilder(logic.newLine);
guessedChar.setCharAt(logic.line.indexOf(answer), answer);
lettersGuessed = answer +lettersGuessed;
score = score + 1;
System.out.println("Letters guessed: " + lettersGuessed);
System.out.println("Letters missed: " + lettersMissed);
System.out.println("Your score is:" + score);
logic.newLine = guessedChar.toString();
System.out.println(logic.newLine);
}}
public void checkScore (){
if (score == -10) {
System.out.println("The game is over! You lost..."); }}}
//Create list for index
ArrayList<Integer>answerIndexList=new ArrayList<Integer>();
//get char index
for (int i=0;i<logic.line.length();i++){
if(logic.line.charAt(i) == answer){
answerIndexList.add(i);
}
}
//replace index with answer
for(int i=0;i<answerIndexList.size();i++){
guessedChar.setCharAt(answerIndexList.get(i), answer);
}
logic.newLine = guessedChar.toString();
Not gonna solve it for you, not what this site is for, but suggestions:
check this method - basically you tell it where the indexOf should start searching. At first you start with 0, then if you find a result you start at foundResultIndex + 1, put it all in a loop and voila.
word: batman, guess: a
int startAt = 0;
int foundResultIndex = "batman".indexOf('a', startAt) // 1
startAt = foundResultIndex + 1;
foundResultIndex = "batman".indexOf('a', startAt) // 4
...
don't keep so much state in your programs, especially static like in Logic class. Your getListOfMovies is perfect example, you are already returning a result, why keep it in some line variable? Use the returned result instead.
the replaceAll is funny, do this instead line.replaceAll("[a-z]", "_");
I have printed my array of 20 integers and then printed a single random number after this. I need to search/count the initial array for how many times the single # is present. So far I have been able to all but search/count for the single random number, it continues to search for any random number within the first array and count that number rather than searching for my single #.
My code:
import java.util.Scanner;
import java.util.Random;
class Main{
public static final Random RND_GEN = new Random();
public int[] createNum(int[] randomNumbers) {
for (int i = 0; i < randomNumbers.length; i++) {
randomNumbers[i] = RND_GEN.nextInt(10) + 1;
}
return randomNumbers;
}
public void printNum(int[] randomNumbers){
for (int i = 0; i < randomNumbers.length; i++) {
System.out.println("Number " + i + " : " + randomNumbers[i]);
}
}
public void searchArray(int[] randomNumbers,int numSearch) {
int count = 0;
System.out.println("Single # is: " + (RND_GEN.nextInt(10) + 1));
for (int i : randomNumbers) {
if (i == numSearch) {
count++;
}
}
if (count == 0) {
System.out.println("Single #" + numSearch + " was not found!");
} else {
System.out.println("Single # "+ numSearch + " was found " + count + " times");
}
}
public void run() {
Scanner inputReader = new Scanner(System.in);
int x = 1;
do {
int[] numbers = new int[20];
numbers = createNum(numbers);
printNum(numbers);
int numSearch = RND_GEN.nextInt(10) + 1;
searchArray(numbers, numSearch);
System.out.print("Restart Program?, Enter 1 for YES, 2 for NO: ");
x = inputReader.nextInt();
} while (x == 1);
}
public static void main(String[] args) {
Main go = new Main();
go.run();
}
}
I know this question have been asked a lot of times, but I still could not solve the problem. The problem is that I have to store an user input and print out a value.
For example, there are 4 people, person1, person2, person3 and person4. If I vote for person1, the vote number of person1 becomes 1 and the others remain 0. Then if I vote for person2, the vote number of person2 becomes 1 and person1 is also 1.
I can compile the code. But then if I vote for person1, the output becomes 4. and if I then vote for person2, the output of person2 becomes 4 and vote for person1 went back to 0. I am a complete beginner in programming and got stuck at this program for 4 whole days so any help is greatly appreciated. Thank you very much in advance.
import javax.swing.*; // import swing lib for i/o
public class Arrays4
{
public static void main (String[] args)
{
voteperson();
voterepeat();
System.exit(0);
} // end method main
public static int voteperson()
{
// Initialize String Arrays
String[] person = new String[4];
person[0] = "person1";
person[1] = "person2";
person[2] = "person3";
person[3] = "person4";
// Initialize int Arrays
int[] votescount = new int[4];
votescount[0] = 0;
votescount[1] = 0;
votescount[2] = 0;
votescount[3] = 0;
// Declare String Variables
String userinput;
userinput = JOptionPane.showInputDialog
("Please tell us which painting you think is the best."+"\n"+
"Vote 1 "+person[0]+"\n"+
"Vote 2 "+person[1]+"\n"+
"Vote 3 "+person[2]+"\n"+
"Vote 4 "+person[3]);
int answer = Integer.parseInt(userinput);
int i;
for (i=0; i<votescount.length; i++)
{
if (answer == 1)
{
votescount[0] = votescount[0]+1;
}
else if (answer == 2)
{
votescount[1] = votescount[1]+1;
}
else if (answer == 3)
{
votescount[2] = votescount[2]+1;
}
else if (answer == 4)
{
votescount[3] = votescount[3]+1;
}
else
{
}
} // end for loop
JOptionPane.showMessageDialog
(null, "The current votes are" + "\n" +
votescount[0] + " :" + person[0] + "\n" +
votescount[1] + " :" + person[1] + "\n" +
votescount[2] + " :" + person[2] + "\n" +
votescount[3] + " :" + person[3]);
return 0;
}
public static void voterepeat()
{
for (int j=1; j<=4; j++)
{
int repeat;
repeat = voteperson();
System.out.println(j);
}
}
}
When you do this:
for (i=0; i<votescount.length; i++){...
} // end for loop
The loop happens 4 times. This means that this bit is happening 4 times:
if (answer == 1)
{
votescount[0] = votescount[0]+1;
}
which means the vote count goes up by 4!
get rid of your for loop:
for (i=0; i<votescount.length; i++)
and make persons and votescount global and static.
This is the updated code:
import javax.swing.*; // import swing lib for i/o
public class Arrays4
{
static String[] person = new String[4];//these have been made global and static
static int[] votescount = new int[4];
public static void main (String[] args)
{
// Initialize String Arrays
person[0] = "person1";//these have been moved so that it is only called once
person[1] = "person2";
person[2] = "person3";
person[3] = "person4";
// Initialize int Arrays
votescount[0] = 0;
votescount[1] = 0;
votescount[2] = 0;
votescount[3] = 0;
voteperson();
voterepeat();
System.exit(0);
} // end method main
public static int voteperson()
{
// Declare String Variables
String userinput;
userinput = JOptionPane.showInputDialog
("Please tell us which painting you think is the best."+"\n"+
"Vote 1 "+person[0]+"\n"+
"Vote 2 "+person[1]+"\n"+
"Vote 3 "+person[2]+"\n"+
"Vote 4 "+person[3]);
int answer = Integer.parseInt(userinput);
System.out.println(answer);
int i;
if (answer == 1)
{
votescount[0] = votescount[0]+1;
}
else if (answer == 2)
{
votescount[1] = votescount[1]+1;
}
else if (answer == 3)
{
votescount[2] = votescount[2]+1;
}
else if (answer == 4)
{
votescount[3] = votescount[3]+1;
}
else
{
}
JOptionPane.showMessageDialog
(null, "The current votes are" + "\n" +
votescount[0] + " :" + person[0] + "\n" +
votescount[1] + " :" + person[1] + "\n" +
votescount[2] + " :" + person[2] + "\n" +
votescount[3] + " :" + person[3]);
return 0;
}
public static void voterepeat()
{
for (int j=1; j<=4; j++)
{
int repeat;
repeat = voteperson();
System.out.println(j);
}
}
}
First you do,
int[] votescount = new int[4];
then, you do
for (i=0; i<votescount.length; i++)
{
}
So, that loop iterates 4 times.
and inside the loop, you do,
if (answer == 1)
{
votescount[0] = votescount[0]+1;
}
and that's why, your count is up by 4!