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));
}
}
}
}
Related
I am new to Java and this is a very basic question.
However I struggle to find a solution, so hopefully someone could give me some pointers.
I am trying to fill values into an array "addedPlayer".
However, every time I run the AddPlayer() method it is initialiezed to zero again.
How can I structure this in a better way?
public class DemoApplication implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
public void AddPlayer() {
int[] addedPlayer;
addedPlayer = new int[500];
System.out.println(" *** Add new player *** ");
System.out.println("Name:");
String name = System.console().readLine();
System.out.println("Age:");
int age = Integer.parseInt(System.console().readLine());
System.out.println("JNUM:");
int jnum = Integer.parseInt(System.console().readLine());
player p = new player();
p.SetAge(age);
p.SetName(name);
p.SetJnum(jnum);
System.out.println(addedPlayer[0]);
for (int j = 0; j < addedPlayer.length; j++) {
if (addedPlayer[j] != 0) {
} else {
addedPlayer[j] = p.GetAge();
System.out.println(addedPlayer[j]);
System.out.println(j);
break;
}
}
}
public void EditPlayer() {
//empty
}
public void ListPlayer() {
//empty
}
#Override
public void run(String... args) throws Exception {
while (true) {
System.out.println(" *** MENY *** ");
System.out.println(" 1. Add player ");
System.out.println(" 2. Edit player ");//ÖKurs
System.out.println(" 3. List player ");
System.out.println(" 100. Exit ");
System.out.println("Ange val");
int sel = Integer.parseInt(System.console().readLine());
if (sel == 100) break;
if (sel == 1) AddPlayer();
if (sel == 2) EditPlayer();
if (sel == 3) AddPlayer();
}
}
}
Each time you run AddPlayer(), it creates a new player from scratch. If you want to keep your modifications to a bare minimum, you must put it outside of the method and make it a property for your class like List<int[]> addedPlayers = new ArrayList<int[]>(); and you can add this line AddPlayer to add it in a list addedPlayers.add(addedPlayer). Otherwise, if you want a more cleaner code, you should add more classes than only one main class. To improve your code, you can see #g.momo's answer.
int[] addedPlayer; addedPlayer = new int[500];
It gets overridden because you are creating an new local var addedPlayer, and then setting all values to 0 (addedPlayer = new int[500];) I'm assuming you would want addedPlayer to be global, so don't define it locally and set it to 0.
Also, should addedPlayer be a player[] or just a player rather than an int[]? Plus, you didn't close the function in the code you gave us, so is there more missing or did you just not close it?
Your code and your expectations are completely differents.
Read this and tell us if you understand. It is the way I would have written if I were you . But it is NOT TESTED:
public class AddPlayer { // you create a class
player[] addedPlayer; // array of players
int index;
public AddPlayer() { // constructor of the class
addedPlayer = new player[500]; // max 500 players
index = 0;
}
public void addPlayer(player p) {
if(index < 500) {
addedPlayer[index] = p; // add at index,
index = index + 1; // then increment index for the next added player
}
}
public static void main(String... args) {
AddPlayer addPlayers = new AddPlayer();
int i = 0;
while(i < 5) { // will run 5 times, so only 5 players will be added. Change to stop when you will need
// here your read console inputs
System.out.println(" *** Add new player *** "+ (i+1));
System.out.println("Name:");
String name = System.console().readLine();
System.out.println("Age:");
int age = Integer.parseInt(System.console().readLine());
System.out.println("JNUM:");
int jnum = Integer.parseInt(System.console().readLine());
// initialize the player
player p = new player();
p.SetAge(age);
p.SetName(name);
p.SetJnum(jnum);
addPlayers.addPlayer(p); // add in the array
i++;
}
}
}
I am trying to make the compiler pass the array from one of the classes to the main method. I don't know why it does not work, the code looks like this:
public class Main {
public static void main(String[] args) {
int[] board2;
int userInput;
playBoard = board.createBoard();
userInput = takeAGuess.input();
}
}
import java.util.Scanner;
public class takeAGuess {
int input()
{
int input=0;
Scanner reader = new Scanner(System.in);
System.out.println("Please enter your guess now");
input = reader.nextInt();
System.out.println("Guess entered successfully");
return input;
}
}
public class board {
int[] createBoard()
{
int[] board = new int[7];
int randomNum =(int) (Math.random()*5);
for (int i=0; i<2; i++)
{
board[randomNum+i] = 1;
}
System.out.println("Board created");
return board;
}
}
I already tried these lines:
new[] board = board.Createboard();
int board[] = board.Createboard();
{
int board = new board();
board = createBoard();
}
I am aware of that I could easily put everything in one class and even one method but i'm to practice on using classes therefore I create lots of them.
int[] board2;
int userInput;
playBoard = board.createBoard();
userInput = takeAGuess.input();
where is playboard defined?
And... so much classes! Use methods in the Main class instead, it'll make your job lighter.
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;
}
}
}
So I'm in the middle of working on a class called planner [no main in it as it's a separate class], but I'm having an issue with declaring an array with eclipse. You will need to enter it in eclipse to see what it is because I have no idea what it means by 'Syntax error on token ";", , expected'.
Here is the code:
import java.util.Scanner;
public class Planner {
private int maxEvents = 1000;
private int numEvents = 0;
private int choice;
int[] anArray;
anArray = new int [1000];
public void Planner() {
Scanner scan = new Scanner (System.in);
System.out.print("Press 1 to add an event. 2 to display events for the day. 3 to display events for the week. 4 to quit: ");
choice = scan.nextInt();
if (choice == 1){addEvent();}
if (choice == 2){displayOneDate();}
if (choice == 3){displayOneWeek();}
if (choice == 4){System.out.println("Have a good day.");}
else {Planner();}
}
public void addEvent() {
Event newEvent = new Event();
if (numEvents == maxEvents){System.out.println("Error: No more room.");}
else {
for (int i=0; anArray.length > i; i++) {
numEvents++;
newEvent.getEventFromUser();
}
}
}
public void displayOneDate() {
System.out.println("Event one: " + anArray[0]);
}
public void displayOneWeek() {
}
}
When you declare
int[] anArray;
anArray = new int [1000];
it should be
int[] anArray = new int [1000];
You cannot have executable code in class directly. You should have it either in method or constructor.
Otherwise if you want initialize the array you have to write like this int[] anArray = new int [1000];
I'm having a problem with my code. We're working on binary search, and I can't seem to get the right output whenever I input a number. We were given a list of 60 numbers already in order(external file), and whatever number we input, the program should search and return the position. If the number is not on the list, it should return a -1.
My code:
import java.io.*;
import java.util.*;
public class Prog489
{
public static void main(String[] args) throws IOException
{
Scanner scan = new Scanner(System.in);
System.out.print("Enter a number to search for: ");
int search = scan.nextInt();
Scanner kbReader = new Scanner(new File("C:\\Users\\Guest\\Documents\\java programs\\Prog489\\Prog489.in"));
int[] num = new int[60];
int i = 0;
System.out.println(binarySearch(num, search));
while(kbReader.hasNextInt())
{
num[i++] = kbReader.nextInt();
}
}
private static int binarySearch(int[] num, int search)
{
int lb = 0;
int ub = num.length - 1;
while(lb<=ub)
{
int mid = (lb+ub)/2;
if(num[mid] == search)
{
return mid;
}
else if(search>num[mid])
{
lb=mid+1;
}
else
{
ub = mid-1;
}
}
return -1;
}
}
So the part with the return should only return -1 if the number is not on the list. But whenever I do enter a number on the list (such as 60), it still returns a -1. Everything compiles, so I'm not really sure what I'm missing, or if it's something really obvious that I'm forgetting. Could someone please help me identify the error? Any guidance/feedback is greatly appreciated.
Move the call to print the output of binarySearch to after you populate the array:
int[] num = new int[60];
int i = 0;
while(kbReader.hasNextInt())
{
num[i++] = kbReader.nextInt();
}
System.out.println(binarySearch(num, search));