(Writing in java)I have two inputs(History, Geography) taken from the console. I can enter the values of History/Geography as any integer and I can do it any number of times I want. When I decide to stop taking console input I need to find out how many History and how many Geography.
I have successfully taken the console inputs.
However, I don't know how my code should store (remember) what all I entered for History and Geography and then spit it out.
Help Please. IN the example below I cannot figure out how to achieve the second part annotated with
console>
Select 1.Subject 2.Subject Count //console message
1 //console input
Which Subject? 1.History 2. Geography //console message
1 //console input
How many History ? //console message
5 //console input
[Another round]
console>
Select 1.Subject 2.Subject Count //console message
2 //console input
5 History // console message
The question you have asked isnt very clear, but from what I understood, this might be of help to you
You could also use a SwitchCase statement here!
import java.io.*;
public class Subject{
public static void main(String[] args)throws IOException{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(isr);
boolean flag = true;
int hist = 0, geog = 0, val = 0;
while(flag){
System.out.println("Enter the number for subject\n1.History\n2.Geography\n -1.Exit");
val = Integer.parseInt(in.readLine());
if(val == 1){
hist ++;
}
else if(val == 2){
geog ++;
}
else if(val == -1){
System.out.print("Total History: ", hist);
System.out.print("Total Geography: ", geog);
flag = false;
continue;
}
else{
System.out.println("invalid option");
continue;
}
}
}
}
/*
int hist[] = new int[100];
int geog[] = new int[100];
int i = 0;
int j = 0
while(true){
//if history
//then do this
hist[i] = i + 1;
i++;
//if geography
//do this
geog[j] = i + 1;
j++
//if user wants to exit
for(int m = 0; m<=i; m++){
//calculate sum like this: Sum += hist[m];
//print sum
}
for(int n = 0; m<=j; n++){
//calculate sum like this: Sum2 += geog[n];
//print Sum2
}
}
*/
Related
I'm trying to write a java code with(bingo game),(bullseye game)
the rules are simple:
computer picks 4 numbers
user input 4 numbers
must check the user input is between 1 to 10
If the user input exists in the computer randomized numbers it will be 1 bulls
If a number exist in the same location of the computer randomized number it will show 1 "eye"
Max limit is 20 tries until the user is considered "failed"; I need to print each round how many bulls were and how many eye were by the user input;
Example:
if the pc randomizing 1 4 6 7
and the user type 3 4 1 7
the output will be 3 bulls and 2 eyes.
my code prints 0 and 0 at the end.
Thanks for the help!
Here is my code:
import java.util.Random;
import java.util.Scanner;
public class ArraysEx1 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Random r = new Random();
int[] pcGuess = new int[4];
int[] playerGuess = new int[4];
int countGuess = 0, bulls = 0, eye = 0;
final int maxGuess = 20;
System.out.println("Please press enter to begin");
in.nextLine();
boolean areNumbersCorrect = true; // a boolean value to define if the user input are correct (values between 1 to 10)
for (; countGuess < maxGuess; countGuess++) {
System.out.println("Please enter 4 numbers between 1-10");
for (int i = 0; i < playerGuess.length; i++) {
playerGuess[i] = in.nextInt();
pcGuess[i] = r.nextInt(10)+1;
if (playerGuess[i] < 0 || playerGuess[i] > 10) { // an if statement to check if the user input are correct
areNumbersCorrect = false;
do { // do while loop if the boolean is not true. (force the user to enter correct values)
System.out.println("Please try again");
for (int j = 0; j < playerGuess.length; j++) {
playerGuess[j] = in.nextInt();
if (playerGuess[j] > 0 && playerGuess[j] < 10) {
areNumbersCorrect = true;
continue;
}
}
} while (!areNumbersCorrect); // end of do while loop
}
for (int j=pcGuess.length; j>0; j--) { // for loop to check each number from the user and computer.
if (playerGuess[i] == pcGuess[i]) {
eye++; // if the user number exist in the same location evaluate eye++
if (playerGuess[i]%pcGuess[j]== 0) {
bulls++; // if the user number exist in the randomized number but not in the same location evaluate bulls++
}
}
}
System.out.println(
eye+" Hits!(same pc number and location)"+" And: "+bulls+" Numbers exist");
} if(eye==4&&bulls==4) {
break;
}
}
System.out.println("It took you: "+countGuess+" Times to guess the numbers");
}
}
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
public class ArraysEx1 {
public static void main(String[] args) {
ArrayList<Integer> randNumbers = new ArrayList<>();
Random random = new Random();
String input;
int number;
Scanner sc = new Scanner(System.in);
do {
System.out.println("Please press enter to begin");
input = sc.nextLine();
}while (!input.equals(""));//loop while user doesn't press ENTER
for (int i = 0; i < 4; i++){
randNumbers.add(random.nextInt(10) + 1);//loop to fill the randNumbers arraylist with random numbers
}
/*
randNumbers.add(3);
randNumbers.add(2);
randNumbers.add(9);
randNumbers.add(9);
*/
System.out.println("My random numbers: " + randNumbers.toString());
int counter = 0;
int bulls = 0;
int eyes = 0;
do {
System.out.println("Please enter 4 numbers between 1-10");
number = sc.nextInt();
if (number > 0 && number <= 10){
//System.out.println("index of rand: " + randNumbers.indexOf(number));
//System.out.println("count: " + counter);
if (randNumbers.indexOf(number) == counter){
eyes++;
System.out.println("eyes++");
}else if (randNumbers.contains(number)){
bulls++;
System.out.println("bulls++");
}
counter++;
System.out.println("Number " + counter + " introduced. " + (4 - counter) + " more to go.");
}else {
System.out.println("Wrong number.");
}
}while (counter < 4);//loop for user to introduce valid numbers
System.out.println("You scored " + bulls + " bulls and " + eyes + " eyes.");
}
}
Try this piece of code. Note that I used ArrayList rather than an array, as it offers methods such as .contains() and .indexof().
WARNING: Code will fail if the randNumbers arraylist contains two numbers that are equals, such as the 3-2-9-9 array that is commented when you input 9-9-9-9 as your number guesses. This is because .indexof() method:
Returns the index of the first occurrence of the specified element
in this list, or -1 if this list does not contain the element.
Meaning the code fails to account the last 9 as it will compare the count index (3) to the first occurrence of 9 in the randNumbers, which is 2, making it false and not increasing eyes count.
Since I'm short on time, and this is an assigment you have and just copying it won't teach you much, I'll leave it to you to solve this specific case (I already told you what's wrong, won't be difficult to solve).
I have tried to code in which the code stop processing input after reading in the number 42. All numbers at input are integers.In this code the user is asked to give the number of input he wants to give.But I am not getting how to take input without asking the user how many number he wants to enter.
import java.util.Scanner;
public class antarahac {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int pattern[] = new int[1];
pattern[0] = 42;
int max, ls, lp = 1;
System.out.println("enter the no. of values you want to enter");
ls = sc.nextInt();
int input[] = new int[ls];
for (int i = 0; i < ls; i++) {
input[i] = sc.nextInt();
}
max = ls - lp - 1;
boolean flag;
for (int i = 0; i < max; i++) {
flag = true;
for (int j = 0; j < lp && flag == true; j++) {
if (pattern[j] != input[j + i]) {
flag = false;
System.out.println("" + input[i]);
}
}
if (flag == true) {
break;
}
}
}
}
You can simply use a loop until the value you want is acquired. You mention to stop when the user input 42 :
int tmp;
while((tmp = sc.nextInt()) != 42){
// do something
}
This will read input until a 42 is inputted.
Scanner sc = new Scanner(System.in);
int tmp;
while((tmp = sc.nextInt()) != 42){
System.out.println(tmp);
}
sc.close();
Input :
1, 2, 3, 5, 48, 42
Output:
1
2
3
5
48
More information
Now, if you want to store those, if you use an array, you will need to create an array with enough spaces (risky) like : new int[1000]; or you can use a List to use a dynamic sized collection. If you don't know it, simply know that to create a List you just need to :
List<Integer> input = new ArrayList<>(); //int[] input = new int[####];
Then to add a value at the end you can :
input.add(i); //input[index] = i;
And to read the value (get) :
input.get(index); // input[index]
Then, I notice you use ls, previous the size of the array, you can know how many values were added in the list using the method size() :
ls = input.size();
I'm having some problems splitting a string that is read in from an input file, making sure it's valid, then saving it to a variable.
Let's say this is the first string:
12345 5 59.28
I would want to split the 12345, 5, and 59.28.
After verifying that they are the correct format ( 00000-99999, 0-5, 000.00 0 100.00 ), I would then assign it to a variable.
My main two obstacles are that I CANNOT use arrays in this program, so I'm not sure how to split the string. I have tried just pulling each section as an int, but that doesn't seem to work.
My other problem is that I'm not sure how to validate it. Would I be using something like this:
//Assuming I have a scanner set up and a class, method declared
//Declare variables
int numbers;
int studentID;
while(fileInput.hasNext())
{
numbers = fileInput.nextInt(); //Not sure how to pull a part of the string
}
//Used to validate that it is within the range
if(numbers < 00000 || numbers > 99999)
{
studentID = numbers;
}
I am a beginner at Java so please do excuse my confusion.
If you know what the structure of the file is, for example if it's always formatted like this:
int int double
Then you can simply callnextInt(), nextInt(), and then nextDouble() to parse the data from it that way.
Maybe something like this
do
{
num1 = scanner.nextInt();
num2 = scanner.nextInt();
num3 = scanner.nextDouble();
} while (scanner.hasNextInt());
And do that in order to collect all of your data, but you'll likely need lots of variables if you have any substantial amount of data you're reading in
Or if there's bad data sometimes with it's correct data immediately after it you could so something like this to skip over the bad one, even though it's not very pretty
do
{
if (scanner.hasNextInt())
{
num1 = scanner.nextInt();
}
else
{
scanner.next() // move past whatever bad data there was
num1 = scanner.nextInt();
}
if (scanner.hasNextInt())
{
num2 = scanner.nextInt();
}
else
{
scanner.next() // move past whatever bad data there was
num2 = scanner.nextInt();
}
if (scanner.hasNextDouble())
{
num3 = scanner.nextDouble();
}
else
{
scanner.next() // move past whatever bad data there was
num3 = scanner.nextDouble();
}
} while (scanner.hasNext());
I think your teachers give this assignment to practice your if-else condition or switch statement and for loop(fundamental) skills.
Here what I did, this may be not completely match with your assignment question but using this you can get complete idea and think of a way to reduce this. Hey! because of we are not here to do your assignment. you have to tackle with your problem and get familiar with those.
Try to understand these, do changes look what happen:
public static void main(String[] args) {
Scanner fileInput = new Scanner(System.in);
//Declare variables
String numbers = "";
String firstNum = "";
String secondNum = "";
String thirdNum = "";
int studentID = 0;
int secondDigit = 0;
double thirdDigit = 0;
System.out.print("Input: ");
numbers = fileInput.nextLine();
int firstIndex = 0;
int secondIndex = 0;
int thirdIndex = 0;
firstIndex = numbers.indexOf(" ");
if(firstIndex <= 4){
System.out.println("Number should be 5");
}else{
firstNum = numbers.substring(0, firstIndex);
numbers = numbers.substring(firstIndex+1);
studentID = Integer.parseInt(firstNum);
if(studentID > 0 && studentID < 99999){
System.out.println("First num: " +firstNum);
}else{
System.out.println("first digits not in a range ");
}
}
secondIndex = numbers.indexOf(" ");
if(secondIndex == 0){
System.out.println("no number");
}else{
secondNum = numbers.substring(0, secondIndex);
numbers = numbers.substring(secondIndex+1);
secondDigit = Integer.parseInt(secondNum);
if(secondDigit >= 0 && secondDigit <= 5){
System.out.println("Second num: " +secondNum);
}else{
System.out.println("second digit not in a range ");
}
}
thirdIndex = numbers.length();
if(thirdIndex < 3){
System.out.println("3 numbers should be there");
}else{
thirdNum = numbers.substring(0, thirdIndex);
thirdDigit = Double.parseDouble(thirdNum);
if(thirdDigit >= 0 && thirdDigit <= 100){
System.out.println("third num: " +thirdNum);
}else{
System.out.println("third digit not in a range ");
}
}
}
I'm not going to explain this also. You have to try, if you have any problem after tackling with this code. ask any question in comment.
Hope this will help!
Try this. Invalid formats will throw an exception during the next method call.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner in = new Scanner("12345 5 59.28");
in.useDelimiter(" "); // reads per space
String next = in.next("\\d{5}"); // reads next 5 digits
int numbers = Integer.valueOf(next);
System.out.println(numbers);
next = in.next("\\d{1}"); // reads next 1 digit
int studentId = Integer.valueOf(next);
System.out.println(studentId);
next = in.next("\\d{2}\\.\\d{2}"); // reads next a decimal with two digits before and after point
float floatingNumbers = Float.valueOf(next);
System.out.println(floatingNumbers);
}
}
<script src="//repl.it/embed/IWzC/0.js"></script>
I am trying to finish an assignment. I have to write a program in Java that generates random numbers in an array size100 and then asks the user for a number between 1 and 100. If the number is in the array it displays that the number was found at what location. If not it kicks back that no number was found. So far I can only get it to kick back that the number was not found. It prints it back out 4 different times.
package lab1;
import java.util.Random;
import java.util.Scanner;
public class RandomArray {
public static void main(String[] args) {
int [] randomArray = new int [100];
Random randomGenerator = new Random();
for (int i = 0; i< randomArray.length; i++){
randomArray[i] = randomGenerator.nextInt(100);
}
Scanner input = new Scanner (System.in);
int searchNumber;
System.out.println("Please enter a number to search for between 1 and 100: ");
searchNumber= input.nextInt();
boolean found = false;
for (int i = 0; i < randomArray.length; i++){
if (searchNumber == randomArray[i]){
found = true;
break;
}
if (found){
System.out.println("We have found your" + "number at index " + i);
}else{
System.out.println("We did not find your number");
}
}
}
}
Your if statement inside for loop. So each time searchNumber == randomArray[i] is false you checkif (found). It leads to else branch which print"We did not find your number"`.
PS: Learn how to use debugger. It greatly simplify your life.
you forget the case , if there are more than two location of the same number, as it is just generating random number.
How about this :
boolean found = false;
for (int i=0; i < randomArray.length; i++) {
if (searchNumber == randomArray[i]) {
found = true;
System.out.println("We have found your number at index " + i);
}
}
if (!found) {
System.out.println("We did not find your number");
}
I've created a bank. I need this "Luhn" class to validate the social security number. The problem is, when the user inputs a number that's 1-9 digits, the program just stops. I want it to show a message like "Invalid input. Please try again". How do i do that?
package bank6;
import java.util.Scanner;
public class Luhn {
public static boolean checkLogin(String custPnr) {
int length = custPnr.length();
int sum = 0;
int pos = length-1;
for (int i = 1; i<=10; i++, pos--){
char tmp = custPnr.charAt(pos);
int num = Integer.parseInt(String.valueOf(tmp));
int produkt;
if (i % 2 != 0){
produkt = num * 1;
}else {
produkt = num * 2;
}
if ( produkt > 9 )
produkt -= 9;
sum += produkt;
}
boolean korrekt = (sum % 10) == 0;
if (korrekt){
System.out.println("Correct");
return true;
}else {
System.out.println("Invalid");
return false;
}
}
public static void main(String[] args) {
String pnr;
System.out.println("Welcome customer. Please login by using your "+ "birthdate (yymmddxxxx)");
Scanner input = new Scanner(System.in);
pnr = input.nextLine();
checkLogin(pnr);
}
}
EDIT;
Okay, i edited my code. But i still get errors. I Think im kind of retarded when i comes to coding. Im about to eat my own head soon.
I understand why i am getting infinite recurse but not how to fix it. And how do i fix so i dont have to print out the message to the customer two times?
i am trying to build a bank. To even get logged in to watch your accounts and so on you need to validate you're a Swedish citizen by typing in a Swedish social security number. This is a class were the validation of code is. The codes mission is to validate the security number. If the number is fake, the code will give an "false" return (bottom of code) and "true" return if its true. The problem i had in the start was that if someone typed in a 1-9 digit number then it would just crash. I wanted it to give a "Sorry, invalid input. Please try again" and then the user was supposed to be taken back to the login and try again.
I couldn't run the code from the main class so i had to make a main at the bottom of the page just to be able to fix the above problem.
That's were im at now.
package bank6;
import java.util.Scanner;
public class Luhn {
public static boolean checkLogin(String custPnr) {
String pnr;
System.out.println("Welcome customer. Please login by using your "
+ "birthdate (yymmddxxxx)");
Scanner input = new Scanner(System.in);
pnr = input.nextLine();
do {
System.out.println("Sorry, invalid input. Try again.");
checkLogin(pnr);
} while (pnr.length() != 10);
int length = custPnr.length();
int sum = 0;
int pos = length - 1;
for (int i = 1; i <= length; i++, pos--) {
char tmp = custPnr.charAt(pos);
int num = Integer.parseInt(String.valueOf(tmp));
int produkt;
if (i % 2 != 0) {
produkt = num * 1;
} else {
produkt = num * 2;
}
if (produkt > 9) {
produkt -= 9;
}
sum += produkt;
}
boolean korrekt = (sum % 10) == 0;
if (korrekt) {
System.out.println("Correct");
return true;
} else {
System.out.println("Invalid");
return false;
}
}
public static void main(String[] args) {
String pnr;
System.out.println("Welcome customer. Please login by using your "
+ "birthdate (yymmddxxxx)");
Scanner input = new Scanner(System.in);
pnr = input.nextLine();
checkLogin(pnr);
}
}
When you get the use input, just use an if-statement to check the length.
Example
String str = input.nextLine();
if(str.length() > 9){
// Print error message
}else{
checkLogin(str);
}
You could use a do-while loop and use str.length() > 9 as the condition so that it loops until a valid string of characters is entered. If you haven't used do-while loops, try googling them!
The problem is here:
for (int i = 1; i<=10; i++, pos--)
You always loop from 1 to 10 as if there were 10 characters. If the user inputs a String smaller than 10 characters, your "pos" will go beyond 0, and you will get a StringIndexOutOfBoundsException here:
char tmp = custPnr.charAt(pos);
Instead you should try:
for (int i = 1; i<=length; i++, pos--)
To check the length of the input before you perform the check:
String str = input.nextLine();
if(str.length() != 10){
System.out.println("Invalid input. Please try again");
return false;
}else{
checkLogin(str);
}