Java: linked list - (boolean [head=true, tail false]) - java

Condition 1: if you input more than or equal to 10 straight heads and are able to show in the input then the return is "Streak is found"
Condition 2: if you input less than 10 straight heads then the return is "Streak is broken"
However, I have a problem with condition 1 where it didn't execute to the output.
The code:
import java.util.LinkedList;
import java.util.Iterator;
import java.util.Scanner;
public class LinkedListProgram2
{
public static void main (String [] args)
{
Scanner input = new Scanner (System.in);
LinkedList<String> cointoss = new LinkedList<String>();
boolean head = true;
boolean tail = false;
boolean streak = true;
int streakcount = 0;
System.out.println ("Welcome to the Program #2 ");
//ask for the boolean value. It can be head and tail or true and false.
System.out.print ("\nEnter the boolean value (head=true, tail=false): ");
for (int i = 0; i<18; i++)
{
cointoss.add(input.next());
}
Iterator<String> it = cointoss.iterator();
while (it.hasNext())
{
if(streakcount >= 10)
{
streak = true;
System.out.println ("Streak is found! ");
break;
}
else if(streakcount < 10)
{
streak = false;
System.out.println ("Streak is broken! ");
break;
}
}
}
}

2 logic needs to be added atleast.
Increment the streakcount when true is found
Resetting the counter when false is found
You can have the outer if condition inside the while loop to print broken for every instance or let it be outside while to be printed at the end of loop
while (it.hasNext()) {
String val = it.next();
if (val.equals("true"))
streakcount++;
else
streakcount = 0;
if (streakcount >= 10) {
streak = true;
System.out.println("Streak is found! ");
break;
}
}
if (!streak) {
System.out.println("Streak is broken! ");
}

You miss something in your code, you need to check the input value, and increase streakcount, untested example code:
while (it.hasNext()) {
String val = it.next();
if (val.equals("true")) {
streakcount++;
if (streakcount >= 10) {
streak = true;
System.out.println ("Streak is found! ");
break;
}
}
else if (val.equals("false")) {
streak = false;
System.out.println ("Streak is broken! ");
break;
}
}
There are more action to do, check different input value, or do you need to find streak if it is not from starting array...

According to your description, this is actually a small program that counts specific strings, and doesn't even need LinkedList
I modified your code and now it should satisfy the two conditions you proposed
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
LinkedList<String> cointoss = new LinkedList<String>();
boolean head = true;
boolean tail = false;
boolean streak = true;
int streakcount = 0;
System.out.println("Welcome to the Program #2 ");
// ask for the boolean value. It can be head and tail or true and false.
System.out.println("Enter the boolean value (head=true, tail=false): ");
for (int i = 0; i < 18; i++) {
String next = input.next();
if (next.equals("true") || next.equals("head")) {
streakcount++;
}
cointoss.add(next);
}
if (streakcount >= 10) {
System.out.println("Streak is found! ");
} else {
System.out.println("Streak is broken! ");
}
}

Related

Scanner method .hasNextInt() and if statement - works only 1 time. For next loop - automatically (didn't wait any input) gives false

I tried to do an input check (need to take 3 numbers using Scanner).
Before that, I used a similar method (.hasNext(int)) in another task - everything worked fine. In this case, it doesn't work.
The first "while" loop works correctly, on the second loop .hasNextInt() returns false and loops the loop - not giving the opportunity to enter data.
boolean num1IsInt = false;
boolean num2IsInt = false;
boolean num3IsInt = false;
int scaicius1 = 0;
int scaicius2 = 0;
int scaicius3 = 0;
System.out.println("Įveskite 3 skaičiai, po viena after each press enter");
while (!num1IsInt) { //check first number is int
Scanner sc1 = new Scanner(System.in);
System.out.println("(1)Įveskyte pirmas skaicius");
if (sc1.hasNextInt()) {
scaicius1 = sc1.nextInt();
num1IsInt = true;
} else {
System.out.println("Not correct integer");
continue;
}
sc1.close();
}
while (!num2IsInt) { //check second number is int
Scanner sc2 = new Scanner(System.in);
System.out.println("(2)Įveskyte antras skaicius");
if (sc2.hasNextInt()) {
scaicius2 = sc2.nextInt();
num2IsInt = true;
} else {
System.out.println("Not correct integer");
continue;
}
sc2.close();
}
while (!num3IsInt) { //check third number is int
Scanner sc3 = new Scanner(System.in);
System.out.println("(3)Įveskyte trecias skaicius");
if (sc3.hasNextInt()) {
scaicius3 = sc3.nextInt();
num3IsInt = true;
sc3.close();
} else {
System.out.println("Not correct integer");
continue;
}
sc3.close();
}
System.out.println("First number = " + scaicius1);
System.out.println("First number = " + scaicius2);
System.out.println("First number = " + scaicius3);
Thank you - #Thomas Kläger. I change code like was at the begin (with only one Scanner, cose with 3 scanners it's didn't work) and add to all else statements reader for this "ghost element which loop my code".
boolean num1IsInt = false;
boolean num2IsInt = false;
boolean num3IsInt = false;
int scaicius1 = 0;
int scaicius2 = 0;
int scaicius3 = 0;
System.out.println("Įveskite 3 skaičiai, po viena after each press enter");
**Scanner sc = new Scanner(System.in);**
while (!num1IsInt) { //check first number is int
System.out.println("(1)Įveskyte pirmas skaicius");
if (sc.hasNextInt()) {
scaicius1 = sc.nextInt();
num1IsInt = true;
} else {
System.out.println("Not correct integer");
**sc.next();**
}
}
while (!num2IsInt) { //check second number is int
System.out.println("(2)Įveskyte antras skaicius");
if (sc.hasNextInt()) {
scaicius2 = sc.nextInt();
num2IsInt = true;
} else {
System.out.println("Not correct integer");
sc.next();
}
}
while (!num3IsInt) { //check third number is int
System.out.println("(3)Įveskyte trecias skaicius");
if (sc.hasNextInt()) {
scaicius3 = sc.nextInt();
num3IsInt = true;
} else {
System.out.println("Not correct integer");
sc.next();
}
}
sc.close();
System.out.println("First number = " + scaicius1);
System.out.println("First number = " + scaicius2);
System.out.println("First number = " + scaicius3);

While Loop Parsing Issue

I'm trying to give the user an infinite amount of inputs until they enter q. I'm using a while statement to run the program, but when the user tries to quit I get an error because the program would try and parse q as an integer. Any ideas on how I should change the structuring of this to prevent the error from occurring?
Scanner in = new Scanner(System.in);
System.out.println("What would you like your Fibonacci number to be?(enter q to quit)");
String value = in.next();
int trueValue;
while(!value.equalsIgnoreCase("q")) {
trueValue = Integer.parseInt(value);
Fibonacci userCase = new Fibonacci(trueValue);
System.out.println(userCase.calculateFibonacci(userCase.getCaseValue()));
System.out.println("Please enter another number.");
value = in.next();
trueValue = Integer.parseInt(value);
}
If it matters, here are the methods being called within the loop.
public int calculateFibonacci(int caseValue) {
if(caseValue == 0)
return 0;
else if(caseValue == 1)
return 1;
else
return calculateFibonacci(caseValue-1) + calculateFibonacci(caseValue-2);
}
public int getCaseValue()
{
return caseValue;
}
You can remove the last
trueValue = Integer.parseInt(value);
since you are already doing that at the start of the loop.
do{ getting the user value before checking } while(checking if it's ok);
/* https://stackoverflow.com/questions/40519580/trying-to-determine-if-a-string-is-an-integer */
private boolean isInteger(String str) {
if(str == null || str.trim().isEmpty()) {
return false;
}
for (int i = 0; i < str.length(); i++) {
if(!Character.isDigit(str.charAt(i))) {
return false;
}
}
return true;
}
public static String check(Scanner in) {
String value;
do {
System.out.println("Please enter a number or q to quit.");
value = in.next();
} while(!value.equalsIgnoreCase("q") && !isInteger(value));
return value;
}
public static void main (String[] args) {
Scanner in = new Scanner(System.in);
String value = check(in);
while(!value.equalsIgnoreCase("q")) {
Fibonacci userCase = new Fibonacci(Integer.parseInt(value));
System.out.println(userCase.calculateFibonacci(userCase.getCaseValue()));
value = check(in);
}
in.close();
}

Java - code keeps returning 'error: incompatible types: Object cannot be converted to int'

Inside my code, I am trying to compare the last element of an array list to a random number, but I keep getting the error "incompatible types: Object cannot be converted to int". I cannot seem to find a solution. The problem in question occurs at the boolean class 'checkLastGuess'.
import java.util.Scanner;
import java.util.Random;
import java.util.ArrayList;
public class GuessingGame
{
int numToGuess = new Random().nextInt(10);
ArrayList guesses = new ArrayList();
void getGuess()
{
Scanner keyboard = new Scanner(System.in);
boolean valid = false;
int userGuess = 0;
while (valid == false)
{
System.out.print("What is your guess: ");
String num = keyboard.next();
char new_num = num.charAt(0);
if (Character.isDigit(new_num))
{
userGuess = Integer.parseInt(num);
if (userGuess >= 0 && userGuess < 10)
{
guesses.add(userGuess);
valid = true;
}
else
{
System.out.println("Invalid guess, please enter a number between 0 and 9.");
}
}
else
{
System.out.println("Invalid guess, please enter digit.");
}
}
}
void printGuesses() {
int list_length = guesses.size();
System.out.print("Your guesses: ");
for (int counter = 0; counter < list_length; counter++)
{
System.out.print(guesses.get(counter) + " ");
}
System.out.println();
}
boolean checkLastGuess()
{
int numToTest = guesses.get(guesses.size()-1);
if (numToTest == numToGuess)
{
return true;
}
else
{
return false;
}
}
}
The code is then ran through the following test program
public class GuessingGameTest {
public static void main(String[] args) {
GuessingGame game = new GuessingGame();
System.out.println("Number to guess: " + game.numToGuess);
boolean guessedNumber = false;
while (!guessedNumber) {
game.getGuess();
guessedNumber = game.checkLastGuess();
}
}
}
You're not initializing the arraylist correctly. Change
ArrayList guesses = new ArrayList();
to
ArrayList<Integer> guesses = new ArrayList<Integer>();
Arraylists are generic (ArrayList<E>) in that they require an object to be specified in their construction so that you know what is in the arraylist.

How to use do-while loop to check user input again?

I want to add a loop to my program so that when a user enters an incorrect name it goes back to the start of the program and asks them to enter their name again. I think I need a do-while loop but I am not sure how to implement it with the if statements and boolean already included. I want the user to be only have three entries and if they get it wrong three times then the program closes.
import java.util.Scanner;
public class Username
{
public static void main(String[] args)
{
{
Scanner kb = new Scanner(System.in);
// array containing usernames
String[] name = {"barry", "matty", "olly", "joey"}; // elements in array
System.out.println("Enter your name");
String name1 = kb.nextLine();
boolean b = true;
for (int i = 0; i < name.length; i++)
{
if (name[i].equals(name1))
{
System.out.println("you are verified you may use the lift");
b = false;
break;// to stop loop checking names
}
}
if (b)
{
System.out.println("Invalid entry 2 attempts remaining, try again");
}
}
You can use a condition in the while loop. Something along the lines of:
boolean b = false;
while(!b){
System.out.println("Enter your name");
String name1 = kb.nextLine();
for (int i = 0; i < name.length; i++) {
if (name[i].equals(name1)) {
b = true;
System.out.println("you are verified you may use the lift");
}else{
System.out.println("Invalid entry 2 attempts remaining, try again");
}
}
}
The loop will quit if the name condition is fulfilled and will loop around if it is not.
You can do it like this:
int count = 0;
point:
do {
System.out.println("Enter your name");
String name1 = kb.nextLine();
boolean b = true;
for (int i = 0; i < name.length; i++) {
if (name[i].equals(name1)) {
System.out.println("you are verified you may use the lift");
b = false;
break point;// to stop loop checking names
}
}
if (b) {
count++;
System.out.println("Invalid entry 2 attempts remaining, try again");
}
while(!b || count <=3)
Use the following approach. Good thing is that it is a clean and robust solution.
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class AccessPoint
{
private Scanner scanner;
private List<String> usernames;
public AccessPoint()
{
scanner = new Scanner(System.in);
usernames = Arrays.asList("Barry", "Matty", "Olly", "Joey");
if (tryAccessForTimes(3))
{
allowAccess();
}
else
{
denyAccess();
}
scanner.close();
}
public static void main(String[] args)
{
new AccessPoint();
}
private boolean tryAccessForTimes(int times)
{
boolean accessAllowed = false;
for (int tryIndex = 1; tryIndex <= times && !accessAllowed; tryIndex++)
{
String userInput = getUserName();
for (String userName : usernames)
{
if (userName.equals(userInput))
{
accessAllowed = true;
break;
}
}
if (!accessAllowed)
{
printNumberOfTriesLeft(times, tryIndex);
}
}
return accessAllowed;
}
private void printNumberOfTriesLeft(int times, int tryIndex)
{
int triesLeft = times - tryIndex;
if (triesLeft != 0)
{
System.out.println("You have " + triesLeft
+ (triesLeft == 1 ? " try" : " tries") + " left.");
}
}
private String getUserName()
{
System.out.print("Enter Username: ");
return scanner.nextLine();
}
private void allowAccess()
{
System.out.println("Access Granted. Allowed to use lift.");
}
private void denyAccess()
{
System.out.println("Access Denied.");
}
}
package com.loknath.lab;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class User1 {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
// array containing usernames
String[] name = {"zerr", "barry", "matty", "olly", "joey" }; // elements
String []temp=name;
Arrays.sort(temp);
while (true) {
System.out.println("Enter your name");
String name1 = kb.nextLine();
if (Arrays.binarySearch(temp,name1)>=0) {
System.out.println("you are verified you may use the lift");
break;
} else {
System.out.println("Not a verified user try again!");
}
}
System.out.println("Done");
}
}
output
Enter your name
loknath
Not a verified user try again!
Enter your name
chiku
Not a verified user try again!
Enter your name
zerr
you are verified you may use the lift
Done

Looping an array

void searchForPopulationChange()
{
String goAgain;
int input;
int searchCount = 0;
boolean found = false;
while(found == false){
System.out.println ("Enter the Number for Population Change to be found: ");
input = scan.nextInt();
for (searchCount = 0; searchCount < populationChange.length; searchCount++)
{
if (populationChange[searchCount] == input)
{
found = true;
System.out.print(""+countyNames[searchCount]+" County / City with a population of "+populationChange[searchCount]+" individuals\n");
}
}
}
}
}
hello!
I am working on a method that will take an users input,
lets say (5000) and search a data file with those corresponding numbers.
and return the corresponding number, and county that it corresponds with.
However, I am able to get this code to run to return the correct value,
but i am unable to get it to run when i enter an "incorrect" value.
Any pointers?
Thank you!
It's a bit unclear, but I assume you want something to handle if the input is incorrect (not an integer)? Use hasNextInt so you will only capture integers.
Scanner scanner = new Scanner(System.in);
while (!scanner.hasNextInt()) {
scanner.nextLine();
}
int num = scanner.nextInt();
This will keep looping the input until it is a valid integer. You can include a message in the loop reminding the user to input a correct number.
If you want something to display if your number has no match inside of the array, simply add code after your for block, if found == false. For example:
for (searchCount = 0; searchCount < populationChange.length; searchCount++)
{
if (populationChange[searchCount] == input)
{
found = true;
System.out.print(""+countyNames[searchCount]+" County / City with a population of "+populationChange[searchCount]+" individuals\n");
}
}
if (found == false) {
System.out.println("Error, No records found!");
}
Since found is still false, your while loop kicks in and prints your line requesting for input again.
EDIT: Since you seem to have problem adding these two concepts to your code, here's the whole function:
void searchForPopulationChange() {
String goAgain;
int input;
int searchCount = 0;
boolean found = false;
while(found == false){
System.out.println ("Enter the Number for Population Change to be found: ");
Scanner scanner = new Scanner(System.in);
while (!scanner.hasNextInt()) {
scanner.nextLine();
}
input = scanner.nextInt();
for (searchCount = 0; searchCount < populationChange.length; searchCount++)
{
if (populationChange[searchCount] == input)
{
found = true;
System.out.print(""+countyNames[searchCount]+" County / City with a population of "+populationChange[searchCount]+" individuals\n");
}
}
if (found == false) {
System.out.println("Error, No records found!");
}
}
}

Categories