if condition used with JOptionPane showMessageDialog - if-statement

The code below when run generates only the name of the last student with marks<30 I want all the names of the student to be displayed in the same message dialog box. Please help. Thanks and I'm fairly new to coding.
import javax.swing.JOptionPane;
class marks
{
public static void main(String args[])
{
String name=" ";
int marks=0;
for(int x=0; x<3; x++)
{
name=JOptionPane.showInputDialog(null,"Please enter the name");
marks=Integer.parseInt(JOptionPane.showInputDialog(null,"Please enter the marks"));
}
if (marks<30)
{
(JOptionPane.showMessageDialog(null,"the students who got marks below 30 are: "+name));
}
}
}

I think you need to read some basics. Also for that purposes use arrays instead of one variable. I change your code, I think it do what you want :
public class marks {
public static void main(String args[]) {
int count = 3;
String[] name = new String[3];
int[] marks = new int[3];
for (int x = 0; x < count; x++) {
name[x] = JOptionPane.showInputDialog(null, "Please enter the name");
marks[x] = Integer.parseInt(JOptionPane.showInputDialog(null,"Please enter the marks"));
}
String names="";
for(int i = 0;i<count;i++){
if (marks[i] < 30){
names+= name[i]+", ";
}
}
if(names.endsWith(", ")){
names = names.substring(0,names.length()-2);
}
if(!names.isEmpty()){
JOptionPane.showMessageDialog(null,"the students who got marks below 30 are: " + names);
}
}
}

import java.util.ArrayList;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
class marks
{
public static void main(String args[])
{int x=0;
// String name=" ";
// int marks=0;
ArrayList<Integer> marks= new ArrayList<Integer>();
ArrayList<String> name= new ArrayList<String>();
ArrayList<String> array = new ArrayList<String>();
for(x=0; x<3; x++)
{
name.add(JOptionPane.showInputDialog(null,"Please enter the name"));
marks.add(Integer.parseInt(JOptionPane.showInputDialog(null,"Please enter the marks")));
}
// if (marks<30)
for(x=0 ; x<name.size(); x++)
{
if(marks.get(x)<30){
array.add(name.toString());
// JOptionPane.showMessageDialog(null,"the students who got marks below 30 are: "+name.);
break;
}
}
JOptionPane.showMessageDialog(null, new JScrollPane(new JList(array.toArray())));
}
}

Related

Segmentation fault (core dumped) C++ Object Oriented Programming

I'm a student of system engineering, 2nd semester of the ULA (Universidad de los Andes)
So, I'm programming a c++ mini project for university. The project consists of making a draft of a software oriented to buying and selling crypto currencies, however, since yesterday I've been getting a problem with it (a segmentation fault core dumped specifically)... So, as this page had been helpful with my previous programs and this time I didn't find something that could have helped me, I decided to register and ask in case someone is willing to help me.
#include <iostream>
#include <string.h>
#include <stdlib.h>
using namespace std;
class usuario {
private :
string username[10], password[10];
int aux;
public :
usuario();
void setUnamep(string, string, int);
string getUnamep();
void setPass(string);
string getPass();
int DataAcc(string, string);
~usuario();
};
class moneda {
protected :
float cantidad;
public :
moneda(float);
void setCant(float);
void getCant();
~moneda();
};
class bitcoin : public moneda {
private :
float btc[20];
public :
bitcoin (float);
void setBuy(float, float[]);
void getBuy();
void mostrarc(float);
~bitcoin();
};
usuario::usuario () {
}
void usuario::setUnamep(string username_, string password_, int aux_) {
string PreUser[20], aux_2;
aux = aux_;
for (int i= 1; i <= aux; i++) {
username[i] = username_[i];
password[i] = password_[i];
cout<<"\nEnter an username: ";
cin>>username[i];
cout<<"Enter a password: ";
cin>>password[i];
username[0] = "."; //pass 1 leer
for (int v = 0 ; v < i; v++) {
if (username[v] == username[i]) {
cout<<"\nUsername already in use. Choose another"<<endl;
username[i] = "null";
password[i] = "null";
i--;
v = 20000;
}
}
}
}
int usuario::DataAcc(string InUs, string InPass) {
bool ing = false, ret = false;
int u = 0;
do {
if (InUs==username[u] and InPass==password[u]) {
ing = true;
u = 10;
ret = true;
}
else //////
u++;
}
while (ing == false and u<5);
if (u == 5)
cout<<"\nIncorrect user or password. Try again."<<endl;
if (ing == true) {
cout<<"\nAccount data..."<<endl;
}
return ret;
}
usuario::~usuario() {
}
moneda::moneda(float cantidad_) {
cantidad = cantidad_;
}
moneda::~moneda() {
}
bitcoin::bitcoin(float cantidad_) : moneda(cantidad_) {
}
void bitcoin::setBuy(float cantidad_, float btc_[]) {
int aux;
for (int i = 0; i < 20 ; i++) {
btc[i] = btc_[i];
}
cout<<"How many BTC do you wish to buy?: ";
cin>>cantidad;
btc[aux] = btc[aux] + cantidad;
}
bitcoin::~bitcoin() {
}
int main() {
int opc = 0, aux1;
string InUs, InPass;
int aux2 = 0;
bitcoin b1(0);
cout<<"Welcome to BitZuela 2018, down there you have several options for you to choice which one do you want to run. ";
cout<<"\n\n1. Sign Up."<<endl;
cout<<"2. Log in."<<endl;
cout<<"3. Finish program."<<endl;
usuario u1;
while (opc >=0 and opc <=2) {
cout<<"\nPress the button of the option you want to run: ";
cin>>opc;
if (opc==1) {
cout<<"\nHow many accounts do you want to register?: ";
cin>>aux1;
u1.setUnamep("null", "null", aux1);
}
if (opc==2) {
cout<<"\nUsername: ";
cin>>InUs;
cout<<"Password: ";
cin>>InPass;
aux2 = u1.DataAcc(InUs, InPass);
if (aux2 == 1) {
b1.setBuy(0,0); //The problem is when this object is created
}
}
if (opc == 3)
cout<<"\nProgram finished."<<endl;
}
return 0;
}
That's it, I would be very grateful if someone can help me solving this problem. Also, if you have a suggestion about another thing, It'll be a pleasure to read it!
There seems to be some trouble with this method
void bitcoin::setBuy(float cantidad_, float btc_[]) {
int aux;
for (int i = 0; i < 20 ; i++) {
btc[i] = btc_[i];
}
cout<<"How many BTC do you wish to buy?: ";
cin>>cantidad;
btc[aux] = btc[aux] + cantidad;
}
The 'aux' variable is used before it is set resulting in undefined behavior.
Also the call is passing a 0 instead of a float[]. The compiler interprets the 0 as a nullptr, resulting a crash in ::setBuy
if (aux2 == 1) {
b1.setBuy(0,0);
Probably some other issues but fixing these will be a step in the right direction
Your core dumped is in the setBuy function. You ask for an array of float, but when you call it in your code, you pass a "0", but you should pass an array of 20 elements.
The aux variable is set inside the function, but I think you should pass it from the signature of the function.
Also, the cantidad variable that you are using inside that function is not the one in the signature (you should remove it from the signature, or add an _ to cantidad).
I also looked into your setUnamep function, you should use an std::map for your username and password management (You can search for an already existing keys in log(n)).

Unity Iterate over a list to sort by the number value

I have a text file called highscore.txt and I know the format of the data going into the file which works in the following way:
Username:score
I then need to search through the whole file to see where the new score needs to be added such that the file is in order of score from largest to smallest
List<string> tempoaryList = new List<string>();
List<int> valueList = new List<int>();
string lineValues = "";
using (StreamReader sr = new StreamReader(finalPath))
{
while (sr.EndOfStream == false)
{
lineValues = sr.ReadLine();
tempoaryList.Add(lineValues);
int data = Convert.ToInt32(lineValues.Substring(lineValues.LastIndexOf(':') + 1));
valueList.Add(data);
}
}
valueList.Sort();
for(int i =0; i > valueList.Count; i++)
{
if(valueList[i] <= playerScore)
{
tempoaryList.Insert(i - 1, playerScore.ToString());
}
}
using (StreamWriter sw = new StreamWriter(finalPath, false))
{
for (int i = 0; i < tempoaryList.Count; i++)
{
sw.WriteLine(tempoaryList[i]);
Debug.Log(tempoaryList[i]);
}
}
The above just simply doesn't change the text file and leaves it as it was found, any ideas of what I am doing wrong?
You should change your code to this:
ScoreList.cs
using UnityEngine;
using System;
using System.IO;
using System.Collections.Generic;
public class ScoreList : MonoBehaviour {
private void Start() {
GameOver.GameOverEvent += UpdateScoreBoardFile;
}
private void UpdateScoreBoardFile(string playerName, int playerScore) {
string lineValues;
string finalPath = "[ScoreBoard File Location]";
List<string> tempoaryList = new List<string>();
List<int> valueList = new List<int>();
bool isScoreLowest = true;
using (StreamReader sr = new StreamReader(finalPath)) {
while (sr.EndOfStream == false) {
lineValues = sr.ReadLine();
tempoaryList.Add(lineValues);
int data = Convert.ToInt32(lineValues.Substring(lineValues.LastIndexOf(':') + 1));
valueList.Add(data);
}
}
if (tempoaryList != null) {
for (int i = 0; i < valueList.Count; i++) {
if (valueList[i] <= playerScore) {
tempoaryList.Insert(i, playerName + ":" + playerScore.ToString());
isScoreLowest = false;
break;
}
}
}
if (isScoreLowest) {
tempoaryList.Add(playerName + ":" + playerScore.ToString());
}
using (StreamWriter sw = new StreamWriter(finalPath, false)) {
for (int i = 0; i < tempoaryList.Count; i++) {
sw.WriteLine(tempoaryList[i]);
Debug.Log(tempoaryList[i]);
}
}
}
}
GameOver.cs (or wherever you manage the game over condition):
using UnityEngine;
using System;
public class GameOver : MonoBehaviour {
public static event Action<string, int> GameOverEvent;
string playerName;
int finalScore;
private void GameOver() {
//Do other stuff when the game is over
GameOverEvent(playerName, finalScore);
}
}
Explanation of the changes:
isScoreLowest is needed to Add the new lowest score at the end of the list, since the for loop won't add it by itself.
The if (tempoaryList != null) check is done to skip the for loop when the scoreboard is empty.
And you saved yourself from doing a Sort, which is always a good thing. :)

Segmentation fault error with structures

I have no idea where the segmentation error is coming from ... Any ideas?
I am working with structures for an assignment
TestResult testResultFactory(std::string name, double mark)
{
//creating an object of TestResult
TestResult car;
car.name = name;
car.mark = mark;
return car;
}
Student studentFactrory(std::string name)
{
//Creating an object of student
Student house;
house.name = name;
house.testResults = 0;
house.numTestResults = 0;
return house;
}
void addTestResult(Student * student, std::string testName, double testMark)
{
//First we need to create a new array
(student->numTestResults)+=1;
TestResult *newTestArray = new TestResult[(student->numTestResults)];
//Now we loop through the old array and add it to the new one
int index = (student->numTestResults);
for (size_t i = 0; i < (index-1); i++)
{
newTestArray[i] = testResultFactory((student->testResults[i].name),(student->testResults[i].mark));
}
//Now we need to add the new student to the end of the array
newTestArray[index] = testResultFactory(testName, testMark);
(student->testResults) = newTestArray;
}
string studentBest(Student const * student)
{
//create variables as temps
string highestName;
double highestMark;
int index = (student->numTestResults);
//Setting the two variables to the first value
highestName = (student->testResults[0].name);
highestMark = (student->testResults[0].mark);
//Using a while loop to compare and get the best
for (size_t i = 0; i < index; i++)
{
if((student->testResults[i].mark)> highestMark)
{
highestMark = (student->testResults[i].mark);
highestName = (student->testResults[i].name);
}
}
//returning the string they want
string send = (highestName)+ " "+ doubleToString(highestMark)+ "%";
return send;
}
double studentAverage(Student const * student)
{
//Variables used as temps
double average = 0;
double counter = 0.0;
double running = 0;
int index = (student->numTestResults);
//Now we need to loop through each one and add to running and counter
for (size_t i = 0; i < index; i++)
{
counter++;
running += (student->testResults[i].mark);
}
//calculating the average;
average = (running)/counter;
return average;
}
void destroyStudent(Student * student)
{
delete [] (student->testResults);
(student->testResults)=0;
}
Subject subjectFactory(std::string name)
{
//Creating an object to use in subject factory
Subject lamp;
lamp.name = name;
lamp.numStudents = 0;
lamp.studentsAllocated = 0;
lamp.students = 0;
return lamp;
}
MY guess is that the error occurs because of an out of bounds array or an pointer not worked with correctly .
int getStudentIndex(Subject const * subject, std::string studentName)
{
int index;
int count = (subject->numStudents);
//loop to find the names and set index
for (size_t i = 0; i < count; i++)
{
if(studentName == ((subject->students[i].name)))
{
index = i;
}
else index = -1;
}
return index;
}
void addStudent(Subject * subject, std::string studentName)
{
//Variables as temps
Student *pointer =0;
int index = getStudentIndex(subject,studentName);
if(index != -1)
{
//Now we need to see if they are large enough
if((subject->studentsAllocated)==0)
{
//Set the allocated to 2
(subject->studentsAllocated) = 2;
pointer = new Student[2];
//Figure this out later
pointer[1] = studentFactrory(studentName);
(subject->students) = pointer;
}
else
{
//increase SA with 1.5
(subject->studentsAllocated) = (subject->studentsAllocated) * 1.5;
pointer = new Student[(subject->studentsAllocated)+1];
int count = (subject->studentsAllocated);
//Now we need to put all the other students in
for (size_t i = 0; i < count-1; i++)
{
pointer[i] = (subject->students[i]);
}
pointer[(subject->studentsAllocated)+1] = studentFactrory(studentName);
(subject->studentsAllocated) += 1 ;
}
//Once done just seet one equal to
(subject->students) = pointer;
}
else return;
}
void removeStudent(Subject * subject, std::string studentName)
{
//First get temps
int index = getStudentIndex(subject ,studentName);
int number = (subject->studentsAllocated);
int i = index;
//delete student
if(index == -1) return;
destroyStudent(&(subject->students)[index]);
//loop to shift the things
while (i<(number -1))
{
(subject->students)[i] = (subject-> students[i+1]);
}
//Removing the last one
(subject->numStudents) -= 1;
}
bool addTestResult(Subject * subject, std::string studentName, std::string testName, double testMark)
{
int index = getStudentIndex(subject ,studentName);
if(index != -1)
{
addTestResult(&(subject->students [index]),testName,testMark);
return true;
}
else
return false;
}
void printSubjectSummary(Subject const * subject)
{
cout<<(subject->name)<< ": with "<<(subject->numStudents)<<" students"<<endl;
//Variables to use in the loop
size_t indexLoop = subject->numStudents;
int i=0;
while (i< indexLoop)
{
cout<<(subject->students[i].name)<<" Average: "<<studentAverage(&(subject->students[i]))<<", Best: "<<studentBest(&(subject->students[i]))<<endl;
}
}
void destroySubject(Subject * subject)
{
//Variables
size_t indexLoop = subject->numStudents;
for (size_t i = 0; i < indexLoop; i++)
{
destroyStudent(&(subject->students[i]));
}
delete [] subject->students;
subject->students =0;
}
I can not seem to find where the segmentation error is coming from. Even restarted the whole assignment from scratch and still seem to get errors.
Can someone please help or indicate where the fault could be coming from.
Over here we have the structs.h file that is included in my code above
#ifndef STRUCTS_H
#define STRUCTS_H
struct TestResult{
double mark;//the test mark as a percentage
std::string name;//the test name
};
struct Student{
std::string name;
TestResult * testResults;//an arry of TestResults
size_t numTestResults;//the number of results for this student (also the size of the array)
};
struct Subject{
std::string name;
Student * students;//an array of Students
size_t numStudents;//the number of students added to the subject
size_t studentsAllocated;//the size of the Student arry(must never be smaller that numStudents)
};
#endif
There are so many logical errors in there that the root cause (or causes; there are quite a few candidates) could be pretty much anywhere.
getStudentIndex returns -1 unless the student is the last one in the array, and an indeterminate value for the first one you add, so adding the first student to a subject is undefined.
addStudent only adds a student if they're already taking the subject.
It also (for some inexplicable reason) allocates an array of two Students, leaving the first element uninitialised.
Using this first element is, of course, undefined.
In the other branch, it first claims that the number of allocated students is * 1.5, but then only allocates + 1.
This will undoubtedly lead to problems.
There is a recursion in addTestResult that will never terminate.
There are most likely other problems as well – this was just a quick glance.
Start with fixing these.
And do learn about constructors and destructors so you can get rid of those "factory" and "destroy" functions.

std::bad_alloc at memory location 0x002b123c

I am making a small program. First I made a Header File:
private:
string UserName, Password;
public:
void setUN(string);
void setP(string);
string getUN();
Then in my cpp file:
void UserInfo::setUN(string un){
UserName = un;
}
string UserInfo::getUN(){
return UserName;
}
After that in my main I make a object:
UserInfo addUser[100];
to add users
cout<<"Enter Username : ";
getline(cin,tUN);
addUser[0].setUN(tUN);
After that in my other function void LoginScreen()
I made the same object:
UserInfo addUser[100];
string EUN, EP;
system("cls");
cout<<"Enter Username : ";
cin>>EUN;
cout<<endl;
cout<<"Enter Password : ";
//cin>>EP;
for( int a = 0; a <= 100; a++){
if (EUN == addUser[a].getUN()){
system("cls");
cout<<"OMG HELP MEEE ";
break;
}
}
It works fine when till get to this for loop and gives this error:
std::bad_alloc at memory location 0x002b123c
Can you tell me what the error means and how can I get rid of this.
UserInfo addUser[100]; has elements indexed from 0 - 99.
So fix:-
for( int a = 0; a <= 100; a++){
^^This should be a < 100
}

Call to function is ambiguous in C++. Candidate functions are the Prototype and the function itself

I am working through Stanford CS106B C++ assignments and I have a 'semantic issue' with an assignment.
It seems as if the compiler cannot deduce whether the call is to a function or to the prototype of the function. I don't understand why a call would ever be made to the prototype. How can I make it so that the call is made to the function rather than the prototype? The error message I get it "Call to 'humansTurn' is ambiguous".
The error messages relate to the calls of the humansTurn(Lexicon,Lexicon) function, within the humansTurn(Lexicon,Lexicon) function, at the bottom of the page. The prototype for this function is above the main function.
Any help would be greatly appreciated.
Kind regards,
Mehul
/*
* File: Boggle.cpp
* ----------------
*/
#include <iostream>
#include "gboggle.h"
#include "graphics.h"
#include "grid.h"
#include "vector.h"
#include "lexicon.h"
#include "random.h"
#include "simpio.h"
using namespace std;
/* Constants */
const int BOGGLE_WINDOW_WIDTH = 650;
const int BOGGLE_WINDOW_HEIGHT = 350;
const string STANDARD_CUBES[16] = {
"AAEEGN", "ABBJOO", "ACHOPS", "AFFKPS",
"AOOTTW", "CIMOTU", "DEILRX", "DELRVY",
"DISTTY", "EEGHNW", "EEINSU", "EHRTVW",
"EIOSST", "ELRTTY", "HIMNQU", "HLNNRZ"
};
const string BIG_BOGGLE_CUBES[25] = {
"AAAFRS", "AAEEEE", "AAFIRS", "ADENNN", "AEEEEM",
"AEEGMU", "AEGMNN", "AFIRSY", "BJKQXZ", "CCNSTW",
"CEIILT", "CEILPT", "CEIPST", "DDLNOR", "DDHNOT",
"DHHLOR", "DHLNOR", "EIIITT", "EMOTTT", "ENSSSU",
"FIPRSY", "GORRVW", "HIPRRY", "NOOTUW", "OOOTTU"
};
/* Function prototypes */
void welcome();
void giveInstructions();
// Create random board
static Grid <char> randomBoard();
// Create custom board
static Grid<char> customBoard();
static void drawAndFillBoard(Grid<char>);
static void humansTurn(Lexicon,Lexicon);
int main() {
initGraphics(BOGGLE_WINDOW_WIDTH, BOGGLE_WINDOW_HEIGHT);
welcome();
giveInstructions();
string custom = getLine("Type y to create custom board:" );
Grid<char> gridData;
if (custom=="y"){
gridData = customBoard();
} else {
gridData = randomBoard();
}
drawAndFillBoard(gridData);
Lexicon english("EnglishWords.dat");
// Lexicon holds words previously encountered
Lexicon previousWords;
humansTurn(english, previousWords);
return 0;
}
/*
* Function: welcome
* Usage: welcome();
* -----------------
* Print out a cheery welcome message.
*/
void welcome() {
cout << "Welcome! You're about to play an intense game " << endl;
}
/*
* Function: giveInstructions
* Usage: giveInstructions();
* --------------------------
* Print out the instructions for the user.
*/
void giveInstructions() {
cout << endl;
cout << "The boggle board is a grid onto which I ";
cout << "or triple your paltry score." << endl << endl;
cout << "Hit return when you're ready...";
getLine();
}
static Grid<char> randomBoard(){
Vector<string> standardCubes;
for(int i = 0; i<16;i++){
standardCubes.add(STANDARD_CUBES[i]);
}
// Shuffle cubes
for (int i = 0; i < standardCubes.size(); i++) {
int r = randomInteger(i, standardCubes.size()-1);
if (i!=r){
string stringToMove1 = standardCubes.get(i);
string stringToMove2 = standardCubes.get(r);
standardCubes.set(r, stringToMove1);
standardCubes.set(i, stringToMove2);
}
}
// Update grid with random side of cube
Grid<char> gridData(4, 4);
int counter = 0;
for (int columnNo = 0; columnNo <4; columnNo++){
for (int rowNo = 0; rowNo<4; rowNo++) {
string s = standardCubes.get(counter);
int r = randomInteger(0, 5);
gridData[columnNo][rowNo] = s[r];
counter++;
}
}
return gridData;
}
static Grid<char> customBoard(){
Grid<char> gridData(4,4);
string s = getLine("Please enter 16 characters to make up the custom board. Characters will fill the board left to right, top to bottom: ");
for (int i = 0; i < s.length(); i++) {
s[i] = toupper(s[i]);
}
if (s.length()<16){
cout << "String has to be 16 characters long, try again" << endl;
customBoard();
}
int i =0;
for (int columnNo = 0; columnNo <4; columnNo++){
for (int rowNo = 0; rowNo<4; rowNo++) {
gridData[columnNo][rowNo] = s[i];
i++;
}
}
return gridData;
}
static void drawAndFillBoard(Grid<char> gridData){
drawBoard(4, 4);
for (int columnNo = 0; columnNo <4; columnNo++){
for (int rowNo = 0; rowNo<4; rowNo++) {
labelCube(rowNo, columnNo, gridData[rowNo][columnNo]);
}
}
}
static void humansTurn(Lexicon englishWords, Lexicon &previousWords){
/*
Human’s turn (except for finding words on the board). Write the loop that allows the user to enter words. Reject words that have already been entered or that don’t meet the minimum word length or that aren’t in the lexicon. Use the gboggle functions to add words to the graphical display and keep score.
*/
string humanGuess = getLine("Please enter your guess: ");
for (int i = 0; i < humanGuess.length(); i++) {
humanGuess[i] = tolower(humanGuess[i]);
}
if (humanGuess.length()<4){
cout << "Min guess length is four characters" << endl;
humansTurn(englishWords, previousWords);
}
if (!englishWords.contains(humanGuess)) {
cout << "That word is not English, please try another word" << endl;
humansTurn(englishWords, previousWords);
}
if (previousWords.contains(humanGuess)){
cout << "That word has already been guessed, please try another word" << endl;
humansTurn(englishWords, previousWords);
}
// check if word can be made using data on board
}
Your function humansTurn definition has different signature with declaration
function declaration:
static void humansTurn(Lexicon,Lexicon);
Function definition:
static void humansTurn(Lexicon englishWords, Lexicon &previousWords)
^^
//Here