I am making course work for my univeristy. And I want to make a test about programming. I am new to java and I need help to make a point counting system after you answer the question correctly. My idea is you get one point for every question you answer correctly.
My code:
package sandis_iesmins_kursadarbs;
import java.util.Scanner;
public class Sandis_iesmins_kursadarbs {
public static void main(String[] args) {
int a;
Scanner intScan = new Scanner(System.in);
String[] jaut = new String[3]; //jaut = is questions in latvian language
jaut[0] = "Is java a programming language";
//jaut[1] = "Kas ir prog1"; these are comments
//jaut[2] = "Kas ir prog2"; these are comments
System.out.println(jaut[0]);
String[] atbildes = {"answers", "1)Yes", "2)No", "3)Maybe", "4)Dont know"}; //answer options
for (String atb: atbildes) {
System.out.println(atb);
}
System.out.println("Insert your answers");
a = intScan.nextInt();
//answer is just "yes" and now I want to add 1 point to my score. How can I do this?
}
}
Does anyboy have an idea for making that kind of counting system. FYI I will have 10 approximately questions.
You can keep a variable which will keep track of the score.
int score = 0;
/*
Ask your question here
*/
if(/*Correct answer*/)
score++; // increment score
Please go through a basic Java tutorial. One is found here
If I understood your question correctly:
Put a integer called e.g. "counter":
int counter = 0;
Each time you want add something do:
counter++;
In the program:
package sandis_iesmins_kursadarbs;
import java.util.Scanner;
public class Sandis_iesmins_kursadarbs {
public static void main(String[] args) {
int counter = 0; //New counter
int a;
Scanner intscan = new Scanner(System.in);
String [] jaut = new String[3]; //jaut = is questions in latvian language
jaut[0] = "Is java a programming language";
//jaut[1] = "Kas ir prog1"; these are comments
//jaut[2] = "Kas ir prog2"; these are comments
System.out.println(jaut[0]);
String[] atbildes = {"answers", "1)Yes", "2)No", "3)Maybe", "4)Dont know"}; //answer options
for(String atb: atbildes){
System.out.println(atb);
}
System.out.println("Insert your answers");
a=intscan.nextInt();
counter++; //Add a new point
}
}
You can make use of counters. Create an intvariable called 'score', and increase it one point if the answer is correct. Here's an example:
package sandis_iesmins_kursadarbs;
import java.util.Scanner;
public class Sandis_iesmins_kursadarbs {
public static void main(String[] args) {
int a;
int score = 0;
Scanner intscan = new Scanner(System.in);
String [] jaut = new String[3]; //jaut = is questions in latvian language
jaut[0] = "Is java a programming language";
//jaut[1] = "Kas ir prog1"; these are comments
//jaut[2] = "Kas ir prog2"; these are comments
System.out.println(jaut[0]);
String[] atbildes = {"answers", "1)Yes", "2)No", "3)Maybe", "4)Dont know"}; //answer options
for(String atb: atbildes){
System.out.println(atb);
}
System.out.println("Insert your answers");
a=intscan.nextInt();
//let's imagine that the correct answer is "Yes".
if(a == 1){
score++;
}
}
Btw, if you want to make a system that punish you for wrong answers, you can do something like this:
package sandis_iesmins_kursadarbs;
import java.util.Scanner;
public class Sandis_iesmins_kursadarbs {
public static void main(String[] args) {
int a;
double score = 0.0;
Scanner intscan = new Scanner(System.in);
String [] jaut = new String[3]; //jaut = is questions in latvian language
jaut[0] = "Is java a programming language";
//jaut[1] = "Kas ir prog1"; these are comments
//jaut[2] = "Kas ir prog2"; these are comments
System.out.println(jaut[0]);
String[] atbildes = {"answers", "1)Yes", "2)No", "3)Maybe", "4)Dont know"}; //answer options
for(String atb: atbildes){
System.out.println(atb);
}
System.out.println("Insert your answers");
a=intscan.nextInt();
//let's imagine that the correct answer is "Yes"
if(a == 1){
score++;
//the system punishes you -0.25 for wrong answer
}else{
score -= 0.25;
}
}
}
Related
I need to make a program that allows me to ask the user for a few numbers and keep doing that until the user enters a 'q' but i cant seem the get the hasNextInt to work as i thought it worked. I am very new to Java and doing the ground course atm.
Here is what i have done so far
public class Matte
{
public static void main (String[] args)
{
int r1 = 0;
int h1 = 0;
int r2 = 0;
int h2 = 0;
int level = 1;
String choice = new String();
Scanner values = new Scanner(System.in);
values.useDelimiter("\\s");
if (level == 1)
{
if(!values.hasNextInt())
r1 = values.nextInt();
else choice = values.nextLine();
if(!values.hasNextInt())
h1 = values.nextInt();
else choice = values.nextLine();
if(!values.hasNextInt())
r2 = values.nextInt();
else choice = values.nextLine();
if(!values.hasNextInt())
h2 = values.nextInt();
else choice = values.nextLine();
}
}
}
I want to save what ever text is typed in the scanner in the "choice" variable
How do i do it??
I didn't really understand your problem, but here is a solution for your problem, adding these integers to an ArrayList and stoping the program when the user types 'q'. Hope it helps you. Cheers!
public class Matte
{
public static void main (String[] args)
{
ArrayList<Integer> numbers = new ArrayList();
int level = 1;
String choice;
Scanner values = new Scanner(System.in);
values.useDelimiter("\\s");
if (level == 1)
{
while(true){
choice = values.nextLine();
if(choice.equals("q"))
break;
else
numbers.add(Integer.parseInt(choice));
}
}
}
}
I am pretty new at Java and I am finding difficulty in solving the problem. Basically the code get a number, and generate a vector in the function generateVector. When I run this code, I am asked to put a number and then the software stay running forever. If possible, could you guys help me without other functions that is kind advanced? I am still learning. Thanks.
import java.util.Scanner;
public class Atividade02 {
static Scanner dados = new Scanner(System.in);
static int n;
//Main
public static void main(String args[]){
System.out.println("Type a number: ");
n = dados.nextInt();
int[] VetorA = generateVector(n);
for(int i=0; i<VetorA.length; i++){
System.out.println("Position: "+ VetorA[i]);
}
}
//Função
public static int[] generateVector(int n){
int[] VetorA = new int [n];
for (int i=0; i<n; i++){
VetorA[i] = dados.nextInt();
}
return VetorA;
}
}
I am asked to put a number and then the software stay running forever.
Did you enter in the n numbers required by generateVector? The program is probably just blocked on input from the user.
Try to modfiy the class as follows:
import java.util.Scanner;
public class Atividade02 {
// Added private access modifiers for properties.
// It's not necessary here, but as a general rule, try to not allow direct access to
// class properties when possible.
// Use accessor methods instead, it's a good habit
private static Scanner dados = new Scanner(System.in);
private static int n = 0;
// Main
public static void main(String args[]){
// Ask for vector size
System.out.print("Define vector size: ");
n = dados.nextInt();
// Make some space
System.out.println();
// Changed the method signature, since n it's declared
// as a class (static) property it is visible in every method of this class
int[] vetorA = generateVector();
// Make some other space
System.out.println();
// Show results
for (int i = 0; i < vetorA.length; i++){
System.out.println("Number "+ vetorA[i] +" has Position: "+ i);
}
}
// The method is intended for internal use
// So you can keep this private too.
private static int[] generateVector(){
int[] vetorA = new int[n];
for (int i = 0; i < n; i++) {
System.out.print("Insert a number into the vector: ");
vetorA[i] = dados.nextInt();
}
return vetorA;
}
}
Also when naming variables stick with the Java naming convention, only classes start with capital letters.
I am trying to build a program that reads in info from a .txt file, which contains 20 individuals. Each person has four fields, the team they belong to, their batting average, and home run totals. I need to add each individual to their team(4 players to each team), total up the team home run totals, and rank the 5 teams in order.
I am able to read the text in properly to a single array, consisting of each individual, but I cannot figure out how to also use this data to create a 2D Array. Using the 2D array I would, put the players on the correct teams, and add their home run totals. I want to sort the home run totals from greatest to smallest for each team, and each individual. I am have done my best to find answers, and to learn on other posts and sites, but I am just stumped with the concept of creating 2D arrays and how to sort them.
Updated explanation:
This is what the info should look like for the single array:
[Team][Name][avg][Home Runs]
Then I JUST want to sort the [Home Runs] column, from greatest to smallest, but don't know how to just access that portion of the array.
The 2D array should look like this:
[Team] [Total Team Home Runs]
Once again, sorting from greatest to smallest.
Example of the .txt file looks like this:
Team: Name: Avg:HR:
MILRyan Braun .31015
STLMatt Adams .28718
PITSterling Marte .26420
CINJoey Votto .30224
CUBAnthony Rizzo .27422
PITAndrew McCutchen .29522
MILAdam Lind .28013
The following class reads in the .txt file and puts it in array.
public class ReadTxt {
static String[] teamm = new String[20];
static String[] name = new String[20];
static int[] avg = new int[20];
static double[] homeRuns = new double[20];
static String teams;
static int i;
public void Players(String[] teamm, String[] name, int[] avg, double[] homeRuns){
String[] team = new String[20];
File txtFile = new File("C:\\Users\\Users Name\\Desktop\\homerun.txt");
try{
Scanner txtScan = new Scanner(txtFile);
while(txtScan.hasNext()){
for(i = 0; i < 20; i++){
teams = txtScan.nextLine();
team[i] = teams;
}
}
}
catch(FileNotFoundException e){
System.out.println("File not found" + txtFile);
}
for (i = 0; i < team.length; i++){
System.out.println(team[i]);
}
}
}
The next class is my attempt at sorting:
public class Sort {
static String[] teamm = new String[20];
static String[] name = new String[20];
static int[] avg = new int[20];
static double[] homeRuns = new double[20];
private int index = 0;
private int US = 0;
static double[] homeRunArray;
public void Players(String[] teamm, String[] name, int[] avg, double[] homeRuns){
homeRunArray[index] = ReadTxt.homeRuns[index];
index++;;
US++;
}
public void selectionSort(){
double temp;
int min;
for(int i = 0; i < US-2; i++){
min = i;
for(int j=i+1; j<= US-1; j++){
if(min !=i){
temp = homeRunArray[i];
homeRunArray[i] = homeRunArray[min];
homeRunArray[min] = temp;
}
}
}
}
public void printArray(double[] homeRuns){
for(int i = 0; i < 20; i++){
System.out.print(homeRunArray[i]);
}
System.out.print("\n");
}
}
I don't get your question, but I think you are kind of stuck in your 2D-Array problem...
I would recommend you to create a class and implement Comparable (or use a Comparator). Something like the code below, or even better, make a real Player class. This is much easier to understand.
public class Sorter {
public static void main(String[] args) {
try {
Scanner scanner = new Scanner(new File("team"));
List<SortableLine> lines = new ArrayList<SortableLine>();
while(scanner.hasNext()) {
lines.add(new SortableLine(scanner.nextLine()));
}
Collections.sort(lines);
for(SortableLine line : lines) {
System.out.println(line.line);
}
} catch(FileNotFoundException e) {
System.err.println("File not found");
}
}
private static class SortableLine implements Comparable<SortableLine> {
private String sortCol;
private String line;
private SortableLine(String line) {
this.line = line;
this.sortCol = line.substring(24, 26);
}
public int compareTo(SortableLine other) {
return sortCol.compareTo(other.sortCol);
}
}
}
My code is throwing an NPE exception at line 27 and 32.
(names[i] = myScanner.nextLine();) +
(content[i] = myScanner.next();)
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class Main {
static Scanner myScanner = new Scanner(System.in);
static int timesNames = 0;
static String[] names;
static String[] content = null;
public static void main(String[] args) {
System.out.println("How many things ? ");
timesNames = myScanner.nextInt();
for(int i = 0; i <= timesNames; i++ ){
int times = i + 1;
if(times <= timesNames ){
System.out.println("Thing Nr." + times);
System.out.println("");
System.out.println("Name of the thing: ");
names[i] = myScanner.nextLine();
System.out.println("");
System.out.println("Desciption : ");
content[i] = myScanner.next();
try {
File newTextFile = new File("P:/" + names[i] + ".txt");
FileWriter myFilewriter = new FileWriter(newTextFile);
myFilewriter.write(content[i]);
myFilewriter.close();
} catch (IOException iox) {
iox.printStackTrace();
}
}
}
}
}
What is causing this? Am I missing something?
I've searched about my problem but I didn't find anything helpful.
This would do it:
static String[] names;
static String[] content = null;
Both of those are initialized to null - one explicitly, one implicitly. You need to set some default size on them.
static String[] names = new String[timesNames];
static String[] content = new String[timesNames];
You haven't initialized names and content yet, so try:
names = new int[namesArraySize];
content = new String[contentArraySize];
where namesArraySize and contentArraySize should your sizes needed for your arrays (in your case it's probably timesNames).
You assigned content explicitly with null and names was set to null implicitly, so both are actually null when you try to access them by names[i] and content[i] (therefore the NPE).
If you don't know how many items there will be stored you should try a java.util.List.
Initialize the array after you know how many "things" there are:
public static void main(String[] args) {
System.out.println("How many things ? ");
timesNames = myScanner.nextInt();
names = new String[timesNames];
content = new String[timesNames];
You have many errors.
1. You didn't initialize the arrays
2.When you do you will probably give them the size of timeNames,which will give you a NPE inside your loop
To fix this you should change the conditions from i<=timeNmaes to i
The both codes below are from different class files.
I'm trying to use the input from spinWheels for pull.
Is that possible?
public int spinWheels(int betAmt)
{
String[] aWheel = new String[5];
Scanner kb = new Scanner(System.in);
betAmt = kb.nextInt();
}
public void pull(int bet)
{
betAmt = bet;
totalcoins = totalcoins - bet;
}
You mean like this?
int x = 0;
spinWheels(x);
pull(x);
It is possible but there are several things that you must do first. Say you have a class A:
class A{
public int spinWheels(int betAmt)
{
String[] aWheel = new String[5];
Scanner kb = new Scanner(System.in);
return kb.nextInt(); //I assume you need this value later
//you must return an int here
}
}
and you have a second class B:
class B{
public void pull()
{
//you need a reference to an Object of type A
A a = new A();
bet = a.spinWheels();
totalcoins = totalcoins - bet;
}
}
Of course the above code is very simplistic, without knowing what you want to achieve it is not possible to say more.
You could just use
public int spinWheels()
{
String[] aWheel = new String[5];
Scanner kb = new Scanner(kb.nextInt());
...
}
I don't understand why you'd want to pass betAmt as an argument if you're going to run it over anyway...